Pu Zhibing
2025-03-26 cbf2486983b77a27af9968bbb362cb8d43789115
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
package com.ruoyi.other.controller;
 
 
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.account.api.feignClient.AppUserClient;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.other.api.domain.Shop;
import com.ruoyi.other.api.domain.ShopBalanceStatement;
import com.ruoyi.other.api.domain.ShopWithdraw;
import com.ruoyi.other.service.ShopBalanceStatementService;
import com.ruoyi.other.service.ShopService;
import com.ruoyi.other.service.ShopWithdrawService;
import com.ruoyi.other.util.payment.TransferUtil;
import com.ruoyi.other.util.payment.model.AccountBalanceQueryResult;
import com.ruoyi.other.util.payment.model.SinglePay;
import com.ruoyi.other.util.payment.model.SinglePayCallbackResult;
import com.ruoyi.other.util.payment.model.SinglePayResult;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.feignClient.SysUserClient;
import com.ruoyi.system.api.model.LoginUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
 
/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author luodangjia
 * @since 2024-11-20
 */
@RestController
@RequestMapping("/shop-withdraw")
@Api(tags = {"管理后台-门店管理-提现管理"})
public class ShopWithdrawController {
 
    @Resource
    private ShopWithdrawService shopWithdrawService;
    @Resource
    private ShopService shopService;
    @Resource
    private TokenService tokenService;
    
    @Resource
    private ShopBalanceStatementService shopBalanceStatementService;
    
    @Resource
    private AppUserClient appUserClient;
 
    @Resource
    private SysUserClient sysUserClient;
 
 
    @GetMapping("/getShopById")
    @ApiOperation("通过门店id获取账户信息回填")
    public R<Shop> getShopById(Integer id) {
        return R.ok(shopService.getById(id));
    }
 
    /**
     * 提现申请列表
     */
    @GetMapping("/list")
    @ApiOperation("提现申请列表")
    public R<IPage<ShopWithdraw>> list(@ApiParam("页码") @RequestParam Integer pageNum,
                         @ApiParam("每一页数据大小") Integer pageSize,
                         ShopWithdraw shopWithdraw) {
        List<Shop> list = shopService.list(new LambdaUpdateWrapper<Shop>()
                .like(StringUtils.isNotEmpty(shopWithdraw.getShopName()), Shop::getName, shopWithdraw.getShopName())
                .eq(Shop::getDelFlag, 0));
        List<Integer> collect1 = list.stream().map(Shop::getId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect1)){
            return R.ok(Page.of(pageNum, pageSize));
        }
        Page<ShopWithdraw> page = shopWithdrawService.page(Page.of(pageNum, pageSize), new LambdaQueryWrapper<ShopWithdraw>()
                .in(collect1.size() > 0, ShopWithdraw::getShopId, collect1)
        .orderByDesc(ShopWithdraw::getCreateTime));
        List<ShopWithdraw> records = page.getRecords();
        List<Integer> collect = records.stream().map(ShopWithdraw::getShopId).collect(Collectors.toList());
        List<Shop> shops = null;
        if(collect.size() > 0){
            shops = shopService.listByIds(collect);
        }
        for(ShopWithdraw item : records){
            Optional<Shop> first = shops.stream().filter(s -> s.getId().equals(item.getShopId())).findFirst();
            if(first.isPresent()){
                item.setShopName(first.get().getName());
            }
            item.setIdStr(item.getId().toString());
        }
        return R.ok(page);
    }
 
    @GetMapping("/shop/list")
    @ApiOperation(value = "提现申请列表", notes = "提现申请列表", tags = {"门店后台"})
    public R<IPage<ShopWithdraw>> shoplist(@ApiParam("页码") @RequestParam Integer pageNum,
                                       @ApiParam("每一页数据大小") Integer pageSize,
                                       ShopWithdraw shopWithdraw) {
        LoginUser loginUser = tokenService.getLoginUser();
        SysUser sysUser = sysUserClient.getSysUser(loginUser.getUserid()).getData();
        Page<ShopWithdraw> page = shopWithdrawService.page(Page.of(pageNum, pageSize), new LambdaQueryWrapper<ShopWithdraw>()
                        .eq(sysUser!=null,ShopWithdraw::getShopId,sysUser.getObjectId())
                        .eq(shopWithdraw.getAuditStatus()!=null,ShopWithdraw::getAuditStatus,shopWithdraw.getAuditStatus())
                        .orderByDesc(ShopWithdraw::getCreateTime)
                );
        page.getRecords().forEach(s->s.setIdStr(s.getId().toString()));
        return R.ok(page);
    }
 
    @GetMapping("/shop/info")
    @ApiOperation(value = "提现申请列表上方数据", notes = "提现申请列表", tags = {"门店后台"})
    public R<Shop> shopCommissionStatisticsinfo(){
        LoginUser loginUser = tokenService.getLoginUser();
        SysUser sysUser = sysUserClient.getSysUser(loginUser.getUserid()).getData();
        Shop byId = shopService.getById(sysUser.getObjectId());
        List<ShopWithdraw> list = shopWithdrawService.lambdaQuery()
                .eq(ShopWithdraw::getShopId, sysUser.getObjectId())
                .list();
 
 
        if (!list.isEmpty()){
            // 待审核列表
            List<ShopWithdraw> toBeReviewList = list.stream()
                    .filter(s -> s.getAuditStatus() == 0)
                    .collect(Collectors.toList());
            // 审核通过列表
            List<ShopWithdraw> passedReviewList = list.stream()
                    .filter(s -> s.getAuditStatus() == 1)
                    .collect(Collectors.toList());
 
            BigDecimal bigDecimal = toBeReviewList.stream().map(ShopWithdraw::getMoney).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
            byId.setWithdrawAuditMoney(bigDecimal);
 
            BigDecimal bigDecimal1 = passedReviewList.stream().map(ShopWithdraw::getMoney).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
            byId.setWithdrawMoney(bigDecimal1);
        }else {
            byId.setWithdrawAuditMoney(BigDecimal.ZERO);
        }
        return R.ok(byId);
    }
    
    @GetMapping("/shop/with")
    @ApiOperation(value = "提现申请", notes = "提现申请列表", tags = {"门店后台"})
    public R shopwith(@RequestParam BigDecimal money){
        LoginUser loginUser = tokenService.getLoginUser();
        SysUser sysUser = sysUserClient.getSysUser(loginUser.getUserid()).getData();
        baseWithdrawalApplication(money, sysUser.getUserId(), sysUser.getObjectId());
        return R.ok();
    }
 
    /**
     * 小程序端提现申请
     */
    @ApiOperation(value = "提现申请", notes = "提现申请", tags = {"小程序-个人中心-门店管理-门店钱包"})
    @GetMapping("/withdrawalApplication")
    @ResponseBody
    public R withdrawalApplication(@RequestParam BigDecimal money, @RequestParam Integer shopId) {
        LoginUser loginUser = tokenService.getLoginUserApplet();
        baseWithdrawalApplication(money, loginUser.getUserid(), shopId);
        return R.ok();
    }
 
    private void baseWithdrawalApplication(BigDecimal money, Long userId, Integer shopId) {
        Shop shop = shopService.getById(shopId);
        if (money.compareTo(BigDecimal.ZERO)==0){
            throw new ServiceException("提现金额必须大于零");
        }
        if (money.compareTo(shop.getCanWithdrawMoney())>0){
            throw new ServiceException("提现金额不能大于可提现金额");
        }
        if(StringUtils.isEmpty(shop.getReceiverAccountNoEnc())){
            throw new ServiceException("请完善账户信息后再申请提现!");
        }
        ShopWithdraw shopWithdraw = new ShopWithdraw();
        shopWithdraw.setShopId(shopId);
        shopWithdraw.setMoney(money);
        shopWithdraw.setAuditStatus(0);
        shopWithdraw.setStatus(1);
        shopWithdraw.setCreateTime(LocalDateTime.now());
        shopWithdrawService.save(shopWithdraw);
        //扣除账户余额及添加变动明细
        BigDecimal balance = shop.getBalance();
        BigDecimal canWithdrawMoney = shop.getCanWithdrawMoney();
        BigDecimal withdrawMoney = shop.getWithdrawMoney();
        shop.setBalance(balance.subtract(money).setScale(2, RoundingMode.HALF_EVEN));
        shop.setCanWithdrawMoney(canWithdrawMoney.subtract(money).setScale(2, RoundingMode.HALF_EVEN));
        shop.setWithdrawMoney(withdrawMoney.add(money).setScale(2, RoundingMode.HALF_EVEN));
        shopService.updateById(shop);
        //添加门店变动明细
        ShopBalanceStatement shopBalanceStatement = new ShopBalanceStatement();
        shopBalanceStatement.setShopId(shop.getId());
        shopBalanceStatement.setType(4);
        shopBalanceStatement.setVariableAmount(money);
        shopBalanceStatement.setCreateUserId(userId);
        shopBalanceStatement.setCreateTime(LocalDateTime.now());
        shopBalanceStatement.setObjectId(shopWithdraw.getId());
        shopBalanceStatement.setChangeDirection(-1);
        shopBalanceStatementService.save(shopBalanceStatement);
    }
 
 
 
    /**
     * 审核
     */
    @PostMapping("/audit")
    @ApiOperation("审核")
    public R<Void> audit(@RequestBody ShopWithdraw shopWithdraw) {
        LoginUser loginUser = tokenService.getLoginUser();
 
        ShopWithdraw shopWithdraw1 = shopWithdrawService.getById(shopWithdraw.getId());
        if(0 != shopWithdraw1.getAuditStatus()){
            return R.fail("不能重复审核");
        }
        Shop shop = shopService.getById(shopWithdraw1.getShopId());
        BigDecimal money = shopWithdraw1.getMoney();
        if(1 == shopWithdraw.getAuditStatus()){
            //先检查账户余额是否充足
            AccountBalanceQueryResult accountBalanceQueryResult = TransferUtil.accountBalanceQuery();
            if(null == accountBalanceQueryResult){
                return R.fail("查询账户余额出错");
            }
            Double useAbleSettAmount = accountBalanceQueryResult.getUseAbleSettAmount();
            if(useAbleSettAmount < (shopWithdraw1.getMoney().doubleValue() + 1)){
                return R.fail("账户可用余额不足,请先补充账户余额");
            }
            //银行卡转账
            SinglePay singlePay = new SinglePay();
            singlePay.setTradeMerchantNo(TransferUtil.sysTradeMerchantNo);
            singlePay.setMerchantOrderNo(shopWithdraw1.getId().toString());
            singlePay.setReceiverAccountNoEnc(shop.getReceiverAccountNoEnc());
            singlePay.setReceiverNameEnc(shop.getReceiverNameEnc());
            singlePay.setReceiverAccountType(shop.getReceiverAccountType());
            singlePay.setReceiverBankChannelNo(shop.getReceiverBankChannelNo());
            singlePay.setPaidAmount(shopWithdraw1.getMoney().doubleValue());
            singlePay.setPaidDesc("账户余额提现");
            singlePay.setPaidUse("208");
            singlePay.setCallbackUrl("/other/shop-withdraw/withdrawalCallback");
            SinglePayResult singlePayResult = TransferUtil.singlePay(singlePay);
            if(null == singlePayResult){
                return R.fail("转账失败");
            }
            shopWithdraw1.setStatus(1);
        }
        if(2 == shopWithdraw.getAuditStatus()){
            //回退金额和添加变动明细
            BigDecimal balance = shop.getBalance();
            BigDecimal canWithdrawMoney = shop.getCanWithdrawMoney();
            BigDecimal withdrawMoney = shop.getWithdrawMoney();
            shop.setBalance(balance.add(money).setScale(2, RoundingMode.HALF_EVEN));
            shop.setCanWithdrawMoney(canWithdrawMoney.add(money).setScale(2, RoundingMode.HALF_EVEN));
            shop.setWithdrawMoney(withdrawMoney.subtract(money).setScale(2, RoundingMode.HALF_EVEN));
            shopService.updateById(shop);
            //添加门店变动明细
            ShopBalanceStatement shopBalanceStatement = new ShopBalanceStatement();
            shopBalanceStatement.setShopId(shop.getId());
            shopBalanceStatement.setType(4);
            shopBalanceStatement.setVariableAmount(money);
            shopBalanceStatement.setCreateUserId(loginUser.getUserid());
            shopBalanceStatement.setCreateTime(LocalDateTime.now());
            shopBalanceStatement.setObjectId(shopWithdraw.getId());
            shopBalanceStatement.setChangeDirection(-1);
            shopBalanceStatementService.save(shopBalanceStatement);
        }
        shopWithdraw1.setAuditStatus(shopWithdraw.getAuditStatus());
        shopWithdraw1.setAuditUserId(loginUser.getUserid());
        shopWithdraw1.setAuditTime(LocalDateTime.now());
        shopWithdraw1.setAuditMsg(shopWithdraw.getAuditMsg());
        shopWithdrawService.updateById(shopWithdraw1);
        return R.ok();
    }
    
    
    
    /**
     * 提现审核通过后转账回调通知
     * @param singlePayCallbackResult
     */
    @ResponseBody
    @PostMapping("/withdrawalCallback")
    public Object withdrawalCallback(@RequestBody SinglePayCallbackResult singlePayCallbackResult){
        Integer status = singlePayCallbackResult.getStatus();
        String merchantOrderNo = singlePayCallbackResult.getMerchantOrderNo();
        ShopWithdraw shopWithdraw = shopWithdrawService.getById(merchantOrderNo);
        if(203 == status || 205 == status){
            if(1 == shopWithdraw.getStatus()){
                shopWithdraw.setStatus(2);
                shopWithdraw.setArrivalTime(LocalDateTime.now());
                shopWithdrawService.updateById(shopWithdraw);
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("statusCode", 2001);
            return jsonObject;
        }else{
            //回退金额和添加变动明细
            Shop shop = shopService.getById(shopWithdraw.getShopId());
            BigDecimal balance = shop.getBalance();
            BigDecimal canWithdrawMoney = shop.getCanWithdrawMoney();
            BigDecimal withdrawMoney = shop.getWithdrawMoney();
            shop.setBalance(balance.add(shopWithdraw.getMoney()).setScale(2, RoundingMode.HALF_EVEN));
            shop.setCanWithdrawMoney(canWithdrawMoney.add(shopWithdraw.getMoney()).setScale(2, RoundingMode.HALF_EVEN));
            shop.setWithdrawMoney(withdrawMoney.subtract(shopWithdraw.getMoney()).setScale(2, RoundingMode.HALF_EVEN));
            shopService.updateById(shop);
            //添加门店变动明细
            ShopBalanceStatement shopBalanceStatement = new ShopBalanceStatement();
            shopBalanceStatement.setShopId(shop.getId());
            shopBalanceStatement.setType(4);
            shopBalanceStatement.setVariableAmount(shopWithdraw.getMoney());
            shopBalanceStatement.setCreateUserId(shopWithdraw.getAuditUserId());
            shopBalanceStatement.setCreateTime(LocalDateTime.now());
            shopBalanceStatement.setObjectId(shopWithdraw.getId());
            shopBalanceStatement.setChangeDirection(-1);
            shopBalanceStatementService.save(shopBalanceStatement);
            shopWithdraw.setStatus(3);
            shopWithdraw.setRemark(singlePayCallbackResult.getErrorCodeDesc());
            shopWithdrawService.updateById(shopWithdraw);
 
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("statusCode", 2001);
            return jsonObject;
        }
    }
}