lishouyi
2023-05-25 b24677ee3bc1a1605088c4ddfae2bf35a4affbb6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
package com.stylefeng.guns.modular.api;
 
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.intuit.ipp.core.IEntity;
import com.intuit.ipp.data.*;
import com.intuit.ipp.exception.FMSException;
import com.intuit.ipp.services.DataService;
import com.intuit.ipp.services.QueryResult;
import com.intuit.oauth2.data.BearerTokenResponse;
import com.intuit.oauth2.exception.OAuthException;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.core.util.Convert;
import com.stylefeng.guns.core.util.JwtTokenUtil;
import com.stylefeng.guns.core.util.MD5Util;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.dao.TCompanyMapper;
import com.stylefeng.guns.modular.system.dao.UserMapper;
import com.stylefeng.guns.modular.system.model.TCompany;
import com.stylefeng.guns.modular.system.model.User;
import com.stylefeng.guns.modular.system.model.UserInfo;
import com.stylefeng.guns.modular.system.utils.EmailUtil;
import com.stylefeng.guns.modular.system.utils.InvoicesDataUploadUtil;
import com.stylefeng.guns.modular.system.utils.RedisUtil;
import com.stylefeng.guns.modular.system.utils.tips.SuccessTip;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;
 
/**
 * 接口控制器提供
 *
 * @author stylefeng
 * @Date 2018/7/20 23:39
 */
@RestController
@Api(tags = "登录")
@RequestMapping("/gunsApi")
@Slf4j
public class ApiController extends BaseController {
 
    @Autowired
    private UserMapper userMapper;
 
    @Resource
    private TCompanyMapper companyMapper;
 
    @Autowired
    private RedisUtil redisUtil;
 
    private final String  INVOICE_DATA = "CARINVOICE:";
 
    private static final String ACCOUNT_QUERY = "select * from Account where AccountType='%s' maxresults 1";
 
    /**
     * api登录接口,通过账号密码获取token
     */
 
    @PostMapping("/companyLogin")
    @ApiOperation(value = "卡车公司登录", notes = "卡车公司登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "password", value = "用户密码", required = true, dataType = "String")
    })
    public Object companyLogin(@RequestParam("username") String username,
                       @RequestParam("password") String password) {
 
 
        //获取数据库中的账号密码,准备比对
        List<TCompany> user = companyMapper.selectList(new EntityWrapper<TCompany>().eq("account",username));
        if (user.size()==0) {
            return new ErrorTip(500, "Account password error!");
        }
        if(user.get(0).getExpirationTime().getTime()<new Date().getTime()){
            return new ErrorTip(500, "Account Expire!");
        }
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(user, userInfo);
//        String credentials = user.getPassword();
//        String salt = user.getSalt();
//        ByteSource credentialsSalt = new Md5Hash(salt);
//        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
//                new ShiroUser(), credentials, credentialsSalt, "");
 
        //校验用户账号密码
//        HashedCredentialsMatcher md5CredentialsMatcher = new HashedCredentialsMatcher();
//        md5CredentialsMatcher.setHashAlgorithmName(ShiroKit.hashAlgorithmName);
//        md5CredentialsMatcher.setHashIterations(ShiroKit.hashIterations);
//        boolean passwordTrueFlag = md5CredentialsMatcher.doCredentialsMatch(
//                usernamePasswordToken, simpleAuthenticationInfo);
        String encrypt = MD5Util.encrypt(password);
        if(user.get(0).getStatus()==3){
            return new ErrorTip(500, "Your account has been frozen, please contact the platform!");
        }
        if (!encrypt.equals(user.get(0).getPassword())) {
            return new ErrorTip(500, "Account password error!");
        } else {
            TCompany company = user.get(0);
            HashMap<String, Object> result = new HashMap<>();
            result.put("token", JwtTokenUtil.generateToken(String.valueOf(company.getId())));
            result.put("company", company);
            return result;
        }
    }
 
 
 
 
    private ShiroUser shiroUser(User user) {
        ShiroUser shiroUser = new ShiroUser();
 
        shiroUser.setId(user.getId());
        shiroUser.setAccount(user.getAccount());
        shiroUser.setDeptId(user.getDeptid());
        shiroUser.setDeptName(ConstantFactory.me().getDeptName(user.getDeptid()));
        shiroUser.setName(user.getName());
 
        Integer[] roleArray = Convert.toIntArray(user.getRoleid());
        List<Integer> roleList = new ArrayList<Integer>();
        List<String> roleNameList = new ArrayList<String>();
        for (int roleId : roleArray) {
            roleList.add(roleId);
            roleNameList.add(ConstantFactory.me().getSingleRoleName(roleId));
        }
        shiroUser.setRoleList(roleList);
        shiroUser.setRoleNames(roleNameList);
 
        return shiroUser;
    }
 
    /**
     * 测试接口是否走鉴权
     */
    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public Object test() {
        return SUCCESS_TIP;
    }
 
 
    @PostMapping("/forget")
    @ApiOperation(value = "忘记密码", notes = "忘记密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "password", value = "用户密码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "String"),
    })
    public Object forget(@RequestParam("username") String username,
                         @RequestParam("password") String password,
                         @RequestParam("code") String code) {
        List<TCompany> user = companyMapper.selectList(new EntityWrapper<TCompany>().eq("account",username));
        String value = redisUtil.getValue(username);
        if(!code.equals(value)){
            return new ErrorTip(5001, "Verification code error!");
        }
        if (user.size()==0){
            return new ErrorTip(500, "Account does not exist!");
        }
        user.get(0).setPassword(MD5Util.encrypt(password));
        companyMapper.updateById(user.get(0));
        return new SuccessTip();
    }
 
 
    @PostMapping("/sendCode")
    @ApiOperation(value = "发送验证码", notes = "发送验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "email", value = "用户邮箱", required = true, dataType = "String"),
    })
    public Object sendCode(@RequestParam("email") String email) {
        String randomNumber = getRandomString(6);
        redisUtil.setStrValue(email,randomNumber,300);
        try {
            EmailUtil.sendMailGMail(email, randomNumber);
            return new com.stylefeng.guns.core.base.tips.SuccessTip();
        }catch (Exception e){
            e.printStackTrace();
            return new ErrorTip(500,"ERROR");
        }
    }
 
 
    private  String getRandomString(int length) {
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
 
        for(int i = 0; i < length; ++i) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
 
        return sb.toString();
    }
 
    @ApiOperation(value = "redirectURL接口",notes="redirectURL接口")
    @GetMapping(value = "/oauth2redirectOfCar")
    @ResponseBody
    @Transactional
    public String callbackIntuit(@RequestParam("code") String authCode,
                                 @RequestParam("state") String state,
                                 @RequestParam(value = "realmId", required = false) String realmId, HttpSession session) throws OAuthException {
        String accessToken = "";
        if (com.stylefeng.guns.core.util.ToolUtil.isEmpty(realmId)) {
            return new JSONObject().put("response","No realm ID.  QBO calls only work if the accounting scope was passed!").toString();
        }
        try {
            session.setAttribute("realmId", realmId);
            session.setAttribute("auth_code", authCode);
 
            // OAuth2PlatformClient client = factory.getOAuth2PlatformClient();
            // String redirectUri = factory.getRedirectUrl();
 
            BearerTokenResponse bearerTokenResponse = InvoicesDataUploadUtil.callBackFromOAuth(authCode);
            accessToken = bearerTokenResponse.getAccessToken();
            session.setAttribute("access_token", bearerTokenResponse.getAccessToken());
            session.setAttribute("refresh_token", bearerTokenResponse.getRefreshToken());
        }catch (Exception e){
            e.printStackTrace();
        }
        try {
 
            String value = redisUtil.getValue(INVOICE_DATA);
            log.info("value:{}",value);
            if (ToolUtil.isEmpty(value)){
                return "ERROR";
            }
            Gson gson = new Gson();
            JsonArray jsonArray = gson.fromJson(value, JsonArray.class);
            for (JsonElement jsonElement : jsonArray) {
                JsonObject asJsonObject = jsonElement.getAsJsonObject();
                String name = asJsonObject.get("name").getAsString();
                String amount = asJsonObject.get("amount").getAsString();
                String unitPrice = asJsonObject.get("unitPrice").getAsString();
                DataService service = InvoicesDataUploadUtil.getDataService(realmId, accessToken);
                Customer customer = getCustomerWithAllFields(name,"testconceptsample@mailinator.com");
                Customer savedCustomer = service.add(customer);
                Item item = getItemFields(service, unitPrice == null || unitPrice == "ABC Corporations" ? "0" : unitPrice );
                Item savedItem = service.add(item);
                Invoice invoice = getInvoiceFields(savedCustomer, savedItem, amount == null || amount == "" ? "0" : amount);
                Invoice savedInvoice = service.add(invoice);
                service.sendEmail(savedInvoice, customer.getPrimaryEmailAddr().getAddress());
                Payment payment = getPaymentFields(savedCustomer, savedInvoice);
                Payment savedPayment = service.add(payment);
                createResponse(savedPayment);
            }
 
        } catch (Exception e) {
            e.printStackTrace();
            throw new GunsException(BizExceptionEnum.CALLBACK_ERROR);
        }
        return "SUCCESS";
    }
 
 
 
 
    private Customer getCustomerWithAllFields(String companyName,String mailAddr) {
        Customer customer = new Customer();
        customer.setDisplayName(RandomStringUtils.randomAlphanumeric(6));
        customer.setCompanyName(companyName);
 
        EmailAddress emailAddr = new EmailAddress();
        emailAddr.setAddress(mailAddr);
        customer.setPrimaryEmailAddr(emailAddr);
 
        return customer;
    }
 
    private Item getItemFields(DataService service,String unitPrice) throws FMSException {
 
        Item item = new Item();
        item.setName("Item" + RandomStringUtils.randomAlphanumeric(5));
        item.setTaxable(false);
        item.setUnitPrice(unitPrice == null || unitPrice == "" ? BigDecimal.ZERO :new BigDecimal(unitPrice));
        item.setType(ItemTypeEnum.SERVICE);
 
        Account incomeAccount = getIncomeBankAccount(service);
        item.setIncomeAccountRef(createRef(incomeAccount));
 
        return item;
    }
 
    private Account getIncomeBankAccount(DataService service) throws FMSException {
        QueryResult queryResult = service.executeQuery(String.format(ACCOUNT_QUERY, AccountTypeEnum.INCOME.value()));
        List<? extends IEntity> entities = queryResult.getEntities();
        if(!entities.isEmpty()) {
            return (Account)entities.get(0);
        }
        return createIncomeBankAccount(service);
    }
 
    private ReferenceType createRef(IntuitEntity entity) {
        ReferenceType referenceType = new ReferenceType();
        referenceType.setValue(entity.getId());
        return referenceType;
    }
    private Account createIncomeBankAccount(DataService service) throws FMSException {
        Account account = new Account();
        account.setName("Incom" + RandomStringUtils.randomAlphabetic(5));
        account.setAccountType(AccountTypeEnum.INCOME);
 
        return service.add(account);
    }
 
    private Invoice getInvoiceFields(Customer customer, Item item,String amount) {
 
        Invoice invoice = new Invoice();
        invoice.setCustomerRef(createRef(customer));
        BigDecimal balance = invoice.getBalance();
        log.info("balance:{}",balance);
 
        List<Line> invLine = new ArrayList<Line>();
        Line line = new Line();
        line.setAmount(amount == null || amount == "" ? BigDecimal.ZERO : new BigDecimal(amount));
        line.setDetailType(LineDetailTypeEnum.SALES_ITEM_LINE_DETAIL);
 
        SalesItemLineDetail silDetails = new SalesItemLineDetail();
        silDetails.setItemRef(createRef(item));
 
        line.setSalesItemLineDetail(silDetails);
        invLine.add(line);
        invoice.setLine(invLine);
 
        return invoice;
    }
 
    private Payment getPaymentFields(Customer customer, Invoice invoice) {
 
        Payment payment = new Payment();
        payment.setCustomerRef(createRef(customer));
 
        payment.setTotalAmt(invoice.getTotalAmt());
 
        List<LinkedTxn> linkedTxnList = new ArrayList<LinkedTxn>();
        LinkedTxn linkedTxn = new LinkedTxn();
        linkedTxn.setTxnId(invoice.getId());
        linkedTxn.setTxnType(TxnTypeEnum.INVOICE.value());
        linkedTxnList.add(linkedTxn);
 
        Line line1 = new Line();
        line1.setAmount(invoice.getTotalAmt());
        line1.setLinkedTxn(linkedTxnList);
 
        List<Line> lineList = new ArrayList<Line>();
        lineList.add(line1);
        payment.setLine(lineList);
 
        return payment;
    }
 
 
    private String createResponse(Object entity) {
        ObjectMapper mapper = new ObjectMapper();
        String jsonInString;
        try {
            jsonInString = mapper.writeValueAsString(entity);
        } catch (Exception e) {
            return createErrorResponse(e);
        }
        return jsonInString;
    }
 
    private String createErrorResponse(Exception e) {
        log.error("Exception while calling QBO ", e);
        return new JSONObject().put("response","Failed").toString();
    }
 
}