shinnosuke
2026-07-31 82141e1b9e46a154418295aa95b34cb842c001c3
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
package com.talentcard.server.business.merchant;
 
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
 
import com.talentcard.server.business.BusinessIdGenerator;
import com.talentcard.server.business.DatabaseRows;
import com.talentcard.server.business.PageResult;
import com.talentcard.server.business.merchant.auth.MerchantPrincipal;
import com.talentcard.server.common.BusinessException;
import com.talentcard.server.common.ErrorCode;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
@Service
public class MerchantWorkService {
    private static final long REVOCATION_HOURS = 24;
 
    private final JdbcTemplate jdbcTemplate;
 
    public MerchantWorkService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
 
    @Transactional(readOnly = true)
    public PageResult<Map<String, Object>> orders(Long merchantId, Long storeId, int page, int size, MerchantOrderQuery query) {
        int safePage = Math.max(page, 1);
        int safeSize = Math.min(Math.max(size, 1), 100);
        OrderFilters filters = filters(query);
        String conditions = " where o.deleted = 0 and o.merchant_id = ? and (o.store_id is null or o.store_id = ?)" + filters.conditions();
        List<Object> arguments = new ArrayList<>();
        arguments.add(merchantId);
        arguments.add(storeId);
        arguments.addAll(filters.arguments());
 
        String recordSql = """
                select o.id, o.order_no, tu.name as talent_name, tu.mobile as talent_mobile, tc.card_level,
                       b.benefit_name, o.order_type, o.order_amount, o.subsidy_amount, o.pay_amount,
                       o.order_status, o.verify_status, o.created_at, verified.verify_time
                from benefit_order o
                left join talent_user tu on tu.id = o.talent_id
                left join talent_card tc on tc.id = o.card_id
                left join benefit b on b.id = o.benefit_id
                left join (select order_id, max(verify_time) verify_time from verify_record where status = 1 group by order_id) verified on verified.order_id = o.id
                """ + conditions + " order by o.id desc limit ? offset ?";
        List<Object> recordArguments = new ArrayList<>(arguments);
        recordArguments.add(safeSize);
        recordArguments.add((safePage - 1) * safeSize);
        List<Map<String, Object>> records = query(recordSql, recordArguments.toArray()).stream().map(this::toListItem).toList();
        Long total = jdbcTemplate.queryForObject("select count(*) from benefit_order o" + conditions, Long.class, arguments.toArray());
        return new PageResult<>(records, safePage, safeSize, total == null ? 0 : total);
    }
 
    public PageResult<Map<String, Object>> orders(Long merchantId, Long storeId, int page, int size) {
        return orders(merchantId, storeId, page, size, new MerchantOrderQuery(null, null, null, null));
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> order(String orderNo, Long merchantId, Long storeId) {
        List<Map<String, Object>> rows = query("""
                select o.id, o.order_no, o.talent_id, tu.name as talent_name, tu.mobile as talent_mobile,
                       o.card_id, tc.card_no, tc.card_level, o.benefit_id, b.benefit_name,
                       o.merchant_id, m.merchant_name, o.order_type, o.order_amount,
                       o.subsidy_amount, o.pay_amount, o.order_status, o.verify_status, o.created_at,
                       vr.verify_time, vr.status as verify_record_status
                from benefit_order o
                left join talent_user tu on tu.id = o.talent_id
                left join talent_card tc on tc.id = o.card_id
                left join benefit b on b.id = o.benefit_id
                left join merchant m on m.id = o.merchant_id
                left join verify_record vr on vr.order_id = o.id and vr.status = 1
                where o.deleted = 0 and o.order_no = ? and o.merchant_id = ? and (o.store_id is null or o.store_id = ?)
                """, orderNo, merchantId, storeId);
        if (rows.isEmpty()) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "订单不存在");
        }
        return enrichOrder(rows.get(0));
    }
 
    @Transactional
    public Map<String, Object> verify(String orderNo, MerchantPrincipal principal, VerifyRequest request, String idempotencyKey) {
        if (idempotencyKey == null || idempotencyKey.isBlank()) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, "缺少幂等键");
        }
        Map<String, Object> order = order(orderNo, principal.merchantId(), principal.storeId());
        List<Map<String, Object>> repeated = query("""
                select order_id from verify_record where idempotency_key = ? and merchant_id = ? limit 1
                """, idempotencyKey.trim(), principal.merchantId());
        if (!repeated.isEmpty()) {
            if (!String.valueOf(order.get("id")).equals(String.valueOf(repeated.get(0).get("orderId")))) {
                throw new BusinessException(ErrorCode.CONFLICT, "幂等键已用于其他订单");
            }
            return order(orderNo, principal.merchantId(), principal.storeId());
        }
        if (((Number) order.get("orderStatus")).intValue() != 1) {
            throw new BusinessException(ErrorCode.CONFLICT, "订单未支付,不能核销");
        }
        if (((Number) order.get("verifyStatus")).intValue() == 1) {
            throw new BusinessException(ErrorCode.CONFLICT, "订单已核销");
        }
 
        String verifyNo = BusinessIdGenerator.next("V");
        jdbcTemplate.update("""
                insert into verify_record(verify_no, order_id, talent_id, card_id, benefit_id, merchant_id,
                                          staff_id, verify_type, verify_amount, subsidy_amount, remark, idempotency_key)
                values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                """,
                verifyNo,
                order.get("id"),
                order.get("talentId"),
                order.get("cardId"),
                order.get("benefitId"),
                order.get("merchantId"),
                    principal.operatorId(),
                request.verifyType(),
                order.get("payAmount"),
                order.get("subsidyAmount"),
                request.remark(), idempotencyKey.trim());
        jdbcTemplate.update("update benefit_order set verify_status = 1 where order_no = ? and verify_status = 0", orderNo);
        return order(orderNo, principal.merchantId(), principal.storeId());
    }
 
    @Transactional
    public Map<String, Object> revokeVerification(MerchantPrincipal principal, MerchantRevokeVerificationRequest request, String idempotencyKey) {
        if (idempotencyKey == null || idempotencyKey.isBlank()) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, "缺少幂等键");
        }
        String normalizedIdempotencyKey = idempotencyKey.trim();
        Long orderId;
        try {
            orderId = Long.valueOf(request.orderId().trim());
        } catch (NumberFormatException exception) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, "订单编号无效");
        }
        List<Map<String, Object>> keyOwner = query("""
                select order_id from verify_record where revoke_idempotency_key = ? limit 1
                """, normalizedIdempotencyKey);
        if (!keyOwner.isEmpty() && number(keyOwner.get(0).get("orderId")) != orderId) {
            throw new BusinessException(ErrorCode.CONFLICT, "幂等键已用于其他订单");
        }
        List<Map<String, Object>> repeated = query("""
                select vr.revoked_at
                from verify_record vr
                join benefit_order o on o.id = vr.order_id
                where vr.revoke_idempotency_key = ? and o.id = ? and o.deleted = 0
                  and o.merchant_id = ? and (o.store_id is null or o.store_id = ?)
                limit 1
                """, normalizedIdempotencyKey, orderId, principal.merchantId(), principal.storeId());
        if (!repeated.isEmpty()) {
            return revokeResult(orderId, time(repeated.get(0).get("revokedAt")));
        }
        List<Map<String, Object>> orders = query("""
                select o.id, o.order_no, o.order_type, o.order_status, o.verify_status,
                       o.merchant_id, o.store_id, vr.id verify_record_id, vr.verify_time
                from benefit_order o
                left join verify_record vr on vr.order_id = o.id and vr.status = 1
                where o.id = ? and o.deleted = 0 and o.merchant_id = ? and (o.store_id is null or o.store_id = ?)
                for update
                """, orderId, principal.merchantId(), principal.storeId());
        if (orders.isEmpty()) throw new BusinessException(ErrorCode.NOT_FOUND, "订单不存在");
        Map<String, Object> order = orders.get(0);
        if (!"GROUP_BUY".equals(String.valueOf(order.get("orderType")))) {
            throw new BusinessException(ErrorCode.CONFLICT, "当前业务类型不支持撤销核销");
        }
        if (number(order.get("verifyStatus")) == null || number(order.get("verifyStatus")) != 1
                || number(order.get("verifyRecordId")) == null) {
            throw new BusinessException(ErrorCode.CONFLICT, "订单当前不可撤销核销");
        }
        LocalDateTime verifyTime = time(order.get("verifyTime"));
        if (verifyTime == null || Duration.between(verifyTime, LocalDateTime.now()).toHours() >= REVOCATION_HOURS) {
            throw new BusinessException(ErrorCode.CONFLICT, "已过可撤销时间");
        }
        String reason = request.reason() == null || request.reason().isBlank() ? "商户撤销核销" : request.reason().trim();
        int updated = jdbcTemplate.update("""
                update verify_record set status = 2, revoked_at = now(), revoked_by = ?, revoke_reason = ?, revoke_idempotency_key = ?
                where id = ? and status = 1
                """, principal.operatorId(), reason, normalizedIdempotencyKey, number(order.get("verifyRecordId")));
        if (updated == 0) throw new BusinessException(ErrorCode.CONFLICT, "核销已被处理,请刷新后重试");
        jdbcTemplate.update("update benefit_order set verify_status = 0 where id = ? and verify_status = 1", orderId);
        return revokeResult(orderId, LocalDateTime.now());
    }
 
    private Map<String, Object> revokeResult(Long orderId, LocalDateTime revokedAt) {
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("orderId", String.valueOf(orderId));
        result.put("orderStatus", "pending_verification");
        result.put("orderStatusText", "待核销");
        result.put("revokedAt", (revokedAt == null ? LocalDateTime.now() : revokedAt).toString());
        return result;
    }
 
    private Map<String, Object> enrichOrder(Map<String, Object> order) {
        Map<String, Object> result = new LinkedHashMap<>(order);
        String orderType = String.valueOf(order.get("orderType"));
        String category = "GROUP_BUY".equals(orderType) ? "group" : ("STORE_CONSUME".equals(orderType) ? "store" : "stay");
        Long orderStatus = number(order.get("orderStatus"));
        Long verifyStatus = number(order.get("verifyStatus"));
        String status = orderStatus != null && orderStatus == 0 ? "pending_payment" : (verifyStatus != null && verifyStatus == 1 ? "completed" : "pending_verification");
        result.put("category", category);
        result.put("status", status);
        result.put("statusText", "pending_payment".equals(status) ? "待支付" : ("completed".equals(status) ? "已完成" : "待核销"));
        result.put("customerName", maskName(String.valueOf(order.get("talentName"))));
        result.put("customerMobile", maskMobile(String.valueOf(order.get("talentMobile"))));
        result.put("title", order.get("benefitName") == null ? ("store".equals(category) ? "到店消费订单" : "团购订单") : String.valueOf(order.get("benefitName")));
        LocalDateTime verifyTime = time(order.get("verifyTime"));
        boolean canRevoke = "GROUP_BUY".equals(orderType) && verifyTime != null && Duration.between(verifyTime, LocalDateTime.now()).toHours() < REVOCATION_HOURS && verifyStatus != null && verifyStatus == 1;
        result.put("canRevoke", canRevoke);
        result.put("revokeDeadline", verifyTime == null ? null : verifyTime.plusHours(REVOCATION_HOURS).toString());
        result.put("revokeReason", canRevoke ? "" : ("GROUP_BUY".equals(orderType) ? "已过可撤销时间" : "当前业务类型不支持撤销核销"));
        return result;
    }
 
    private List<Map<String, Object>> query(String sql, Object... args) {
        return DatabaseRows.normalize(jdbcTemplate.queryForList(sql, args));
    }
 
    private OrderFilters filters(MerchantOrderQuery query) {
        MerchantOrderQuery value = query == null ? new MerchantOrderQuery(null, null, null, null) : query;
        StringBuilder conditions = new StringBuilder();
        List<Object> arguments = new ArrayList<>();
        String category = normalize(value.category());
        if (!category.isEmpty()) {
            String orderType = switch (category) {
                case "group" -> "GROUP_BUY";
                case "store" -> "STORE_CONSUME";
                case "stay" -> "FREE_STAY";
                default -> throw new BusinessException(ErrorCode.BAD_REQUEST, "订单业务类型无效");
            };
            conditions.append(" and o.order_type = ?");
            arguments.add(orderType);
        }
        String status = normalize(value.status());
        if (!status.isEmpty() && !"all".equals(status)) {
            switch (status) {
                case "pending_verification" -> conditions.append(" and o.order_status = 1 and o.verify_status = 0");
                case "pending_payment" -> conditions.append(" and o.order_status = 0");
                case "completed" -> conditions.append(" and o.order_status = 1 and o.verify_status = 1");
                default -> throw new BusinessException(ErrorCode.BAD_REQUEST, "订单状态无效");
            }
        }
        LocalDate startDate = date(value.startDate(), "开始日期");
        LocalDate endDate = date(value.endDate(), "结束日期");
        if (startDate != null && endDate != null && startDate.isAfter(endDate)) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, "开始日期不能晚于结束日期");
        }
        if (startDate != null) {
            conditions.append(" and o.created_at >= ?");
            arguments.add(Timestamp.valueOf(startDate.atStartOfDay()));
        }
        if (endDate != null) {
            conditions.append(" and o.created_at < ?");
            arguments.add(Timestamp.valueOf(endDate.plusDays(1).atStartOfDay()));
        }
        return new OrderFilters(conditions.toString(), arguments);
    }
 
    private Map<String, Object> toListItem(Map<String, Object> order) {
        Map<String, Object> result = new LinkedHashMap<>(order);
        String category = category(String.valueOf(order.get("orderType")));
        String status = status(number(order.get("orderStatus")), number(order.get("verifyStatus")));
        result.put("category", category);
        result.put("status", status);
        result.put("statusText", statusText(status));
        result.put("customerName", maskName(String.valueOf(order.get("talentName"))));
        result.put("customerMobile", maskMobile(String.valueOf(order.get("talentMobile"))));
        result.put("title", order.get("benefitName") == null ? categoryTitle(category) : String.valueOf(order.get("benefitName")));
        return result;
    }
 
    private String category(String orderType) {
        if ("GROUP_BUY".equals(orderType)) return "group";
        if ("STORE_CONSUME".equals(orderType)) return "store";
        if ("FREE_STAY".equals(orderType)) return "stay";
        return "group";
    }
 
    private String status(Long orderStatus, Long verifyStatus) {
        if (orderStatus != null && orderStatus == 0) return "pending_payment";
        if (verifyStatus != null && verifyStatus == 1) return "completed";
        return "pending_verification";
    }
 
    private String statusText(String status) {
        if ("pending_payment".equals(status)) return "待支付";
        if ("completed".equals(status)) return "已完成";
        return "待核销";
    }
 
    private String categoryTitle(String category) {
        if ("store".equals(category)) return "到店消费订单";
        if ("stay".equals(category)) return "免费入住";
        return "团购订单";
    }
 
    private String maskName(String value) {
        if (value == null || value.isBlank() || "null".equals(value)) return "";
        return value.length() == 1 ? value + "*" : value.substring(0, 1) + "*".repeat(value.length() - 1);
    }
 
    private String maskMobile(String value) {
        if (value == null || value.length() < 7 || "null".equals(value)) return "";
        return value.substring(0, 3) + "****" + value.substring(value.length() - 4);
    }
 
    private String normalize(String value) {
        return value == null ? "" : value.trim();
    }
 
    private LocalDate date(String value, String field) {
        if (value == null || value.isBlank()) return null;
        try {
            return LocalDate.parse(value);
        } catch (Exception exception) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, field + "格式无效");
        }
    }
 
    private Long number(Object value) {
        return value instanceof Number number ? number.longValue() : null;
    }
 
    private LocalDateTime time(Object value) {
        if (value instanceof LocalDateTime dateTime) return dateTime;
        if (value instanceof Timestamp timestamp) return timestamp.toLocalDateTime();
        return null;
    }
 
    private record OrderFilters(String conditions, List<Object> arguments) {
    }
}