zj
2024-06-03 287ac389edd047696d956afafdb855a93830bc0c
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
package com.nq.service.impl;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nq.common.ServerResponse;
import com.nq.dao.*;
import com.nq.pojo.*;
import com.nq.service.*;
import com.nq.utils.DateTimeUtil;
import com.nq.utils.HttpClientRequest;
import com.nq.utils.PropertiesUtil;
import com.nq.utils.redis.JsonUtil;
import com.nq.utils.redis.RedisShardedPoolUtils;
import com.nq.utils.stock.sina.SinaStockApi;
import com.nq.vo.foreigncurrency.ExchangeVO;
import com.nq.vo.position.PositionProfitVO;
import com.nq.vo.position.UserPendingorderVO;
import com.nq.vo.stock.MarketVO;
import com.nq.vo.stock.StockListVO;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
 
import static com.nq.utils.DateTimeUtil.getCurrentTimeMiao;
import static com.nq.utils.DateTimeUtil.getCurrentTimeMiaoZero;
 
 
/**
* @author Administrator
* @description 针对表【user_pendingorder】的数据库操作Service实现
* @createDate 2022-11-10 06:10:40
*/
@Service
@Slf4j
public class UserPendingorderServiceImpl extends ServiceImpl<UserPendingorderMapper, UserPendingorder>
    implements UserPendingorderService {
    @Autowired
    private UserPendingorderMapper userPendingorderMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IUserPositionService iUserPositionService;
    @Resource
    private SiteTaskLogMapper siteTaskLogMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private StockIndexMapper stockIndexMapper;
    @Autowired
    private IStockIndexService iStockIndexService;
    @Autowired
    private IUserIndexPositionService iUserIndexPositionService;
    @Autowired
    private IStockCoinService iStockCoinService;
    @Autowired
    private IStockFuturesService iStockFuturesService;
    @Autowired
    private ISiteSettingService iSiteSettingService;
    @Resource
    private UserPositionMapper userPositionMapper;
    @Override
    public ServerResponse addOrder(String stockId, Integer buyNum, Integer buyType, Integer lever, BigDecimal profitTarget, BigDecimal stopTarget, BigDecimal targetPrice, HttpServletRequest request) {
        User user = this.iUserService.getCurrentRefreshUser(request);
 
        if (user == null) {
            return ServerResponse.createByErrorMsg("Please log in first");
        }
        SiteSetting siteSetting = this.iSiteSettingService.getSiteSetting();
        if (buyNum.intValue() < siteSetting.getBuyMinNum().intValue()) {
            return ServerResponse.createByErrorMsg("The pending order failed, and the purchased quantity was less than" + siteSetting
                    .getBuyMinNum() + "stocks");
        }
        if (buyNum.intValue() > siteSetting.getBuyMaxNum().intValue()) {
            return ServerResponse.createByErrorMsg("The pending order failed because the purchased quantity was greater than" + siteSetting
                    .getBuyMaxNum() + "stocks");
        }
        UserPendingorder userPendingorder = userPendingorderMapper.selectOne(new QueryWrapper<UserPendingorder>().eq("user_id", user.getId()).eq("stock_id", stockId).eq("status", 0));
        if(userPendingorder != null) {
            return ServerResponse.createByErrorMsg("Please do not repeat the order");
        }
 
         userPendingorder = new UserPendingorder();
        userPendingorder.setUserId(user.getId());
        userPendingorder.setStockId(stockId);
        userPendingorder.setBuyNum(buyNum);
        userPendingorder.setBuyType(buyType);
        userPendingorder.setLever(lever);
        userPendingorder.setProfitTarget(profitTarget);
        userPendingorder.setStopTarget(stopTarget);
        userPendingorder.setNowPrice(new BigDecimal(0));
        userPendingorder.setTargetPrice(targetPrice);
        userPendingorder.setAddTime(new Date());
        userPendingorder.setStatus(0);
        int ret = userPendingorderMapper.insert(userPendingorder);
        if (ret > 0) {
            return ServerResponse.createBySuccessMsg("If the pending order is successfully added, the order will be automatically placed if the order conditions are met");
        }
        return ServerResponse.createByErrorMsg("Add failure");
 
    }
    @Override
    public ServerResponse orderList(HttpServletRequest request) {
 
        String property = PropertiesUtil.getProperty("user.cookie.name");
        String header = request.getHeader(property);
//        log.info("header:{}",header);
        if (header != null) {
            String userJson = RedisShardedPoolUtils.get(header);
            User user = (User) JsonUtil.string2Obj(userJson, User.class);
//            log.info("user:{}",user);
            if (user != null) {
                List<UserPendingorder> userPendingorders = userPendingorderMapper.selectList(new QueryWrapper<UserPendingorder>().eq("user_id", user.getId()));
 
                List UserPendingorderList = new ArrayList();
 
 
                for (UserPendingorder userPendingorder : userPendingorders) {
                    UserPendingorderVO userPendingorderVO = new UserPendingorderVO();
                    //挂单-指数
                    if (userPendingorder.getStockId().contains("sh") || userPendingorder.getStockId().contains("sz")||userPendingorder.getStockId().contains("hk")||userPendingorder.getStockId().contains("us")) {
                        StockIndex model = stockIndexMapper.selectIndexByCode(userPendingorder.getStockId().replace("sh", "").replace("sz", "").replace("hk", "").replace("us", ""));
 
                        MarketVO marketVO = this.iStockIndexService.querySingleIndex(model.getIndexGid());
                        userPendingorderVO.setNowPrice(new BigDecimal(marketVO.getNowPrice()));
                        userPendingorderVO.setStockName(model.getIndexName());
                        userPendingorderVO.setStockId(model.getIndexGid());
 
                    } else {
                        //挂单-股票
                        Stock stock = stockMapper.findStockByCode(userPendingorder.getStockId());
                        StockListVO stockListVO = new StockListVO();
                        if (stock.getStockType().equals("hk")) {
                            String hk = RedisShardedPoolUtils.get(stock.getStockGid(), 1);
                            stockListVO = SinaStockApi.otherStockListVO(hk);
                        } else if (stock.getStockType().equals("us")) {
                            String us = RedisShardedPoolUtils.get(stock.getStockGid(), 2);
                            stockListVO = SinaStockApi.otherStockListVO(us);
                        } else {
                            stockListVO = SinaStockApi.assembleInStockListVO(
                                    stock);
                        }
                        String nowPrice = stockListVO.getNowPrice();
                        if (nowPrice == null) {
                            nowPrice = String.valueOf(0);
                        }
                        userPendingorderVO.setNowPrice(new BigDecimal(nowPrice));
                        userPendingorderVO.setStockName(stock.getStockName());
                        userPendingorderVO.setStockId(stock.getStockCode());
                    }
                    userPendingorderVO.setBuyNum(userPendingorder.getBuyNum());
                    userPendingorderVO.setBuyType(userPendingorder.getBuyType());
                    userPendingorderVO.setLever(userPendingorder.getLever());
                    userPendingorderVO.setProfitTarget(userPendingorder.getProfitTarget());
                    userPendingorderVO.setStopTarget(userPendingorder.getStopTarget());
                    userPendingorderVO.setTargetPrice(userPendingorder.getTargetPrice());
                    userPendingorderVO.setAddTime(userPendingorder.getAddTime());
                    userPendingorderVO.setStatus(userPendingorder.getStatus());
                    userPendingorderVO.setId(userPendingorder.getId());
                    userPendingorderVO.setProfitAndLose(getPositionProfitVO(userPendingorder).getProfitAndLose());
                    UserPendingorderList.add(userPendingorderVO);
                }
                return ServerResponse.createBySuccess(UserPendingorderList);
            }
        }
//        else {
//            String admin = PropertiesUtil.getProperty("admin.cookie.name");
//            String adminHeader = request.getHeader(admin);
//            log.info("adminHeader:{}",adminHeader);
//            if (adminHeader!=null) {
//                String adminJson = RedisShardedPoolUtils.get(adminHeader);
//                SiteAdmin siteAdmin = JsonUtil.string2Obj(adminJson, SiteAdmin.class);
//                log.info("siteAdmin:{}",siteAdmin);
//                if (siteAdmin != null) {
//
//                    return ServerResponse.createBySuccess();
//                }
//            }
//
//        }
 
        return ServerResponse.createByErrorMsg("数据异常");
 
    }
 
 
    public PositionProfitVO getPositionProfitVO(UserPendingorder position) {
        BigDecimal profitAndLose = new BigDecimal("0");
        BigDecimal allProfitAndLose = new BigDecimal("0");
        String nowPrice = "";
 
 
            Stock stock  = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code",position.getStockId()));
            StockListVO stockListVO = SinaStockApi.assembleInStockListVO(stock);
            nowPrice = stockListVO.getNowPrice();
            if (nowPrice == null){
                nowPrice = String.valueOf(0);
            }
        BigDecimal subPrice = (new BigDecimal(nowPrice)).subtract(position.getTargetPrice());
        profitAndLose = subPrice.multiply(new BigDecimal(position.getBuyNum().intValue()));
        PositionProfitVO positionProfitVO = new PositionProfitVO();
        positionProfitVO.setProfitAndLose(profitAndLose);
        positionProfitVO.setAllProfitAndLose(allProfitAndLose);
        positionProfitVO.setNowPrice(nowPrice);
 
        return positionProfitVO;
    }
 
    @Override
    @Transactional
    public void orderTask() {
 
        List<UserPendingorder> userPendingorders = userPendingorderMapper.selectList(new QueryWrapper<UserPendingorder>().eq("status", 0));
        log.info("当前有挂单的用户数量 为 {}", Integer.valueOf(userPendingorders.size()));
 
        for (int i = 0; i < userPendingorders.size(); i++) {
//            log.info("=====================");
            Integer userId = userPendingorders.get(i).getUserId();
            User user = this.userMapper.selectByPrimaryKey(userId);
            if (user == null) {
                continue;
            }
            List<UserPendingorder> userPendingorderList = userPendingorderMapper.selectList(new QueryWrapper<UserPendingorder>().eq("user_id", userId).eq("status", 0));
            if (userPendingorderList == null) {
                continue;
            }
 
            log.info("用户id = {} 姓名 = {} 已挂单数: {}", new Object[]{userId, user.getRealName(), Integer.valueOf(userPendingorders.size())});
            BigDecimal enable_user_amt = user.getEnableAmt();
            BigDecimal all_freez_amt = new BigDecimal("0");
            String nowPrice = "";
            String code = "";
            Integer indexId = null;
            StockListVO stockListVO = new StockListVO();
            StockCoin stockCoin = new StockCoin();
            for (UserPendingorder userPendingorder : userPendingorderList) {
                    Stock stock = stockMapper.findStockByCode(userPendingorder.getStockId());
                    stockListVO = SinaStockApi.assembleInStockListVO(stock);
                    nowPrice = stockListVO.getNowPrice();
                    all_freez_amt = new BigDecimal(nowPrice).multiply(new BigDecimal(userPendingorder.getBuyNum())).divide(new BigDecimal(userPendingorder.getLever()), 2, 4);
                    code = stock.getStockCode();
                if (nowPrice == null) {
                    nowPrice = String.valueOf(0);
                }
                if (userPendingorder.getUserId() != null && userPendingorder.getStockId() != null && userPendingorder.getBuyNum() != null && userPendingorder.getBuyType() != null && userPendingorder.getLever() != null && userPendingorder.getTargetPrice() != null) {
                    int ret = userPendingorder.getBuyType().intValue() == 0 ? userPendingorder.getTargetPrice().compareTo(new BigDecimal(nowPrice)) : new BigDecimal(nowPrice).compareTo(userPendingorder.getTargetPrice());
                    //当前时间String
                    String buyTime = DateTimeUtil.dateToStr(new Date());
                    if (ret <= 0) {
                        if (code != null && !"".equals(code)) {
                            try {
                                if(new BigDecimal(nowPrice).compareTo(userPendingorder.getTargetPrice())==0){
                                    this.iUserPositionService.create(userPendingorder.getUserId(),
                                            code, nowPrice, buyTime, userPendingorder.getBuyNum(),
                                            userPendingorder.getBuyType(), userPendingorder.getLever(),
                                            userPendingorder.getProfitTarget(),
                                            userPendingorder.getStopTarget());
                                    userPendingorder.setStatus(1);
                                    this.userPendingorderMapper.updateById(userPendingorder);
                                    SiteTaskLog siteTaskLog = new SiteTaskLog();
                                    siteTaskLog.setTaskType("股票挂单转持仓");
                                    String accountType = (user.getAccountType() == 0) ? "正式用户" : "模拟用户";
                                    String taskcnt = accountType + "-" + user.getRealName() + "挂单[达到目标价格] 用户id = " + user.getId() + ", 可用资金 = " + enable_user_amt + "冻结保证金 = " + all_freez_amt + ", 目标价格 = " + userPendingorder.getTargetPrice() + ",现价" + nowPrice + ", 涨跌:" + (userPendingorder.getBuyType().intValue() == 0 ? "涨" : "跌");
                                    siteTaskLog.setTaskCnt(taskcnt);
                                    String tasktarget = "此次挂单买入id:" + userPendingorder.getId();
                                    siteTaskLog.setTaskTarget(tasktarget);
                                    siteTaskLog.setAddTime(new Date());
                                    siteTaskLog.setIsSuccess(0);
                                    siteTaskLog.setErrorMsg("");
                                    int insertTaskCount = this.siteTaskLogMapper.insert(siteTaskLog);
                                    if (insertTaskCount > 0) {
                                        log.info("挂单task任务成功");
                                    } else {
                                        log.info("挂单task任务失败");
                                    }
                                }
                            } catch (Exception e) {
                                log.error("股票挂单任务失败...");
                                userPendingorder.setStatus(2);
                                this.userPendingorderMapper.updateById(userPendingorder);
                            }
                        }
 
                    }
 
                }
 
            }
 
        }
        log.info("===========挂单结束==========");
    }
 
    //删除
    @Override
    public ServerResponse delOrder(Integer id, HttpServletRequest request) {
        String property = PropertiesUtil.getProperty("user.cookie.name");
        String header = request.getHeader(property);
        if (header != null) {
            String userJson = RedisShardedPoolUtils.get(header);
            User user = (User) JsonUtil.string2Obj(userJson, User.class);
            UserPendingorder userPendingorder = this.userPendingorderMapper.selectById(id);
            if (userPendingorder == null) {
                return ServerResponse.createByErrorMsg("The pending order does not exist");
            }
            if (user.getId().intValue() != userPendingorder.getUserId().intValue()) {
                return ServerResponse.createByErrorMsg("The pending order does not belong to you");
            }
            int delCount = this.userPendingorderMapper.deleteById(id);
            if (delCount > 0) {
                return ServerResponse.createByErrorMsg("Successfully deleted");
            }
            return ServerResponse.createByErrorMsg("Deletion failure");
        }
 
        return ServerResponse.createByErrorMsg("Please log in");
    }
 
 
    @Override
    public ServerResponse orderListByAdmin(int pageNum, int pageSize, String keywords, String status, HttpServletRequest request) {
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<UserPendingorder> queryWrapper = new QueryWrapper();
        if (keywords != null && !keywords.equals("")) {
            queryWrapper.like("stock_id", keywords).or().like("user_id", keywords);
        }
        if (status != null && !status.equals("")) {
            queryWrapper.eq("status", status);
        }
        queryWrapper.orderByDesc("id");
        List<UserPendingorder> stockSubscribeList = this.userPendingorderMapper.selectList(queryWrapper);
        List UserPendingorderList = new ArrayList();
        for (UserPendingorder userPendingorder : stockSubscribeList) {
            UserPendingorderVO userPendingorderVO = new UserPendingorderVO();
            //挂单-指数
            if (userPendingorder.getStockId().contains("sh") || userPendingorder.getStockId().contains("sz")||userPendingorder.getStockId().contains("hk")||userPendingorder.getStockId().contains("us")) {
                StockIndex model = stockIndexMapper.selectIndexByCode(userPendingorder.getStockId().replace("sh", "").replace("sz", "").replace("hk", "").replace("us", ""));
 
                MarketVO marketVO = this.iStockIndexService.querySingleIndex(model.getIndexGid());
                userPendingorderVO.setNowPrice(new BigDecimal(marketVO.getNowPrice()));
                userPendingorderVO.setStockName(model.getIndexName());
                userPendingorderVO.setStockId(model.getIndexGid());
 
            } else {
                //挂单-股票
                Stock stock = stockMapper.findStockByCode(userPendingorder.getStockId());
                StockListVO stockListVO = new StockListVO();
                if (stock.getStockType().equals("hk")) {
                    String hk = RedisShardedPoolUtils.get(stock.getStockGid(), 1);
                    stockListVO = SinaStockApi.otherStockListVO(hk);
                } else if (stock.getStockType().equals("us")) {
                    String us = RedisShardedPoolUtils.get(stock.getStockGid(), 2);
                    stockListVO = SinaStockApi.otherStockListVO(us);
                } else {
                    stockListVO = SinaStockApi.assembleInStockListVO(
                            stock);
                }
                String nowPrice = stockListVO.getNowPrice();
                if (nowPrice == null) {
                    nowPrice = String.valueOf(0);
                }
                userPendingorderVO.setNowPrice(new BigDecimal(nowPrice));
                userPendingorderVO.setStockName(stock.getStockName());
                userPendingorderVO.setStockId(stock.getStockCode());
            }
            userPendingorderVO.setBuyNum(userPendingorder.getBuyNum());
            userPendingorderVO.setBuyType(userPendingorder.getBuyType());
            userPendingorderVO.setLever(userPendingorder.getLever());
            userPendingorderVO.setProfitTarget(userPendingorder.getProfitTarget());
            userPendingorderVO.setStopTarget(userPendingorder.getStopTarget());
            userPendingorderVO.setTargetPrice(userPendingorder.getTargetPrice());
            userPendingorderVO.setAddTime(userPendingorder.getAddTime());
            userPendingorderVO.setStatus(userPendingorder.getStatus());
            userPendingorderVO.setId(userPendingorder.getId());
            UserPendingorderList.add(userPendingorderVO);
        }
        PageInfo pageInfo = new PageInfo(stockSubscribeList);
        pageInfo.setList(UserPendingorderList);
        return ServerResponse.createBySuccess(pageInfo);
    }
 
    @Override
    public ServerResponse updateOrderByAdmin(UserPendingorder userPendingorder) {
        if (userPendingorder.getId() == null) {
            return ServerResponse.createByErrorMsg("id不能为空");
        }
        int updateCount = this.userPendingorderMapper.updateById(userPendingorder);
        if (updateCount > 0) {
            return ServerResponse.createBySuccessMsg("修改成功");
        }
        return ServerResponse.createByErrorMsg("修改失败");
 
    }
 
    @Override
    public ServerResponse addOrderByAdmin(String phone, String buyNum,String code, String buyType, String lever, String targetPrice, HttpServletRequest request) {
        if (StringUtils.isBlank(phone)||StringUtils.isBlank(buyNum)||StringUtils.isBlank(buyType)||StringUtils.isBlank(lever)|| StringUtils.isBlank(targetPrice)){
            return ServerResponse.createByErrorMsg("参数不能为空");
        }
 
        User user = this.userMapper.selectOne(new QueryWrapper<User>().eq("phone", phone));
        if (user == null) {
            return ServerResponse.createByErrorMsg("用户不存在");
        }
        Stock stock = stockMapper.findStockByCode(code);
        if (stock == null) {
            return ServerResponse.createByErrorMsg("股票不存在");
        }
        UserPendingorder userPendingorder = new UserPendingorder();
        userPendingorder.setUserId(user.getId());
        userPendingorder.setStockId(code);
        userPendingorder.setBuyNum(Integer.valueOf(buyNum));
        userPendingorder.setBuyType(Integer.valueOf(buyType));
        userPendingorder.setLever(Integer.valueOf(lever));
        userPendingorder.setTargetPrice(new BigDecimal(targetPrice));
        userPendingorder.setAddTime(new Date());
        userPendingorder.setStatus(0);
        userPendingorder.setNowPrice(new BigDecimal(0));
        int insert = this.userPendingorderMapper.insert(userPendingorder);
        if (insert > 0) {
            return ServerResponse.createBySuccessMsg("添加成功");
        }
        return ServerResponse.createByErrorMsg("添加失败");
 
    }
 
    @Override
    public ServerResponse delOrderByAdmin(Integer id) {
        if (id == null) {
            return ServerResponse.createByErrorMsg("id不能为空");
        }
        int delete = this.userPendingorderMapper.deleteById(id);
        if (delete > 0) {
            return ServerResponse.createBySuccessMsg("删除成功");
        }
        return ServerResponse.createByErrorMsg("删除失败");
    }
}