Jelajahi Sumber

feat: 解析收款对账账单手续费和扣费后净额

yonge 1 Minggu lalu
induk
melakukan
4fb9da6d86

+ 18 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dto/ReceiptChargesDto.java

@@ -0,0 +1,18 @@
+package com.ym.mec.biz.dal.dto;
+
+import lombok.Data;
+
+import java.math.BigDecimal;
+
+@Data
+public class ReceiptChargesDto {
+    private BigDecimal feeAmount;
+    private BigDecimal netAmount;
+
+    public static ReceiptChargesDto from(BigDecimal grossAmount, BigDecimal feeAmount) {
+        ReceiptChargesDto charges = new ReceiptChargesDto();
+        charges.setFeeAmount(feeAmount);
+        charges.setNetAmount(grossAmount.subtract(feeAmount));
+        return charges;
+    }
+}

+ 2 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/dto/ReceiptEntryDto.java

@@ -18,4 +18,6 @@ public class ReceiptEntryDto {
     private String time;
     private String description;
     private BigDecimal amount;
+    @JsonInclude(JsonInclude.Include.NON_NULL)
+    private ReceiptChargesDto charges;
 }

+ 4 - 0
mec-biz/src/main/java/com/ym/mec/biz/dal/vo/ReceiptChannelVo.java

@@ -1,5 +1,7 @@
 package com.ym.mec.biz.dal.vo;
 
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.ym.mec.biz.dal.dto.ReceiptChargesDto;
 import lombok.Data;
 
 import java.math.BigDecimal;
@@ -14,5 +16,7 @@ public class ReceiptChannelVo {
     private Integer thirdCount;
     private BigDecimal systemAmount = BigDecimal.ZERO;
     private BigDecimal thirdAmount;
+    @JsonInclude(JsonInclude.Include.NON_NULL)
+    private ReceiptChargesDto charges;
     private BigDecimal availableBalance;
 }

+ 6 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/impl/receipt/ReceiptLedger.java

@@ -1,6 +1,7 @@
 package com.ym.mec.biz.service.impl.receipt;
 
 import com.ym.mec.biz.dal.dto.ReceiptBillDto;
+import com.ym.mec.biz.dal.dto.ReceiptChargesDto;
 import com.ym.mec.biz.dal.dto.ReceiptEntryDto;
 import com.ym.mec.biz.dal.vo.ReceiptChannelVo;
 import com.ym.mec.biz.dal.vo.ReceiptDifferenceVo;
@@ -57,11 +58,16 @@ public final class ReceiptLedger {
             }
             channel.setThirdCount(bill.getEntries().size());
             channel.setThirdAmount(BigDecimal.ZERO);
+            BigDecimal totalFee = BigDecimal.ZERO;
+            boolean feesKnown = true;
             for (ReceiptEntryDto row : bill.getEntries()) {
                 if (!name.equals(row.getChannel())) throw new IllegalArgumentException("账单与渠道不一致");
                 channel.setThirdAmount(channel.getThirdAmount().add(paymentAmount(row)));
+                if (row.getCharges() == null) feesKnown = false;
+                else totalFee = totalFee.add(row.getCharges().getFeeAmount());
                 rows.add(row);
             }
+            if (feesKnown) channel.setCharges(ReceiptChargesDto.from(channel.getThirdAmount(), totalFee));
             count += channel.getThirdCount();
             amount = amount.add(channel.getThirdAmount());
         }

+ 7 - 0
mec-biz/src/main/java/com/ym/mec/biz/service/impl/receipt/gateway/BillFiles.java

@@ -1,5 +1,6 @@
 package com.ym.mec.biz.service.impl.receipt.gateway;
 
+import com.ym.mec.biz.dal.dto.ReceiptChargesDto;
 import com.ym.mec.biz.dal.dto.ReceiptEntryDto;
 
 import java.time.*;
@@ -137,6 +138,12 @@ final class BillFiles {
             if (entry.getOrderNo().isEmpty() || entry.getTradeNo().isEmpty()) throw invalid();
             entry.setId(channel + ":" + entry.getTradeNo());
             entry.setAmount(money(cells.get(columns.get(amount))));
+            String fee = optional(columns, cells, ada ? "手续费金额" : wx ? "手续费" : "服务费(元)");
+            if (!fee.isEmpty()) {
+                if (!ada && !wx && fee.startsWith("-")) fee = fee.substring(1);
+                if (!fee.matches("[0-9]{1,16}(\\.[0-9]{1,2}0*)?")) throw new BillHttp.Failure("账单手续费金额无效");
+                entry.setCharges(ReceiptChargesDto.from(entry.getAmount(), new BigDecimal(fee).setScale(2)));
+            }
             entry.setTime(TIME.format(paid));
             entry.setDescription(optional(columns, cells, ada ? "交易类型" : "商品名称"));
             entries.add(entry);

+ 19 - 0
mec-biz/src/test/java/com/ym/mec/biz/service/impl/receipt/ReceiptLedgerTest.java

@@ -1,6 +1,7 @@
 package com.ym.mec.biz.service.impl.receipt;
 
 import com.ym.mec.biz.dal.dto.ReceiptBillDto;
+import com.ym.mec.biz.dal.dto.ReceiptChargesDto;
 import com.ym.mec.biz.dal.dto.ReceiptEntryDto;
 import com.ym.mec.biz.dal.vo.ReceiptReconcileResultVo;
 import org.junit.Test;
@@ -38,6 +39,24 @@ public class ReceiptLedgerTest {
         return ReceiptLedger.compare("12", day, orders, bills);
     }
 
+    @Test public void feesDoNotChangeGrossMatchingOrBecomeZeroWhenMissing() {
+        ReceiptEntryDto paid = entry("HUIFU", "order", "charge", "12.34");
+        ReceiptEntryDto third = entry("HUIFU", "order", "charge", "12.34");
+        third.setCharges(ReceiptChargesDto.from(third.getAmount(), new BigDecimal("0.01")));
+        ReceiptReconcileResultVo matched = compare(Collections.singletonList(paid), third);
+        assertTrue(matched.getDifferences().isEmpty());
+        assertEquals(Integer.valueOf(0), matched.getDifferenceCount());
+        assertEquals(new BigDecimal("12.33"), matched.getChannels().get(0).getCharges().getNetAmount());
+        assertEquals(BigDecimal.ZERO, matched.getChannels().get(1).getCharges().getFeeAmount());
+        ReceiptEntryDto extra = entry("HUIFU", "extra", "charge2", "1.00");
+        assertNull(compare(Collections.singletonList(paid), third, extra).getChannels().get(0).getCharges());
+        extra.setCharges(ReceiptChargesDto.from(extra.getAmount(), new BigDecimal("0.02")));
+        ReceiptReconcileResultVo result = compare(Collections.singletonList(paid), third, extra);
+        assertEquals(new BigDecimal("0.03"), result.getChannels().get(0).getCharges().getFeeAmount());
+        assertEquals(new BigDecimal("13.31"), result.getChannels().get(0).getCharges().getNetAmount());
+        assertSame(extra, result.getDifferences().get(0).getThird());
+    }
+
     @Test public void remoteOnlyEvenWhenNoSystemPayments() {
         ReceiptReconcileResultVo result = compare(Collections.emptyList(), entry("WECHAT", "extra", "wx-1", "100.00"));
         assertEquals(0, result.getSystemCount());

+ 18 - 3
mec-biz/src/test/java/com/ym/mec/biz/service/impl/receipt/gateway/ReceiptBillGatewayTest.java

@@ -13,6 +13,7 @@ import com.microsvc.toolkit.middleware.payment.impl.WxPaymentServicePlugin;
 import com.microsvc.toolkit.middleware.payment.properties.PayConfigProperties;
 import com.microsvc.toolkit.middleware.payment.properties.PayConfigProperties.*;
 import com.ym.mec.biz.dal.dto.ReceiptBillDto;
+import com.ym.mec.biz.dal.dto.ReceiptChargesDto;
 import com.ym.mec.biz.dal.vo.ReceiptChannelVo;
 import com.ym.mec.biz.dal.vo.ReceiptReconcileResultVo;
 import com.ym.mec.biz.service.HfMerchantConfigService;
@@ -45,6 +46,20 @@ public class ReceiptBillGatewayTest {
     private static final String WX_CSV = "交易时间,商户号,商户订单号,微信订单号,交易状态,订单金额,货币种类\n`" + DATE + ",`10001,`order,`wx,`SUCCESS,`12.34,`CNY\n总交易单数,总交易额\n`1,`12.34\n";
     private static final String ALI_CSV = "#商户ID:" + PID + "\n支付宝交易号,商户订单号,业务类型,商品名称,完成时间,订单金额(元)\nali,order,交易,\"课程,一期\"," + DATE + ",12.34\nrefund,order,退款,课程," + DATE + ",-2.00\n#业务明细列表结束\n";
     private static final String ADA_CSV = "#支付流水记录\n交易时间,app_id,支付ID,商户订单号,交易类型,交易金额,手续费金额,货币种类,交易状态,第三方订单号,支付完成时间\n20261119150401,ada,charge,order,支付宝正扫,12.34,0.01,cny,S,,\n20261119150401,other,foreign,other,支付宝正扫,9.00,0.01,cny,S,,\n20261119150401,ada,failed,other,支付宝正扫,9.00,0.01,cny,F,,\n#合计:3笔,共30.34元\n";
+    private static final String WX_MERCHANT = "10001";
+
+    @Test public void billFeesComeFromSuccessfulMerchantRows() throws Exception {
+        ReceiptChargesDto ada = BillFiles.parse("HUIFU", "ada", DAY, zip("Charge.csv", ADA_CSV, UTF_8)).get(0).getCharges();
+        assertEquals(new BigDecimal("0.01"), ada.getFeeAmount());
+        assertEquals(new BigDecimal("12.33"), ada.getNetAmount());
+        assertNull(BillFiles.parse("WECHAT", WX_MERCHANT, DAY, WX_CSV.getBytes(UTF_8)).get(0).getCharges());
+        String wx = WX_CSV.replace("货币种类", "货币种类,手续费").replace("`CNY", "`CNY,`0.00000");
+        assertEquals(new BigDecimal("0.00"), BillFiles.parse("WECHAT", WX_MERCHANT, DAY, wx.getBytes(UTF_8)).get(0).getCharges().getFeeAmount());
+        String ali = ALI_CSV.replace("订单金额(元)", "订单金额(元),服务费(元)").replace(",12.34", ",12.34,-0.05").replace(",-2.00", ",-2.00,");
+        assertEquals(new BigDecimal("12.29"), BillFiles.parse("ALIPAY", PID, DAY,
+                zip("业务明细.csv", ali, Charset.forName("GBK"))).get(0).getCharges().getNetAmount());
+    }
+
     private static KeyPair platform;
     private static KeyPair merchant;
     private ReceiptPaymentAccounts accounts;
@@ -99,13 +114,13 @@ public class ReceiptBillGatewayTest {
         runtimeAccount.setRSAPrivateKey(key);
         Adapay.addMerConfig(runtimeAccount, MERCHANT_KEY);
         ali.setPrivateKey(key); ali.setPublicKey(pub); ali.setAppId("ali-app"); ali.setEnable(true);
-        wx.setMerchantId("10001"); wx.setEnable(true);
+        wx.setMerchantId(WX_MERCHANT); wx.setEnable(true);
         register("ALIPAY_101", ali, mock(BasePaymentService.class));
         WxPaymentServicePlugin plugin = mock(WxPaymentServicePlugin.class);
         register("WXPAY_101", wx, plugin);
         WxPayService sdk = mock(WxPayService.class);
         com.github.binarywang.wxpay.config.WxPayConfig runtime = new com.github.binarywang.wxpay.config.WxPayConfig();
-        runtime.setPrivateKey(merchant.getPrivate()); runtime.setMchId("10001"); runtime.setCertSerialNo("SERIAL");
+        runtime.setPrivateKey(merchant.getPrivate()); runtime.setMchId(WX_MERCHANT); runtime.setCertSerialNo("SERIAL");
         Verifier verifier = mock(Verifier.class);
         when(verifier.verify(anyString(), any(byte[].class), anyString())).thenAnswer(call ->
             "PLATFORM".equals(call.getArgument(0)) && BillCredentials.rsa(platform.getPublic()).verify(null,
@@ -147,7 +162,7 @@ public class ReceiptBillGatewayTest {
             Map<String,String> auth = new HashMap<>();
             Matcher matcher = Pattern.compile("([a-z_]+)=\"([^\"]+)\"").matcher(headers.get("Authorization"));
             while (matcher.find()) auth.put(matcher.group(1), matcher.group(2));
-            assertEquals("10001", auth.get("mchid"));
+            assertEquals(WX_MERCHANT, auth.get("mchid"));
             assertEquals("SERIAL", auth.get("serial_no"));
             String path = uri.getRawPath() + (uri.getRawQuery() == null ? "" : "?" + uri.getRawQuery());
             verify("SHA256withRSA", "GET\n" + path + "\n" + auth.get("timestamp") + "\n" + auth.get("nonce_str") + "\n\n", auth.get("signature"));