OrderInvoiceService.java 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. package com.ruoyi.app.order;
  2. import cn.hutool.core.util.StrUtil;
  3. import com.alibaba.fastjson.JSONArray;
  4. import com.alibaba.fastjson2.JSONObject;
  5. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  6. import com.ruoyi.app.utils.ezPay.EzPay;
  7. import com.ruoyi.app.utils.ezPay.EzPayConfig;
  8. import com.ruoyi.common.exception.ServiceException;
  9. import com.ruoyi.common.utils.SecurityUtils;
  10. import com.ruoyi.system.domain.PosLoveOrg;
  11. import com.ruoyi.system.domain.PosOrder;
  12. import com.ruoyi.system.domain.PosOrderInvoice;
  13. import com.ruoyi.system.domain.PosStore;
  14. import com.ruoyi.system.domain.PosStoreEzpay;
  15. import com.ruoyi.system.domain.InfoUser;
  16. import com.ruoyi.system.domain.dto.ApplyInvoiceDto;
  17. import com.ruoyi.system.domain.vo.PosOrderInvoiceVo;
  18. import com.ruoyi.system.mapper.PosLoveOrgMapper;
  19. import com.ruoyi.system.mapper.PosOrderInvoiceMapper;
  20. import com.ruoyi.system.mapper.PosOrderMapper;
  21. import com.ruoyi.system.mapper.PosStoreEzpayMapper;
  22. import com.ruoyi.system.mapper.PosStoreMapper;
  23. import com.ruoyi.system.service.IInfoUserService;
  24. import org.springframework.beans.factory.annotation.Autowired;
  25. import org.springframework.beans.factory.annotation.Value;
  26. import org.springframework.dao.DuplicateKeyException;
  27. import org.springframework.stereotype.Service;
  28. import java.util.Date;
  29. import java.util.LinkedHashMap;
  30. import java.util.List;
  31. import java.util.Map;
  32. import java.util.Objects;
  33. /**
  34. * 订单电子发票 开票 / 作废 / 查询 业务(放 admin,因需调用 {@link EzPay})。
  35. *
  36. * <p>开票链路({@link #applyInvoice}):校验订单归属/状态/支付 → 校验门店可开票(009 凭证 + 免用发票)
  37. * → 金额拆分(不含运费)→ 组装 ezPay issue 参数 + 逐商品明细 → 调 {@link EzPay#issueInvoice}
  38. * → 判读回应 → 落库。作废走 {@link EzPay#doPost} + invoice_invalid。
  39. *
  40. * @author ruoyi
  41. * @date 2026-06-16
  42. */
  43. @Service
  44. public class OrderInvoiceService {
  45. @Autowired
  46. private EzPay ezPay;
  47. @Autowired
  48. private PosOrderMapper posOrderMapper;
  49. @Autowired
  50. private PosStoreMapper posStoreMapper;
  51. @Autowired
  52. private PosStoreEzpayMapper posStoreEzpayMapper;
  53. @Autowired
  54. private PosOrderInvoiceMapper posOrderInvoiceMapper;
  55. @Autowired
  56. private PosLoveOrgMapper posLoveOrgMapper;
  57. @Autowired
  58. private IInfoUserService infoUserService;
  59. /** ezPay 接口根地址(从 application.yml 的 ezpay.base-url 注入,测试/正式在此切换) */
  60. @Value("${ezpay.base-url}")
  61. private String ezpayBaseUrl;
  62. /** 发票状态:0未开/1已开/2失败/3作废 */
  63. private static final int STATUS_NOT_ISSUED = 0;
  64. private static final int STATUS_ISSUED = 1;
  65. private static final int STATUS_FAILED = 2;
  66. private static final int STATUS_INVALID = 3;
  67. /** 订单完成态、已支付 */
  68. private static final long ORDER_STATE_DONE = 3L;
  69. private static final long ORDER_PAID = 1L;
  70. // ==================== US1/US2/US3:客户开票 ====================
  71. /**
  72. * 客户申请开票。校验 → 金额拆分 → 调 ezPay 即时开立 → 落库。
  73. * B2C/B2B/载具由 {@link #buildIssueData} 按 {@code category}/{@code carrierType} 分支处理。
  74. */
  75. public PosOrderInvoiceVo applyInvoice(ApplyInvoiceDto dto, Long currentUserId) {
  76. Long orderId = dto.getOrderId();
  77. PosOrder order = posOrderMapper.selectOne(new LambdaQueryWrapper<PosOrder>().eq(PosOrder::getDdId,orderId.toString()));
  78. if (order == null) {
  79. throw new ServiceException("订单不存在");
  80. }
  81. if (!Objects.equals(order.getUserId(), currentUserId)) {
  82. throw new ServiceException("无权操作该订单");
  83. }
  84. if (order.getState() == null || order.getState() != ORDER_STATE_DONE) {
  85. throw new ServiceException("订单未完成,暂不可开票");
  86. }
  87. if (order.getPayStatus() == null || order.getPayStatus() != ORDER_PAID) {
  88. throw new ServiceException("订单未支付,暂不可开票");
  89. }
  90. Long storeId = order.getMdId();
  91. PosStoreEzpay ez = assertInvoiceable(storeId);
  92. // 场景入参校验(B2B 统编 / B2C 邮箱 / 载具号码)
  93. validateInvoiceInput(dto);
  94. // 防重复开票
  95. PosOrderInvoice row = posOrderInvoiceMapper.selectOne(
  96. new LambdaQueryWrapper<PosOrderInvoice>().eq(PosOrderInvoice::getOrderId, orderId));
  97. if (row != null && Integer.valueOf(STATUS_ISSUED).equals(row.getInvoiceStatus())) {
  98. throw new ServiceException("该订单已开票,不可重复开票");
  99. }
  100. // 金额拆分(不含运费:invoiceTotal = amount - freight)
  101. int amount = order.getAmount() == null ? 0 : order.getAmount();
  102. int freight = (int) Math.round(order.getFreight() == null ? 0d : order.getFreight());
  103. int invoiceTotal = amount - freight;
  104. if (invoiceTotal <= 0) {
  105. throw new ServiceException("订单可开票金额异常,无法开票");
  106. }
  107. int sales = (int) Math.round(invoiceTotal / 1.05);
  108. int tax = invoiceTotal - sales;
  109. // ezPay 凭证(捐赠机构 checkLoveCode 兜底也用到)
  110. EzPayConfig cfg = new EzPayConfig(ez.getMerchantId(), ez.getHashKey(), ez.getHashIv());
  111. // 捐赠发票:解析机构(local 优先,未命中 checkLoveCode 验真),回填买方名为机构名
  112. String loveOrgName = null;
  113. if ("DONATION".equals(dto.getCategory())) {
  114. loveOrgName = resolveLoveOrg(dto.getLoveCode(), cfg);
  115. dto.setBuyerName(loveOrgName);
  116. }
  117. // 组装 ezPay issue 参数 + 调用
  118. Map<String, Object> inv = buildIssueData(dto, order, invoiceTotal, sales, tax);
  119. int newStatus;
  120. String invoiceNumber = null, randomNum = null, invoiceTransNo = null,
  121. invoiceBarCode = null, invoiceQrcodeL = null, invoiceQrcodeR = null, failReason = null;
  122. try {
  123. JSONObject resp = ezPay.issueInvoice(ezpayBaseUrl, cfg, inv); String status = resp == null ? "" : resp.getString("Status");
  124. JSONObject result = resp == null ? null : resp.getJSONObject("Result");
  125. if ("SUCCESS".equals(status) && result != null && StrUtil.isNotBlank(result.getString("InvoiceNumber"))) {
  126. invoiceNumber = result.getString("InvoiceNumber");
  127. randomNum = result.getString("RandomNum");
  128. invoiceTransNo = result.getString("InvoiceTransNo");
  129. invoiceBarCode = result.getString("BarCode");
  130. invoiceQrcodeL = result.getString("QRcodeL");
  131. invoiceQrcodeR = result.getString("QRcodeR");
  132. newStatus = STATUS_ISSUED;
  133. } else {
  134. failReason = resp == null ? "ezPay 无回应" : (status + ":" + resp.getString("Message"));
  135. newStatus = STATUS_FAILED;
  136. }
  137. } catch (Exception e) {
  138. failReason = "ezPay 服务暂不可用:" + (e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage());
  139. newStatus = STATUS_FAILED;
  140. }
  141. // 落库(uk_order_id 兜底防并发重复)
  142. Date now = new Date();
  143. PosOrderInvoice saveRow = row == null ? new PosOrderInvoice() : row;
  144. saveRow.setOrderId(orderId);
  145. saveRow.setOrderNo(order.getDdId());
  146. saveRow.setStoreId(storeId);
  147. saveRow.setInvoiceCategory(dto.getCategory());
  148. saveRow.setBuyerName(dto.getBuyerName());
  149. saveRow.setBuyerUbn(dto.getBuyerUbn());
  150. saveRow.setBuyerEmail(dto.getBuyerEmail());
  151. saveRow.setCarrierType(dto.getCarrierType());
  152. saveRow.setCarrierNum(dto.getCarrierNum());
  153. saveRow.setLoveCode(dto.getLoveCode());
  154. saveRow.setLoveOrgName(loveOrgName);
  155. saveRow.setTotalAmt(invoiceTotal);
  156. saveRow.setSalesAmt(sales);
  157. saveRow.setTaxAmt(tax);
  158. saveRow.setApplyTime(now);
  159. if (newStatus == STATUS_ISSUED) {
  160. saveRow.setInvoiceNumber(invoiceNumber);
  161. saveRow.setRandomNum(randomNum);
  162. saveRow.setInvoiceTransNo(invoiceTransNo);
  163. saveRow.setInvoiceBarCode(invoiceBarCode);
  164. saveRow.setInvoiceQrcodeL(invoiceQrcodeL);
  165. saveRow.setInvoiceQrcodeR(invoiceQrcodeR);
  166. saveRow.setIssueTime(now);
  167. saveRow.setFailReason(null);
  168. } else {
  169. saveRow.setFailReason(StrUtil.sub(failReason, 0, 480));
  170. }
  171. saveRow.setInvoiceStatus(newStatus);
  172. try {
  173. saveOrUpdate(saveRow);
  174. } catch (DuplicateKeyException dup) {
  175. throw new ServiceException("请勿重复提交开票申请");
  176. }
  177. return posOrderInvoiceMapper.selectInvoiceDetail(orderId);
  178. }
  179. /**
  180. * 下单捕获发票意图(010 Phase 11):把下单选的发票类型/载具/统编/捐赠码落成 pos_order_invoice
  181. * 意图行(issueTriggered=0 未触发开票、invoiceStatus=0 未开);出餐 {@link #autoIssue} 在该行
  182. * 上更新开票结果并置 issueTriggered=1。仅在门店可开票时由 createOrder 调用。
  183. */
  184. public void captureInvoiceIntent(PosOrderInvoice intent) {
  185. intent.setInvoiceStatus(STATUS_NOT_ISSUED);
  186. intent.setIssueTriggered(0);
  187. if (intent.getApplyTime() == null) {
  188. intent.setApplyTime(new Date());
  189. }
  190. saveOrUpdate(intent);
  191. }
  192. /**
  193. * 商家出餐自动开票(010 Phase 11):读 pos_order_invoice 发票意图行 → 组装 dto(个人 BuyerName=手机号、
  194. * 捐赠=机构名)→ 复用开票核心 {@link #reIssueAndSave}。系统触发,不校验客户归属;货到付款未付款也开
  195. * (送达失败/取消时作废兜底)。门店不可开票 / 订单无发票意图 / 已开 → 静默跳过,不影响出餐。
  196. *
  197. * @param orderId PosOrder.id(PK,与 invalid/retry/selectInvoiceDetail 一致)
  198. * @return 1=已开 0=跳过或失败
  199. */
  200. public int autoIssue(Long orderId) {
  201. PosOrder order = posOrderMapper.selectPosOrderById(orderId);
  202. if (order == null) {
  203. return 0; // 订单不存在
  204. }
  205. // 发票意图自 Phase 11 起落 pos_order_invoice(下单捕获的意图行),不再读 pos_order
  206. PosOrderInvoice row = posOrderInvoiceMapper.selectOne(
  207. new LambdaQueryWrapper<PosOrderInvoice>().eq(PosOrderInvoice::getOrderId, orderId));
  208. if (row == null || StrUtil.isBlank(row.getInvoiceChoice())) {
  209. return 0; // 无发票意图(门店不可开票时 createOrder 未插意图行)
  210. }
  211. Long storeId = order.getMdId();
  212. if (!canInvoice(storeId)) {
  213. return 0; // 出餐时门店已不可开票(被停用等),跳过
  214. }
  215. PosStoreEzpay ez = posStoreEzpayMapper.selectOne(
  216. new LambdaQueryWrapper<PosStoreEzpay>().eq(PosStoreEzpay::getStoreId, storeId));
  217. if (ez == null) {
  218. return 0;
  219. }
  220. // 防重复:已开则跳过
  221. if (Integer.valueOf(STATUS_ISSUED).equals(row.getInvoiceStatus())) {
  222. return 0;
  223. }
  224. ApplyInvoiceDto dto = buildAutoIssueDto(row);
  225. EzPayConfig cfg = new EzPayConfig(ez.getMerchantId(), ez.getHashKey(), ez.getHashIv());
  226. // 捐赠=机构名;个人=手机号
  227. String loveOrgName = null;
  228. if ("LOVE_CODE".equals(row.getInvoiceChoice())) {
  229. loveOrgName = resolveLoveOrg(dto.getLoveCode(), cfg);
  230. dto.setBuyerName(loveOrgName);
  231. } else if (isPersonalChoice(row.getInvoiceChoice())) {
  232. InfoUser u = infoUserService.getOne(
  233. new LambdaQueryWrapper<InfoUser>().eq(InfoUser::getUserId, order.getUserId()));
  234. dto.setBuyerName(u != null && StrUtil.isNotBlank(u.getPhone()) ? u.getPhone() : "會員");
  235. }
  236. // 出餐触发开票:在意图行上落结果,并标记已触发(与 invoiceStatus 独立)
  237. row.setInvoiceCategory(dto.getCategory());
  238. row.setBuyerName(dto.getBuyerName());
  239. row.setLoveOrgName(loveOrgName);
  240. row.setIssueTriggered(1);
  241. return reIssueAndSave(order, row, dto, ez);
  242. }
  243. /** 出餐自动开票:pos_order_invoice 发票意图行 → ApplyInvoiceDto(捐赠走 DONATION 复用既有分支)。 */
  244. private ApplyInvoiceDto buildAutoIssueDto(PosOrderInvoice intent) {
  245. ApplyInvoiceDto dto = new ApplyInvoiceDto();
  246. dto.setOrderId(intent.getOrderId());
  247. String choice = intent.getInvoiceChoice();
  248. switch (choice) {
  249. case "PAPER":
  250. case "PHONE_BARCODE":
  251. case "CITIZEN":
  252. dto.setCategory("B2C");
  253. dto.setCarrierType(intent.getCarrierType()); // PAPER 时为 null → 个人纸本分支
  254. dto.setCarrierNum(intent.getCarrierNum());
  255. break;
  256. case "LOVE_CODE":
  257. dto.setCategory("DONATION");
  258. dto.setLoveCode(intent.getLoveCode());
  259. break;
  260. case "COMPANY":
  261. dto.setCategory("B2B");
  262. dto.setBuyerUbn(intent.getBuyerUbn());
  263. dto.setBuyerName(intent.getBuyerName());
  264. break;
  265. default:
  266. break;
  267. }
  268. return dto;
  269. }
  270. private boolean isPersonalChoice(String choice) {
  271. return "PAPER".equals(choice) || "PHONE_BARCODE".equals(choice) || "CITIZEN".equals(choice);
  272. }
  273. /** 客户查询订单发票;门店不可开票时 invoiceStatus=null(客户端据此隐藏入口)。 */
  274. public PosOrderInvoiceVo getInvoice(Long orderId, Long currentUserId) {
  275. PosOrder order = posOrderMapper.selectOne(new LambdaQueryWrapper<PosOrder>().eq(PosOrder::getDdId,orderId));
  276. if (order == null || !Objects.equals(order.getUserId(), currentUserId)) {
  277. throw new ServiceException("订单不存在");
  278. }
  279. boolean can = canInvoice(order.getMdId());
  280. PosOrderInvoiceVo vo = posOrderInvoiceMapper.selectInvoiceDetail(orderId);
  281. if (vo == null) {
  282. vo = new PosOrderInvoiceVo();
  283. vo.setOrderId(orderId);
  284. vo.setOrderNo(order.getDdId());
  285. vo.setInvoiceStatus(can ? STATUS_NOT_ISSUED : null);
  286. }
  287. return vo;
  288. }
  289. /** 商家端查询订单发票(校验商家为该订单门店归属人)。 */
  290. public PosOrderInvoiceVo getInvoiceForMerchant(Long orderId, Long merchantUserId) {
  291. requireOwnedOrder(orderId, merchantUserId);
  292. return posOrderInvoiceMapper.selectInvoiceDetail(orderId);
  293. }
  294. /** 商家端作废发票(校验归属后复用作废逻辑)。 */
  295. public int invalidForMerchant(Long orderId, String reason, Long merchantUserId) {
  296. requireOwnedOrder(orderId, merchantUserId);
  297. return invalid(orderId, reason);
  298. }
  299. /** 校验订单存在且属于该商家门店,返回订单;否则抛异常。 */
  300. private PosOrder requireOwnedOrder(Long orderId, Long merchantUserId) {
  301. PosOrder order = posOrderMapper.selectPosOrderById(orderId);
  302. if (order == null) {
  303. throw new ServiceException("订单不存在");
  304. }
  305. InfoUser user = infoUserService.getOne(
  306. new LambdaQueryWrapper<InfoUser>().eq(InfoUser::getUserId, merchantUserId));
  307. if (user == null) {
  308. throw new ServiceException("用户不存在");
  309. }
  310. String ut = user.getUserType();
  311. boolean own;
  312. if ("1".equals(ut) || "3".equals(ut)) {
  313. // 普通/夜市商家:订单 shId 即商家 userId
  314. own = merchantUserId.equals(order.getShId());
  315. } else {
  316. // 摊位商家:订单门店 mdId 即商家 storeId
  317. own = user.getStoreId() != null && user.getStoreId().equals(order.getMdId());
  318. }
  319. if (!own) {
  320. throw new ServiceException("无权操作该订单发票");
  321. }
  322. return order;
  323. }
  324. // ==================== US4/US5:管理端 ====================
  325. /** 管理端:订单发票列表(配合 PageHelper 分页)。 */
  326. public List<PosOrderInvoiceVo> list(PosOrderInvoiceVo query) {
  327. if (query != null && query.getDateRange() != null && query.getDateRange().length == 2) {
  328. query.setCretimStart(query.getDateRange()[0]);
  329. query.setCretimEnd(query.getDateRange()[1]);
  330. }
  331. return posOrderInvoiceMapper.selectInvoiceList(query);
  332. }
  333. /** 会员发票夹(010 Phase 11):按 userId 列已开发票(不含码图)。配合 PageHelper 分页。 */
  334. public List<PosOrderInvoiceVo> listMyInvoices(Long userId) {
  335. return posOrderInvoiceMapper.selectMyInvoices(userId);
  336. }
  337. /** 管理端:订单发票详情。 */
  338. public PosOrderInvoiceVo detail(Long orderId) {
  339. return posOrderInvoiceMapper.selectInvoiceDetail(orderId);
  340. }
  341. /** 管理端:重新开票(仅 失败/作废 单;运营身份不校验客户归属)。 */
  342. public int retry(Long orderId) {
  343. PosOrderInvoice row = posOrderInvoiceMapper.selectOne(
  344. new LambdaQueryWrapper<PosOrderInvoice>().eq(PosOrderInvoice::getOrderId, orderId));
  345. if (row == null) {
  346. throw new ServiceException("发票记录不存在");
  347. }
  348. int st = row.getInvoiceStatus() == null ? STATUS_NOT_ISSUED : row.getInvoiceStatus();
  349. if (st != STATUS_FAILED && st != STATUS_INVALID) {
  350. throw new ServiceException("仅失败或作废的发票可重新开票");
  351. }
  352. // 重置为未开,复用客户开票参数重开(运营身份 currentUserId 传 null 跳过归属校验)
  353. PosOrder order = posOrderMapper.selectOne(new LambdaQueryWrapper<PosOrder>().eq(PosOrder::getDdId,orderId.toString()));
  354. if (order == null) {
  355. throw new ServiceException("订单不存在");
  356. }
  357. PosStoreEzpay ez = assertInvoiceable(order.getMdId());
  358. ApplyInvoiceDto dto = new ApplyInvoiceDto();
  359. dto.setOrderId(orderId);
  360. dto.setCategory(row.getInvoiceCategory());
  361. dto.setBuyerName(row.getBuyerName());
  362. dto.setBuyerUbn(row.getBuyerUbn());
  363. dto.setBuyerEmail(row.getBuyerEmail());
  364. dto.setCarrierType(row.getCarrierType());
  365. dto.setCarrierNum(row.getCarrierNum());
  366. dto.setLoveCode(row.getLoveCode());
  367. // 复用核心开票(不含归属校验):直接走 issue + 落库
  368. return reIssueAndSave(order, row, dto, ez);
  369. }
  370. /** 管理端:作废发票(仅 已开 单,调 ezPay invoice_invalid)。 */
  371. public int invalid(Long orderId, String reason) {
  372. PosOrderInvoice row = posOrderInvoiceMapper.selectOne(
  373. new LambdaQueryWrapper<PosOrderInvoice>().eq(PosOrderInvoice::getOrderId, orderId));
  374. if (row == null || !Integer.valueOf(STATUS_ISSUED).equals(row.getInvoiceStatus())) {
  375. throw new ServiceException("仅已开发票可作废");
  376. }
  377. PosOrder order = posOrderMapper.selectPosOrderById(orderId);
  378. PosStoreEzpay ez = posStoreEzpayMapper.selectOne(
  379. new LambdaQueryWrapper<PosStoreEzpay>().eq(PosStoreEzpay::getStoreId, order.getMdId()));
  380. if (ez == null) {
  381. throw new ServiceException("门店 ezPay 凭证缺失,无法作废");
  382. }
  383. Map<String, Object> postData = new LinkedHashMap<>();
  384. postData.put("RespondType", "JSON");
  385. postData.put("Version", "1.0");
  386. postData.put("InvoiceNumber", row.getInvoiceNumber());
  387. postData.put("InvalidReason", StrUtil.isBlank(reason) ? "商家作废" : reason);
  388. try {
  389. EzPayConfig cfg = new EzPayConfig(ez.getMerchantId(), ez.getHashKey(), ez.getHashIv());
  390. JSONObject resp = ezPay.doPost(ezpayBaseUrl + EzPay.URL_INVALID, cfg, postData); String status = resp == null ? "" : resp.getString("Status");
  391. if ("SUCCESS".equals(status)) {
  392. row.setInvoiceStatus(STATUS_INVALID);
  393. row.setInvalidTime(new Date());
  394. saveOrUpdate(row);
  395. return 1;
  396. }
  397. throw new ServiceException("作废失败:" + (resp == null ? "ezPay 无回应" : resp.getString("Message")));
  398. } catch (ServiceException se) {
  399. throw se;
  400. } catch (Exception e) {
  401. throw new ServiceException("ezPay 服务暂不可用:" + (e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()));
  402. }
  403. }
  404. // ==================== 内部辅助 ====================
  405. /** 复用开票核心(运营重开,无归属校验)。 */
  406. private int reIssueAndSave(PosOrder order, PosOrderInvoice row, ApplyInvoiceDto dto, PosStoreEzpay ez) {
  407. int amount = order.getAmount() == null ? 0 : order.getAmount();
  408. int freight = (int) Math.round(order.getFreight() == null ? 0d : order.getFreight());
  409. int invoiceTotal = amount - freight;
  410. int sales = (int) Math.round(invoiceTotal / 1.05);
  411. int tax = invoiceTotal - sales;
  412. Map<String, Object> inv = buildIssueData(dto, order, invoiceTotal, sales, tax);
  413. EzPayConfig cfg = new EzPayConfig(ez.getMerchantId(), ez.getHashKey(), ez.getHashIv());
  414. int newStatus;
  415. String invoiceNumber = null, randomNum = null, invoiceTransNo = null,
  416. invoiceBarCode = null, invoiceQrcodeL = null, invoiceQrcodeR = null, failReason = null;
  417. try {
  418. JSONObject resp = ezPay.issueInvoice(ezpayBaseUrl, cfg, inv);
  419. String status = resp == null ? "" : resp.getString("Status");
  420. JSONObject result = resp == null ? null : resp.getJSONObject("Result");
  421. if ("SUCCESS".equals(status) && result != null && StrUtil.isNotBlank(result.getString("InvoiceNumber"))) {
  422. invoiceNumber = result.getString("InvoiceNumber");
  423. randomNum = result.getString("RandomNum");
  424. invoiceTransNo = result.getString("InvoiceTransNo");
  425. invoiceBarCode = result.getString("BarCode");
  426. invoiceQrcodeL = result.getString("QRcodeL");
  427. invoiceQrcodeR = result.getString("QRcodeR");
  428. newStatus = STATUS_ISSUED;
  429. } else {
  430. failReason = resp == null ? "ezPay 无回应" : (status + ":" + resp.getString("Message"));
  431. newStatus = STATUS_FAILED;
  432. }
  433. } catch (Exception e) {
  434. failReason = "ezPay 服务暂不可用:" + (e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage());
  435. newStatus = STATUS_FAILED;
  436. }
  437. Date now = new Date();
  438. if (newStatus == STATUS_ISSUED) {
  439. row.setInvoiceNumber(invoiceNumber);
  440. row.setRandomNum(randomNum);
  441. row.setInvoiceTransNo(invoiceTransNo);
  442. row.setInvoiceBarCode(invoiceBarCode);
  443. row.setInvoiceQrcodeL(invoiceQrcodeL);
  444. row.setInvoiceQrcodeR(invoiceQrcodeR);
  445. row.setIssueTime(now);
  446. row.setFailReason(null);
  447. } else {
  448. row.setFailReason(StrUtil.sub(failReason, 0, 480));
  449. }
  450. row.setInvoiceStatus(newStatus);
  451. saveOrUpdate(row);
  452. return newStatus == STATUS_ISSUED ? 1 : 0;
  453. }
  454. /** 校验门店可开票并返回凭证;不可开票抛异常。 */
  455. private PosStoreEzpay assertInvoiceable(Long storeId) {
  456. if (storeId == null) {
  457. throw new ServiceException("订单未关联门店,暂不可开票");
  458. }
  459. PosStore store = posStoreMapper.selectPosStoreById(storeId);
  460. if (store != null && Integer.valueOf(1).equals(store.getInvoiceExempt())) {
  461. throw new ServiceException("该门店免用发票,无需开票");
  462. }
  463. PosStoreEzpay ez = posStoreEzpayMapper.selectOne(
  464. new LambdaQueryWrapper<PosStoreEzpay>().eq(PosStoreEzpay::getStoreId, storeId));
  465. if (ez == null || !Integer.valueOf(2).equals(ez.getEzpayStatus())
  466. || !Integer.valueOf(1).equals(ez.getIsEnabled())) {
  467. throw new ServiceException("该门店暂不支持电子发票");
  468. }
  469. return ez;
  470. }
  471. /** 门店是否可开票(不抛异常):免用发票或 ezPay 未开通启用均返回 false。 */
  472. public boolean canInvoice(Long storeId) {
  473. if (storeId == null) {
  474. return false;
  475. }
  476. PosStore store = posStoreMapper.selectPosStoreById(storeId);
  477. if (store != null && Integer.valueOf(1).equals(store.getInvoiceExempt())) {
  478. return false;
  479. }
  480. PosStoreEzpay ez = posStoreEzpayMapper.selectOne(
  481. new LambdaQueryWrapper<PosStoreEzpay>().eq(PosStoreEzpay::getStoreId, storeId));
  482. return ez != null && Integer.valueOf(2).equals(ez.getEzpayStatus())
  483. && Integer.valueOf(1).equals(ez.getIsEnabled());
  484. }
  485. /** 取门店 ezPay 凭证配置;未开通/未启用返回 null(不抛异常,供校验场景容忍使用)。 */
  486. private EzPayConfig getEzpayConfig(Long storeId) {
  487. if (storeId == null) {
  488. return null;
  489. }
  490. PosStoreEzpay ez = posStoreEzpayMapper.selectOne(
  491. new LambdaQueryWrapper<PosStoreEzpay>().eq(PosStoreEzpay::getStoreId, storeId));
  492. if (ez == null || !Integer.valueOf(2).equals(ez.getEzpayStatus())
  493. || !Integer.valueOf(1).equals(ez.getIsEnabled())) {
  494. return null;
  495. }
  496. return new EzPayConfig(ez.getMerchantId(), ez.getHashKey(), ez.getHashIv());
  497. }
  498. /**
  499. * 结账时校验发票意图(010 Phase 11):载具/捐赠联网验真、统编/凭证格式校验。
  500. * PAPER(默认纸本)不校验。联网校验(手机条码/捐赠码)用 storeId 对应门店的 ezPay 凭证调 BDV。
  501. *
  502. * @param storeId 一个可开票门店(调用方负责选 canInvoice 的门店,用于取 ezPay 凭证)
  503. */
  504. public void validateCheckoutInvoiceIntent(String invoiceChoice, String carrierNum, String loveCode,
  505. String buyerUbn, Long storeId) {
  506. if (StrUtil.isBlank(invoiceChoice) || "PAPER".equals(invoiceChoice)) {
  507. return;
  508. }
  509. switch (invoiceChoice) {
  510. case "PHONE_BARCODE":
  511. if (StrUtil.isBlank(carrierNum) || !carrierNum.matches("^/[0-9A-Z+\\-.]{7}$")) {
  512. throw new ServiceException("手机条码格式不正确(须为 / 加 7 位大写英文/数字/+-.)");
  513. }
  514. EzPayConfig barCfg = getEzpayConfig(storeId);
  515. if (barCfg == null) {
  516. throw new ServiceException("门店暂不支持电子发票,无法校验手机条码");
  517. }
  518. boolean barExist;
  519. try {
  520. barExist = ezPay.checkBarCode(ezpayBaseUrl, barCfg, carrierNum);
  521. } catch (Exception e) {
  522. throw new ServiceException("手机条码校验服务暂不可用,请稍后重试");
  523. }
  524. if (!barExist) {
  525. throw new ServiceException("手机条码不存在,请确认或改选纸本发票");
  526. }
  527. break;
  528. case "CITIZEN":
  529. if (StrUtil.isBlank(carrierNum) || !carrierNum.matches("^[A-Z]{2}\\d{14}$")) {
  530. throw new ServiceException("自然人凭证格式不正确(须为 2 位大写英文 + 14 位数字)");
  531. }
  532. break;
  533. case "LOVE_CODE":
  534. if (StrUtil.isBlank(loveCode) || !loveCode.matches("^\\d{3,7}$")) {
  535. throw new ServiceException("捐赠码格式不正确(须为 3-7 位数字)");
  536. }
  537. EzPayConfig loveCfg = getEzpayConfig(storeId);
  538. if (loveCfg == null) {
  539. throw new ServiceException("门店暂不支持电子发票,无法校验捐赠码");
  540. }
  541. resolveLoveOrg(loveCode, loveCfg); // 抛异常=捐赠码无效
  542. break;
  543. case "COMPANY":
  544. if (StrUtil.isBlank(buyerUbn) || !buyerUbn.matches("^\\d{8}$")) {
  545. throw new ServiceException("统一编号格式不正确(须为 8 位数字)");
  546. }
  547. break;
  548. default:
  549. throw new ServiceException("发票类型不合法:" + invoiceChoice);
  550. }
  551. }
  552. /**
  553. * 捐赠机构列表(客户端选择器,仅 enabled=1,配合 PageHelper 分页)。
  554. */
  555. public List<PosLoveOrg> listLoveOrg(String keyword) {
  556. return posLoveOrgMapper.selectListByKeyword(keyword);
  557. }
  558. /**
  559. * 解析捐赠机构并验真:local 命中返回简称/全名;local 未命中调 ezPay checkLoveCode
  560. * (IsExist=N 抛「捐赠码无效」,调用异常抛「验证失败」)。返回用于展示 / BuyerName 的机构名。
  561. */
  562. private String resolveLoveOrg(String loveCode, EzPayConfig cfg) {
  563. PosLoveOrg org = posLoveOrgMapper.selectOne(new LambdaQueryWrapper<PosLoveOrg>()
  564. .eq(PosLoveOrg::getLoveCode, loveCode)
  565. .eq(PosLoveOrg::getEnabled, 1));
  566. if (org != null) {
  567. return StrUtil.isNotBlank(org.getOrgShortName()) ? org.getOrgShortName() : org.getOrgName();
  568. }
  569. try {
  570. if (!ezPay.checkLoveCode(ezpayBaseUrl, cfg, loveCode)) {
  571. throw new ServiceException("捐赠码无效");
  572. }
  573. } catch (ServiceException se) {
  574. throw se;
  575. } catch (Exception e) {
  576. throw new ServiceException("捐赠码验证失败,请稍后重试");
  577. }
  578. return "未知机构";
  579. }
  580. /**
  581. * 场景入参校验(service 内强校验,拦截非法请求不调 ezPay)。对齐 ezPay 开票模型:
  582. * B2B:统编(8位)+邮箱必填、无载具;B2C:载具(0/1/2)+号码必填,ezPay会员载具(2)时邮箱必填。
  583. */
  584. private void validateInvoiceInput(ApplyInvoiceDto dto) {
  585. if ("B2B".equals(dto.getCategory())) {
  586. if (StrUtil.isBlank(dto.getBuyerName())) {
  587. throw new ServiceException("B2B 发票须填写买方名称");
  588. }
  589. if (StrUtil.isBlank(dto.getBuyerUbn()) || !dto.getBuyerUbn().matches("\\d{8}")) {
  590. throw new ServiceException("统编格式不正确,须为 8 位数字");
  591. }
  592. if (StrUtil.isBlank(dto.getBuyerEmail())) {
  593. throw new ServiceException("B2B 发票须填写买方邮箱");
  594. }
  595. if (StrUtil.isNotBlank(dto.getCarrierType()) || StrUtil.isNotBlank(dto.getCarrierNum())) {
  596. throw new ServiceException("B2B 发票不支持载具");
  597. }
  598. } else if ("DONATION".equals(dto.getCategory())) {
  599. // 捐赠:loveCode 3-7 位必填,与载具/统编互斥
  600. if (StrUtil.isBlank(dto.getLoveCode()) || !dto.getLoveCode().matches("\\d{3,7}")) {
  601. throw new ServiceException("捐赠码格式不正确,须为 3-7 位数字");
  602. }
  603. if (StrUtil.isNotBlank(dto.getCarrierType()) || StrUtil.isNotBlank(dto.getCarrierNum())) {
  604. throw new ServiceException("捐赠发票不支持载具");
  605. }
  606. if (StrUtil.isNotBlank(dto.getBuyerUbn())) {
  607. throw new ServiceException("捐赠发票不支持统编");
  608. }
  609. } else if ("B2C".equals(dto.getCategory())) {
  610. // 载具分支
  611. if (StrUtil.isBlank(dto.getBuyerName())) {
  612. throw new ServiceException("买方名称不能为空");
  613. }
  614. String ct = dto.getCarrierType();
  615. if (StrUtil.isBlank(ct)) {
  616. // 无载具 → 个人纸本(PrintFlag=Y,零信息兜底),无需载具校验
  617. return;
  618. }
  619. if (!"0".equals(ct) && !"1".equals(ct) && !"2".equals(ct)) {
  620. throw new ServiceException("载具类型只能为 0手机条码/1自然人凭证/2ezPay会员");
  621. }
  622. if (StrUtil.isBlank(dto.getCarrierNum())) {
  623. throw new ServiceException("载具号码不能为空");
  624. }
  625. // ezPay doc:载具号码前后不得含空白
  626. dto.setCarrierNum(dto.getCarrierNum().trim());
  627. // ezPay doc:手机条码(0)= / +7码[0-9A-Z+\-.];自然人凭证(1)=2大写英+14数字;ezPay会员(2)=卖方自订代号,不校验
  628. switch (ct) {
  629. case "0":
  630. if (!dto.getCarrierNum().matches("^/[0-9A-Z+\\-.]{7}$")) {
  631. throw new ServiceException("手机条码格式不正确(须为 / 加 7 位大写英文/数字/+ - .)");
  632. }
  633. break;
  634. case "1":
  635. if (!dto.getCarrierNum().matches("^[A-Z]{2}\\d{14}$")) {
  636. throw new ServiceException("自然人凭证格式不正确(须为 2 位大写英文加 14 位数字)");
  637. }
  638. break;
  639. case "2":
  640. default:
  641. break;
  642. }
  643. if ("2".equals(ct) && StrUtil.isBlank(dto.getBuyerEmail())) {
  644. throw new ServiceException("ezPay 会员载具须填写买方邮箱");
  645. }
  646. }
  647. }
  648. /** 组装 ezPay invoice_issue 业务参数(Category/PrintFlag/Buyer/Amt/明细)。 */
  649. private Map<String, Object> buildIssueData(ApplyInvoiceDto dto, PosOrder order,
  650. int invoiceTotal, int sales, int tax) {
  651. Map<String, Object> inv = new LinkedHashMap<>();
  652. inv.put("MerchantOrderNo", order.getDdId());
  653. // ezPay Category 只有 B2C/B2B;DONATION 是我方语义,对应 ezPay B2C + LoveCode
  654. inv.put("Category", "DONATION".equals(dto.getCategory()) ? "B2C" : dto.getCategory());
  655. inv.put("BuyerName", dto.getBuyerName());
  656. if ("B2B".equals(dto.getCategory())) {
  657. inv.put("BuyerUBN", dto.getBuyerUbn());
  658. inv.put("BuyerEmail", dto.getBuyerEmail()); // B2B 邮箱必填:ezPay 发开立通知给买方,凭此查看
  659. inv.put("PrintFlag", "Y");
  660. } else if ("DONATION".equals(dto.getCategory())) {
  661. // 捐赠:LoveCode + PrintFlag=N,无载具/邮箱/统编(买方名=机构名,已在 applyInvoice 回填)
  662. inv.put("LoveCode", dto.getLoveCode());
  663. inv.put("PrintFlag", "N");
  664. } else {
  665. // B2C:有载具 → PrintFlag=N 存载具;无载具 → PrintFlag=Y 个人纸本(零信息兜底,010 Phase 11)
  666. if (StrUtil.isNotBlank(dto.getCarrierType())) {
  667. inv.put("CarrierType", dto.getCarrierType());
  668. inv.put("CarrierNum", dto.getCarrierNum());
  669. inv.put("PrintFlag", "N");
  670. // ezPay 会员载具(2)需邮箱;手机条码(0)/自然人凭证(1)票进载具,邮箱留空
  671. if ("2".equals(dto.getCarrierType()) && StrUtil.isNotBlank(dto.getBuyerEmail())) {
  672. inv.put("BuyerEmail", dto.getBuyerEmail());
  673. }
  674. } else {
  675. // 个人纸本:无载具无捐赠,法定 PrintFlag=Y;不传载具/邮箱
  676. inv.put("PrintFlag", "Y");
  677. }
  678. }
  679. inv.put("TaxType", "1");
  680. inv.put("TaxRate", "5");
  681. inv.put("Amt", String.valueOf(sales));
  682. inv.put("TaxAmt", String.valueOf(tax));
  683. inv.put("TotalAmt", String.valueOf(invoiceTotal));
  684. appendItems(inv, order.getFood(), invoiceTotal);
  685. return inv;
  686. }
  687. /**
  688. * 逐商品明细(research D2/D3):从 food JSON 解析,优惠按比例分摊到单价(方案 B)。
  689. * 每行满足 ItemCount × ItemPrice = ItemAmt(单价决定金额,ezPay 逐商品校验通过)。
  690. */
  691. private void appendItems(Map<String, Object> inv, String foodJson, int invoiceTotal) {
  692. JSONArray arr = StrUtil.isBlank(foodJson) ? null : com.alibaba.fastjson.JSON.parseArray(foodJson);
  693. if (arr == null || arr.isEmpty()) {
  694. inv.put("ItemName", "餐点");
  695. inv.put("ItemCount", "1");
  696. inv.put("ItemUnit", "份");
  697. inv.put("ItemPrice", String.valueOf(invoiceTotal));
  698. inv.put("ItemAmt", String.valueOf(invoiceTotal));
  699. return;
  700. }
  701. int foodTotal = foodOriginalTotal(arr);
  702. double ratio = foodTotal > 0 ? (double) invoiceTotal / foodTotal : 1.0;
  703. StringBuilder name = new StringBuilder(), count = new StringBuilder(),
  704. unit = new StringBuilder(), price = new StringBuilder(), amt = new StringBuilder();
  705. for (int i = 0; i < arr.size(); i++) {
  706. com.alibaba.fastjson.JSONObject it = arr.getJSONObject(i);
  707. int p = it.getIntValue("price") + it.getIntValue("otherPrice");
  708. int c = it.getIntValue("number");
  709. if (c <= 0) {
  710. c = 1;
  711. }
  712. int itemPrice = (int) Math.round(p * ratio);
  713. int itemAmt = itemPrice * c;
  714. if (i > 0) {
  715. name.append("|"); count.append("|"); unit.append("|"); price.append("|"); amt.append("|");
  716. }
  717. String nm = it.getString("name");
  718. name.append(StrUtil.isBlank(nm) ? "餐点" : nm);
  719. count.append(c);
  720. unit.append("個");
  721. price.append(itemPrice);
  722. amt.append(itemAmt);
  723. }
  724. inv.put("ItemName", name.toString());
  725. inv.put("ItemCount", count.toString());
  726. inv.put("ItemUnit", unit.toString());
  727. inv.put("ItemPrice", price.toString());
  728. inv.put("ItemAmt", amt.toString());
  729. }
  730. /** food 商品原价总额(含税)= Σ(price + otherPrice) × number。 */
  731. private int foodOriginalTotal(JSONArray arr) {
  732. int sum = 0;
  733. for (int i = 0; i < arr.size(); i++) {
  734. com.alibaba.fastjson.JSONObject it = arr.getJSONObject(i);
  735. int p = it.getIntValue("price") + it.getIntValue("otherPrice");
  736. int c = it.getIntValue("number");
  737. sum += p * (c <= 0 ? 1 : c);
  738. }
  739. return sum;
  740. }
  741. /** 新增或更新(显式设置时间与人)。 */
  742. private void saveOrUpdate(PosOrderInvoice row) {
  743. Date now = new Date();
  744. String user = currentUser();
  745. if (row.getId() == null) {
  746. row.setCreateTime(now);
  747. row.setUpdateTime(now);
  748. row.setCreateBy(user);
  749. row.setUpdateBy(user);
  750. posOrderInvoiceMapper.insert(row);
  751. } else {
  752. row.setUpdateTime(now);
  753. row.setUpdateBy(user);
  754. posOrderInvoiceMapper.updateById(row);
  755. }
  756. }
  757. private String currentUser() {
  758. try {
  759. return SecurityUtils.getUsername();
  760. } catch (Exception e) {
  761. return "system";
  762. }
  763. }
  764. }