yeg
2026-09-29 b78295e8da96c3e5e76befeef9582ce5273dbb74
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.battery.business.mapper.TTestMapper">
    <resultMap id="CurrentBatteryFieldResultMap" type="CurrentBatteryField">
        <id property="fieldId" column="field_id"/>
        <result property="relationId" column="relation_id"/>
        <result property="fieldName" column="field_name"/>
        <result property="fieldType" column="field_type"/>
        <result property="fieldValue" column="field_value"/>
    </resultMap>
 
    <resultMap id="TTestResultMap" type="TTest">
        <id property="testId" column="test_id" />
        <result property="testName" column="test_name" />
        <result property="creatorId" column="creator_id" />
        <result property="creatorName" column="creator_name" />
        <result property="principalId" column="principal_id" />
        <result property="principalName" column="principal_name" />
        <result property="testTypeId" column="test_type_id" />
        <result property="testTypeName" column="test_type_name" />
        <result property="testPurpose" column="test_purpose" />
        <result property="testStatus" column="test_status" />
        <result property="receptionStatus" column="reception_status" />
        <result property="monitorTimeoutMinutes" column="monitor_timeout_minutes" />
        <result property="startedAtUtc" column="started_at_utc" />
        <result property="receptionBoundaryAtUtc" column="reception_boundary_at_utc" />
        <result property="endedAtUtc" column="ended_at_utc" />
        <result property="runtimeAttach" column="runtime_attach" />
        <result property="delFlag" column="del_flag" />
        <result property="createBy" column="create_by" />
        <result property="createTime" column="create_time" />
        <result property="updateBy" column="update_by" />
        <result property="updateTime" column="update_time" />
        <result property="remark" column="remark" />
        <result property="logicStepMappingsJson" column="logic_step_mappings_json" />
        <result property="consoleDetailJson" column="console_detail_json" />
        <result property="batteryCount" column="battery_count" />
        <result property="batteryNo" column="battery_no" />
    </resultMap>
 
    <resultMap id="TTestBatteryResultMap" type="TTestBattery">
        <id property="relationId" column="test_battery_id" />
        <result property="testBatteryId" column="test_battery_id" />
        <result property="testId" column="test_id" />
        <result property="groupId" column="group_id" />
        <result property="groupName" column="group_name" />
        <result property="batteryNo" column="battery_no" />
        <result property="collectorId" column="collector_id" />
        <result property="collectorName" column="collector_name" />
        <result property="delFlag" column="del_flag" />
    </resultMap>
 
<resultMap id="TTestBindingResultMap" type="TTestChannelBinding">
        <id property="bindingId" column="binding_id" />
        <result property="testId" column="test_id" />
        <result property="batteryRelationId" column="test_battery_id" />
        <result property="testBatteryId" column="test_battery_id" />
        <result property="channelId" column="channel_id" />
        <result property="expectedBarcode" column="expected_barcode" />
        <result property="claimStatus" column="claim_status" />
        <result property="cabinetId" column="cabinet_id" />
        <result property="cabinetCode" column="cabinet_code" />
        <result property="cabinetName" column="cabinet_name" />
        <result property="adapterCode" column="adapter_code" />
        <result property="devtype" column="devtype" />
        <result property="devid" column="devid" />
        <result property="subdevid" column="subdevid" />
        <result property="chlid" column="chlid" />
        <result property="displayNo" column="display_no" />
        <result property="adapterTimezoneId" column="adapter_timezone_id" />
    </resultMap>
 
    <resultMap id="TTestCollectorChannelResultMap" type="TTestCollectorChannel">
        <id property="mappingId" column="mapping_id" />
        <result property="testId" column="test_id" />
        <result property="batteryRelationId" column="test_battery_id" />
        <result property="testBatteryId" column="test_battery_id" />
        <result property="collectorId" column="collector_id" />
        <result property="measurementCode" column="measurement_code" />
        <result property="measurementName" column="measurement_name" />
        <result property="channelCode" column="channel_code" />
    </resultMap>
 
 
 
    <resultMap id="TTestThresholdResultMap" type="TTestWarningThreshold">
        <id property="thresholdId" column="threshold_id" />
        <result property="testId" column="test_id" />
        <result property="metricCode" column="metric_code" />
        <result property="minValue" column="min_value" />
        <result property="maxValue" column="max_value" />
        <result property="unit" column="unit" />
        <result property="unitMetadata" column="unit_metadata" />
        <result property="severity" column="severity" />
        <result property="delFlag" column="del_flag" />
    </resultMap>
    <resultMap id="TTestWarningExceptionResultMap" type="com.battery.business.domain.TTestWarningException">
        <id property="exceptionId" column="exception_id"/><result property="testId" column="test_id"/>
        <result property="exceptionType" column="exception_type"/>
        <result property="testName" column="test_name"/><result property="sourceType" column="source_type"/>
        <result property="sourceIdentity" column="source_identity"/><result property="metricCode" column="metric_code"/>
        <result property="abnormalValue" column="abnormal_value"/><result property="unit" column="unit"/>
        <result property="ruleSnapshot" column="rule_snapshot"/><result property="severity" column="severity"/>
        <result property="exceptionStatus" column="exception_status"/><result property="firstOccurredAtUtc" column="first_occurred_at_utc"/>
        <result property="lastOccurredAtUtc" column="last_occurred_at_utc"/><result property="occurrenceCount" column="occurrence_count"/>
        <result property="handledBy" column="handled_by"/><result property="handledByName" column="handled_by_name"/>
        <result property="handledAtUtc" column="handled_at_utc"/><result property="handlingNote" column="handling_note"/>
    </resultMap>
 
<sql id="selectTestBase">
        select t.test_id, t.test_name, t.creator_id, creator.nick_name creator_name,
               t.principal_id, principal.nick_name principal_name,
               t.test_type_id, ty.test_type_name, t.test_purpose,
               t.test_status,
               t.reception_status, t.monitor_timeout_minutes,
               t.started_at_utc, t.reception_boundary_at_utc, t.ended_at_utc, t.del_flag,
               t.create_by, t.create_time, t.update_by, t.update_time, t.remark,
               cast(t.logic_step_mappings_json as char) logic_step_mappings_json,
               cast(t.console_detail_json as char) console_detail_json,
               (select count(1) from t_test_battery b where b.test_id = t.test_id and b.del_flag = 0) battery_count,
               0 runtime_attach
        from t_test t
        left join sys_user creator on creator.user_id = t.creator_id and creator.del_flag = '0'
        left join sys_user principal on principal.user_id = t.principal_id and principal.del_flag = '0'
        left join t_test_type ty on ty.test_type_id = t.test_type_id and ty.del_flag = 0
    </sql>
 
    <select id="selectTestList" parameterType="TTest" resultMap="TTestResultMap">
        <include refid="selectTestBase" />
        <where>
            t.del_flag = 0
            <if test="testId != null">and t.test_id = #{testId}</if>
            <if test="testName != null and testName != ''">and t.test_name like concat('%', #{testName}, '%')</if>
            <if test="testTypeId != null">and t.test_type_id = #{testTypeId}</if>
            <if test="batteryNo != null and batteryNo != ''">and exists (select 1 from t_test_battery fb where fb.test_id = t.test_id and fb.battery_no = #{batteryNo} and fb.del_flag = 0)</if>
            <if test="testStatus != null and testStatus != ''">
                and (
                    (#{testStatus} = 'RUNNING' and t.test_status = 'RUNNING')
                    or (#{testStatus} = 'COMPLETED' and t.test_status in ('COMPLETED', 'COMPLETION_PENDING', 'TERMINATED'))
                    or (#{testStatus} not in ('RUNNING', 'RUNNING_ABNORMAL', 'COMPLETED') and t.test_status = #{testStatus})
                )
            </if>
            <if test="receptionStatus != null and receptionStatus != ''">and t.reception_status = #{receptionStatus}</if>
            <if test="beginCreateTime != null">and t.create_time &gt;= #{beginCreateTime}</if>
            <if test="endCreateTime != null">and t.create_time &lt;= #{endCreateTime}</if>
        </where>
        order by t.create_time desc, t.test_id desc
    </select>
 
    <select id="selectBatteryNosByTestIds" resultMap="TTestBatteryResultMap">
        select test_id, test_battery_id, battery_no
        from t_test_battery
        where del_flag = 0 and test_id in
        <foreach collection="testIds" item="testId" open="(" separator="," close=")">#{testId}</foreach>
        order by test_id, test_battery_id
    </select>
 
    <select id="selectTestById" parameterType="Long" resultMap="TTestResultMap">
        <include refid="selectTestBase" />
        where t.test_id = #{testId} and t.del_flag = 0
    </select>
 
    <select id="selectTestByIdForUpdate" parameterType="Long" resultMap="TTestResultMap">
        <include refid="selectTestBase" />
        where t.test_id = #{testId} and t.del_flag = 0
        for update
    </select>
 
    <select id="selectTestByName" parameterType="String" resultMap="TTestResultMap">
        <include refid="selectTestBase" />
        where t.test_name = #{testName} and t.del_flag = 0 limit 1
    </select>
 
    <insert id="insertTest" parameterType="TTest" useGeneratedKeys="true" keyProperty="testId">
        insert into t_test
        (test_name, creator_id, principal_id, test_type_id, test_purpose, test_status, reception_status,
         monitor_timeout_minutes, del_flag, create_by, create_time, remark)
        values
        (#{testName}, #{creatorId}, #{principalId}, #{testTypeId}, #{testPurpose}, #{testStatus}, #{receptionStatus},
         #{monitorTimeoutMinutes}, 0, #{createBy}, #{createTime}, #{remark})
    </insert>
    <resultMap id="TTestDataRevisionActionResultMap" type="com.battery.business.domain.TTestDataRevisionAction">
        <id property="actionId" column="action_id"/>
        <result property="testId" column="test_id"/><result property="testName" column="test_name"/>
        <result property="testReceptionStatus" column="reception_status"/>
        <result property="dataType" column="data_type"/><result property="operationType" column="operation_type"/>
        <result property="scopeSummary" column="scope_summary"/><result property="identitySummary" column="identity_summary"/>
        <result property="changesSummary" column="changes_summary"/><result property="reason" column="reason"/>
        <result property="beforeContentJson" column="before_content_json"/>
        <result property="affectedRecordCount" column="affected_record_count"/>
        <result property="operatorId" column="operator_id"/><result property="operatorName" column="operator_name"/>
        <result property="createdAtUtc" column="created_at_utc"/>
    </resultMap>
    <select id="selectDataRevisionActions" parameterType="com.battery.business.domain.TTestDataRevisionAction" resultMap="TTestDataRevisionActionResultMap">
        <!-- 列表只查询和排序摘要字段,不加载批量明细 JSON。 -->
        select a.action_id, a.test_id, t.test_name, t.reception_status,
               a.data_type, a.operation_type, a.scope_summary, a.reason,
               a.operator_id, a.operator_name, a.created_at_utc
        from t_test_data_revision_action a join t_test t on t.test_id = a.test_id
        <where>
            <if test="testId != null">and a.test_id = #{testId}</if>
            <if test="testName != null and testName != ''">and t.test_name like concat('%', #{testName}, '%')</if>
            <if test="dataType != null and dataType != ''">and a.data_type = #{dataType}</if>
            <if test="operationType != null and operationType != ''">and a.operation_type = #{operationType}</if>
            <if test="beginCreatedAt != null">and a.created_at_utc &gt;= #{beginCreatedAt}</if>
            <if test="endCreatedAt != null">and a.created_at_utc &lt; #{endCreatedAt}</if>
        </where>
        order by a.created_at_utc desc, a.action_id desc
    </select>
    <select id="selectDataRevisionActionById" parameterType="long" resultMap="TTestDataRevisionActionResultMap">
        <!-- 非编辑只返回摘要和数量,避免把批量明细加载到服务层;完整审计快照仍留在数据库。 -->
        select a.action_id, a.test_id, t.test_name, t.reception_status,
               a.data_type, a.operation_type, a.scope_summary,
               coalesce(json_length(a.identity_summary), 0) affected_record_count,
               case when a.operation_type = 'EDIT' then cast(a.identity_summary as char) end identity_summary,
               case when a.operation_type = 'EDIT' then cast(a.changes_summary as char) end changes_summary,
               a.reason, a.operator_id, a.operator_name, a.created_at_utc
        from t_test_data_revision_action a join t_test t on t.test_id = a.test_id
        where a.action_id = #{actionId}
    </select>
 
    <update id="updateTest" parameterType="TTest">
        update t_test
        set test_name = #{testName}, principal_id = #{principalId}, test_type_id = #{testTypeId},
            test_purpose = #{testPurpose}, monitor_timeout_minutes = #{monitorTimeoutMinutes},
            remark = #{remark}, update_by = #{updateBy}, update_time = #{updateTime}
        where test_id = #{testId} and test_status = 'WAITING' and reception_status = 'NOT_STARTED' and del_flag = 0
    </update>
 
    <delete id="deleteTestById">
        delete from t_test
        where test_id = #{testId}
    </delete>
 
    <delete id="deleteTestBindingsByTestId">delete from t_test_channel_binding where test_id = #{testId}</delete>
    <delete id="deleteTestCollectorChannelsByTestId">delete from t_test_collector_channel where test_id = #{testId}</delete>
    <delete id="deleteTestThresholdRowsByTestId">delete from t_test_warning_threshold where test_id = #{testId}</delete>
    <delete id="deleteTestBatteriesByTestId">
        delete from t_test_battery where test_id = #{testId} and del_flag = 0
    </delete>
    <update id="deleteTestThresholdsByTestId">
        update t_test_warning_threshold set del_flag = threshold_id where test_id = #{testId} and del_flag = 0
    </update>
 
    <insert id="insertTestBattery" parameterType="TTestBattery" useGeneratedKeys="true" keyProperty="relationId">
        insert into t_test_battery(test_id, group_id, battery_no, collector_id, del_flag)
        values(#{testId}, #{groupId}, #{batteryNo}, #{collectorId}, 0)
    </insert>
    <insert id="insertTestChannelBinding" parameterType="TTestChannelBinding" useGeneratedKeys="true" keyProperty="bindingId">
        insert into t_test_channel_binding(test_id, test_battery_id, channel_id, expected_barcode, claim_status)
        values(#{testId}, #{batteryRelationId}, #{channelId}, #{expectedBarcode}, #{claimStatus})
    </insert>
    <insert id="insertTestCollectorChannel" parameterType="TTestCollectorChannel" useGeneratedKeys="true" keyProperty="mappingId">
        insert into t_test_collector_channel
        (test_id, test_battery_id, collector_id, measurement_code, measurement_name, channel_code)
        values(#{testId}, #{batteryRelationId}, #{collectorId}, #{measurementCode}, #{measurementName}, #{channelCode})
    </insert>
    <insert id="insertTestThreshold" parameterType="TTestWarningThreshold" useGeneratedKeys="true" keyProperty="thresholdId">
        insert into t_test_warning_threshold(test_id, metric_code, min_value, max_value, unit, severity, del_flag)
        values(#{testId}, #{metricCode}, #{minValue}, #{maxValue}, #{unit}, #{severity}, 0)
    </insert>
 
    <select id="selectTestBatteries" parameterType="Long" resultMap="TTestBatteryResultMap">
        select battery.test_battery_id, battery.test_id, battery.group_id, battery_group.group_name,
               battery.battery_no, battery.collector_id, collector.collector_name, battery.del_flag
        from t_test_battery battery
        join t_battery_group battery_group on battery_group.group_id = battery.group_id
        left join t_collector collector on collector.collector_id = battery.collector_id
        where battery.test_id = #{testId} and battery.del_flag = 0
        order by battery.test_battery_id
    </select>
    <select id="selectCurrentBatteryFields" parameterType="Long" resultMap="CurrentBatteryFieldResultMap">
        select battery.test_battery_id as relation_id, relation.battery_group_field_id as field_id,
               definition.field_name, definition.field_type, relation.field_value, relation.del_flag
        from t_test_battery battery
        join t_battery_group_relation_field relation on relation.group_id = battery.group_id and relation.del_flag = 0
        join t_battery_group_field definition on definition.field_id = relation.battery_group_field_id
             and definition.del_flag = 0
        where battery.test_id = #{testId} and battery.del_flag = 0
        order by battery.test_battery_id, relation.relation_id
    </select>
    <select id="selectTestChannelBindings" parameterType="Long" resultMap="TTestBindingResultMap">
        select binding.binding_id, binding.test_id, binding.test_battery_id, binding.channel_id,
               binding.expected_barcode, binding.claim_status, channel_fact.cabinet_id,
               cabinet.cabinet_code, cabinet.cabinet_name,
               channel_fact.adapter_code adapter_code,
               coalesce(adapter.timezone_id, 'Asia/Hong_Kong') adapter_timezone_id,
               channel_fact.devtype, channel_fact.devid, channel_fact.subdevid, channel_fact.chlid, channel_fact.display_no
        from t_test_channel_binding binding
        join t_detection_channel channel_fact on channel_fact.channel_id = binding.channel_id
            and channel_fact.status = '0' and channel_fact.del_flag = 0
        join t_detection_cabinet cabinet on cabinet.cabinet_id = channel_fact.cabinet_id
            and cabinet.status = '0' and cabinet.del_flag = 0
            and cabinet.registration_status = 'REGISTERED'
        left join t_device_adapter adapter on adapter.adapter_id = channel_fact.adapter_id and adapter.del_flag = 0
        where binding.test_id = #{testId} order by binding.binding_id
    </select>
    <select id="selectTestCollectorChannels" parameterType="Long" resultMap="TTestCollectorChannelResultMap">
        select mapping_id, test_id, test_battery_id, collector_id,
               measurement_code, measurement_name, channel_code
        from t_test_collector_channel where test_id = #{testId}
        order by test_battery_id, mapping_id
    </select>
    <select id="selectTestThresholds" parameterType="Long" resultMap="TTestThresholdResultMap">
        select threshold_id, test_id, metric_code, min_value, max_value, unit, severity, del_flag
        from t_test_warning_threshold where test_id = #{testId} and del_flag = 0 order by threshold_id
    </select>
    <insert id="upsertWarningException">
        insert into t_test_warning_exception
        (test_id, threshold_id, source_type, source_identity, metric_code, abnormal_value, unit, rule_snapshot, severity,
         exception_status, first_occurred_at_utc, last_occurred_at_utc, occurrence_count)
        values (#{testId}, #{thresholdId}, #{sourceType}, #{sourceIdentity}, #{metricCode}, #{value}, #{unit},
                cast(#{ruleSnapshot} as json), #{severity}, 'OPEN', #{occurredAt}, #{occurredAt}, 1)
        on duplicate key update abnormal_value = values(abnormal_value), unit = values(unit),
            last_occurred_at_utc = values(last_occurred_at_utc), occurrence_count = occurrence_count + 1,
            source_identity = values(source_identity), severity = values(severity), rule_snapshot = values(rule_snapshot)
    </insert>
    <select id="selectOfflineTestSources" parameterType="Long" resultType="com.battery.business.domain.vo.OfflineTestSource">
        select distinct 'CABINET_CHANNEL' as source_type,
               concat(c.adapter_code, ':', c.devtype, ':', c.devid, ':', c.subdevid, ':', c.chlid) as source_identity
        from t_test_channel_binding b
        join t_detection_channel c on c.channel_id = b.channel_id
        join t_detection_cabinet cabinet on cabinet.cabinet_id = c.cabinet_id
        where b.test_id = #{testId} and (c.online_status = 'OFFLINE' or cabinet.online_status = 'OFFLINE')
        union
        select 'COLLECTOR' as source_type, cast(c.collector_id as char) as source_identity
        from t_test_collector_channel b
        join t_collector c on c.collector_id = b.collector_id
        where b.test_id = #{testId} and c.online_status = 'OFFLINE'
    </select>
    <insert id="upsertOfflineException">
        insert into t_test_warning_exception
        (test_id, exception_type, threshold_id, source_type, source_identity, metric_code,
         abnormal_value, unit, rule_snapshot, severity, exception_status,
         first_occurred_at_utc, last_occurred_at_utc, occurrence_count)
        values (#{testId}, 'DEVICE_OFFLINE', null, #{sourceType}, #{sourceIdentity}, 'DEVICE_ONLINE',
                null, '', '{"expectedStatus":"ONLINE"}', 'WARNING', 'OPEN', #{occurredAt}, #{occurredAt}, 1)
        on duplicate key update last_occurred_at_utc = values(last_occurred_at_utc),
            occurrence_count = occurrence_count + 1
    </insert>
    <select id="selectWarningExceptions" resultMap="TTestWarningExceptionResultMap">
        select e.*, t.test_name, u.nick_name handled_by_name
        from t_test_warning_exception e join t_test t on t.test_id=e.test_id
        left join sys_user u on u.user_id=e.handled_by
        <where>
            <if test="testId != null">e.test_id = #{testId}</if>
            <if test="status != null and status != ''">and e.exception_status = #{status}</if>
        </where>
        order by e.last_occurred_at_utc desc, e.exception_id desc
    </select>
    <select id="selectWarningExceptionById" parameterType="long" resultMap="TTestWarningExceptionResultMap">
        select e.*, t.test_name, u.nick_name handled_by_name from t_test_warning_exception e join t_test t on t.test_id=e.test_id
        left join sys_user u on u.user_id=e.handled_by where e.exception_id=#{exceptionId}
    </select>
    <update id="closeWarningException">
        update t_test_warning_exception set exception_status='CLOSED', handled_by=#{handledBy}, handled_at_utc=#{handledAt}, handling_note=#{handlingNote}
        where exception_id=#{exceptionId} and exception_status='OPEN'
    </update>
    <select id="selectReceivingTestIds" resultType="long">
        select test_id from t_test
        where del_flag = 0 and test_status = 'RUNNING' and reception_status = 'RECEIVING'
        order by test_id
    </select>
<insert id="insertRealtimeRecord" parameterType="com.battery.business.domain.TTestRealtimeRecord" useGeneratedKeys="true" keyProperty="recordId">
        insert ignore into t_test_realtime_record
        (test_id, test_battery_id, binding_id, adapter_code, source_identity, source_record_id, cabinet_devtype, cabinet_devid, cabinet_subdevid, cabinet_chlid,
         cabinet_sequence_id, cabinet_device_time_utc, cabinet_device_time_raw, cabinet_adapter_timezone_id,
         collector_id, collector_channel_code, collector_sequence_id, collector_device_time_utc, collector_device_time_raw,
         collector_adapter_timezone_id, capture_slot_utc, server_received_at_utc, cycle_no, step_no, step_type, step_name,
         voltage_v, current_a, capacity_ah, energy_wh, temperature, positive_potential, negative_potential,
         extension_measurements_json, content_sha256)
        values (#{testId}, #{testBatteryId}, #{bindingId}, #{adapterCode}, #{sourceIdentity}, #{sourceRecordId}, #{cabinetDevtype}, #{cabinetDevid}, #{cabinetSubdevid}, #{cabinetChlid},
         #{cabinetSequenceId}, #{cabinetDeviceTimeUtc}, #{cabinetDeviceTimeRaw}, #{cabinetAdapterTimezoneId},
         #{collectorId}, #{collectorChannelCode}, #{collectorSequenceId}, #{collectorDeviceTimeUtc}, #{collectorDeviceTimeRaw},
         #{collectorAdapterTimezoneId}, #{captureSlotUtc}, #{serverReceivedAtUtc}, #{cycleNo}, #{stepNo}, #{stepType}, #{stepName},
         #{voltageV}, #{currentA}, #{capacityAh}, #{energyWh}, #{temperature}, #{positivePotential}, #{negativePotential},
         cast(#{extensionMeasurementsJson} as json), #{contentSha256})
    </insert>
    <select id="selectRealtimeRecordContentHash" resultType="string">
        select lower(hex(content_sha256)) from t_test_realtime_record
        where test_id = #{testId} and test_battery_id = #{testBatteryId} and capture_slot_utc = #{captureSlotUtc}
        limit 1
    </select>
    <select id="selectRealtimeRecordHashBySourceRecord" resultType="string">
        select lower(hex(content_sha256)) from t_test_realtime_record
        where test_battery_id = #{testBatteryId} and source_identity = #{sourceIdentity}
          and source_record_id = #{sourceRecordId}
        limit 1
    </select>
    <insert id="insertStepRecord" parameterType="com.battery.business.domain.TTestStepRecord" useGeneratedKeys="true" keyProperty="stepRecordId">
        insert ignore into t_test_step_record
        (test_id, test_battery_id, binding_id, adapter_code, source_identity, source_record_id, dedupe_key, adapter_timezone_id,
         device_time_utc, device_time_raw, server_received_at_utc, cycle_no, step_no, step_type, step_name,
         voltage_v, current_a, capacity_ah, energy_wh, extension_measurements_json, content_sha256)
        values (#{testId}, #{testBatteryId}, #{bindingId}, #{adapterCode}, #{sourceIdentity}, #{sourceRecordId}, #{dedupeKey}, #{adapterTimezoneId},
         #{deviceTimeUtc}, #{deviceTimeRaw}, #{serverReceivedAtUtc}, #{cycleNo}, #{stepNo}, #{stepType}, #{stepName},
         #{voltageV}, #{currentA}, #{capacityAh}, #{energyWh}, cast(#{extensionMeasurementsJson} as json), #{contentSha256})
    </insert>
    <insert id="insertCycleRecord" parameterType="com.battery.business.domain.TTestCycleRecord" useGeneratedKeys="true" keyProperty="cycleRecordId">
        insert ignore into t_test_cycle_record
        (test_id, test_battery_id, binding_id, adapter_code, source_identity, source_record_id, source_kind, dedupe_key, adapter_timezone_id,
         device_time_utc, device_time_raw, server_received_at_utc, cycle_no, charge_capacity_ah, discharge_capacity_ah,
         charge_energy_wh, discharge_energy_wh, efficiency, extension_measurements_json, content_sha256)
        values (#{testId}, #{testBatteryId}, #{bindingId}, #{adapterCode}, #{sourceIdentity}, #{sourceRecordId}, #{sourceKind}, #{dedupeKey}, #{adapterTimezoneId},
         #{deviceTimeUtc}, #{deviceTimeRaw}, #{serverReceivedAtUtc}, #{cycleNo}, #{chargeCapacityAh}, #{dischargeCapacityAh},
         #{chargeEnergyWh}, #{dischargeEnergyWh}, #{efficiency}, cast(#{extensionMeasurementsJson} as json), #{contentSha256})
    </insert>
    <select id="selectStepRecordContentHash" resultType="string">
        select lower(hex(content_sha256)) from t_test_step_record
        where test_battery_id = #{testBatteryId} and source_identity = #{sourceIdentity} and dedupe_key = #{dedupeKey}
        limit 1
    </select>
    <select id="selectCycleRecordContentHash" resultType="string">
        select lower(hex(content_sha256)) from t_test_cycle_record
        where test_battery_id = #{testBatteryId} and source_identity = #{sourceIdentity} and dedupe_key = #{dedupeKey}
        limit 1
    </select>
 
    <select id="selectPersistedFinalRealtimeRecords" resultType="map">
        select concat('realtime:', r.record_id) id, concat('realtime:', r.record_id) stableIdentity,
               coalesce(r.source_record_id, concat('RT-', r.record_id)) recordNo,
               'SNAPSHOT' sourceType, b.battery_no batteryNo,
               r.cycle_no cycleNo, r.step_no stepNo, r.step_name stepName, r.step_type stepType,
               r.cabinet_sequence_id sequenceId, r.cabinet_device_time_utc deviceTime,
               r.collector_device_time_utc collectorDeviceTime, r.capture_slot_utc captureSlot,
               r.server_received_at_utc serverReceivedAt, r.voltage_v voltage, r.current_a current,
               r.capacity_ah capacity, r.energy_wh energy, r.temperature temperature,
               r.positive_potential positivePotential, r.negative_potential negativePotential,
               cast(r.extension_measurements_json as char) extensionMeasurementsJson,
               r.adapter_code adapterCode, r.cabinet_devtype devtype, r.cabinet_devid deviceId,
               r.cabinet_subdevid subdevid, r.cabinet_chlid channelId, r.collector_id collectorId,
               r.collector_channel_code channelCode, r.source_identity sourceIdentity, r.source_record_id sourceRecordId
        from t_test_realtime_record r join t_test_battery b on b.test_battery_id = r.test_battery_id
        where r.test_id = #{testId} and b.del_flag = 0
        order by coalesce(r.capture_slot_utc, r.cabinet_device_time_utc) desc, r.record_id desc
    </select>
    <select id="selectPersistedFinalStepRecords" resultType="map">
        select concat('step:', r.step_record_id) id, concat('step:', r.step_record_id) stableIdentity,
               coalesce(r.source_record_id, concat('STEP-', r.step_record_id)) recordNo, b.battery_no batteryNo, r.cycle_no cycleNo,
               r.step_no stepNo, r.step_name stepName, r.step_type stepType,
               r.device_time_utc recordedAt, r.device_time_utc absoluteTime,
               r.server_received_at_utc serverReceivedAt, r.voltage_v endVoltage, r.current_a current,
               r.capacity_ah capacity, r.energy_wh energy, r.adapter_code adapterCode,
               cast(r.extension_measurements_json as char) extensionMeasurementsJson,
               r.source_identity sourceIdentity, r.source_record_id sourceRecordId
        from t_test_step_record r join t_test_battery b on b.test_battery_id = r.test_battery_id
        where r.test_id = #{testId} and b.del_flag = 0
        order by r.cycle_no, r.step_no, r.device_time_utc, r.step_record_id
    </select>
    <select id="selectPersistedFinalCycleRecords" resultType="map">
        select concat('cycle:', r.cycle_record_id) id, concat('cycle:', r.cycle_record_id) stableIdentity,
               coalesce(r.source_record_id, concat('CYCLE-', r.cycle_record_id)) recordNo,
               b.battery_no batteryNo, r.cycle_no cycleNo, r.device_time_utc recordedAt,
               r.device_time_utc absoluteTime, r.server_received_at_utc serverReceivedAt,
               r.charge_capacity_ah chargeCapacity, r.discharge_capacity_ah dischargeCapacity,
               r.charge_energy_wh chargeEnergy, r.discharge_energy_wh dischargeEnergy,
               r.efficiency efficiency, r.source_kind sourceKind, r.adapter_code adapterCode,
               r.source_identity sourceIdentity, r.source_record_id sourceRecordId
        from t_test_cycle_record r join t_test_battery b on b.test_battery_id = r.test_battery_id
        where r.test_id = #{testId} and b.del_flag = 0
        order by r.cycle_no, b.battery_no, r.cycle_record_id
    </select>
 
 
 
    <select id="selectLogicStepMappingsJson" resultType="string">
        select cast(logic_step_mappings_json as char) from t_test where test_id = #{testId} and del_flag = 0
    </select>
    <update id="updateLogicStepMappings">
        update t_test set logic_step_mappings_json = cast(#{mappingsJson} as json),
            update_by = #{updateBy}, update_time = #{updateTime}
        where test_id = #{testId} and del_flag = 0
    </update>
    <update id="updateConsoleDetail">
        update t_test set console_detail_json = cast(#{detailJson} as json)
        where test_id = #{testId} and del_flag = 0
    </update>
 
    <select id="countTestTypeEnabled" resultType="int">
        select count(1) from t_test_type where test_type_id = #{testTypeId} and status = '0' and del_flag = 0
    </select>
    <select id="countUserEnabled" resultType="int">
        select count(1) from sys_user where user_id = #{userId} and status = '0' and del_flag = '0'
    </select>
    <select id="countBatteryInEnabledGroup" resultType="int">
        select count(1) from t_battery_group_battery battery
        join t_battery_group battery_group on battery_group.group_id = battery.group_id
        where battery.group_id = #{groupId} and battery.battery_no = #{batteryNo}
          and battery.del_flag = 0 and battery_group.status = '0' and battery_group.del_flag = 0
    </select>
    <select id="countRegisteredChannel" resultType="int">
        select count(1) from t_detection_channel channel_fact
        join t_detection_cabinet cabinet on cabinet.cabinet_id = channel_fact.cabinet_id
        where channel_fact.channel_id = #{channelId} and channel_fact.status = '0' and channel_fact.del_flag = 0
          and cabinet.registration_status = 'REGISTERED' and cabinet.status = '0' and cabinet.del_flag = 0
    </select>
    <select id="countCollectorEnabled" resultType="int">
        select count(1) from t_collector where collector_id = #{collectorId} and status = '0' and del_flag = 0
    </select>
    <select id="selectCollectorChannelCount" resultType="int">
        select channel_count from t_collector where collector_id = #{collectorId} and status = '0' and del_flag = 0
    </select>
    <select id="selectCollectorCode" resultType="string">
        select collector_code from t_collector where collector_id = #{collectorId} and status = '0' and del_flag = 0
    </select>
 
    <select id="selectEnabledUserOptions" resultType="com.battery.business.domain.vo.TestUserOptionVo">
        select user_id userId, user_name userName, nick_name nickName
        from sys_user where status = '0' and del_flag = '0' order by nick_name, user_id
    </select>
    <select id="selectEnabledTestTypeOptions" resultType="com.battery.business.domain.vo.TestTypeOptionVo">
        select test_type_id testTypeId, test_type_name testTypeName
        from t_test_type where status = '0' and del_flag = 0 order by test_type_name, test_type_id
    </select>
    <select id="selectEnabledBatteryOptions" resultType="com.battery.business.domain.vo.TestBatteryOptionVo">
        select battery.relation_id relationId, battery.relation_id testBatteryId, battery.group_id groupId,
               battery_group.group_name groupName, battery.battery_no batteryNo
        from t_battery_group_battery battery
        join t_battery_group battery_group on battery_group.group_id = battery.group_id
        where battery.del_flag = 0 and battery_group.status = '0' and battery_group.del_flag = 0
        order by battery_group.group_name, battery.sort_order, battery.relation_id
    </select>
    <select id="selectRegisteredChannelOptions" resultType="com.battery.business.domain.vo.TestChannelOptionVo">
        select channel_fact.channel_id channelId, channel_fact.cabinet_id cabinetId,
               cabinet.cabinet_code cabinetCode, cabinet.cabinet_name cabinetName,
               channel_fact.adapter_code adapterCode,
               channel_fact.devtype devtype, channel_fact.devid devid, channel_fact.subdevid subdevid,
               channel_fact.chlid chlid, channel_fact.display_no displayNo
        from t_detection_channel channel_fact
        join t_detection_cabinet cabinet on cabinet.cabinet_id = channel_fact.cabinet_id
        left join t_device_adapter adapter on adapter.adapter_id = channel_fact.adapter_id and adapter.del_flag = 0
        where channel_fact.status = '0' and channel_fact.del_flag = 0
          and cabinet.registration_status = 'REGISTERED' and cabinet.status = '0' and cabinet.del_flag = 0
        order by cabinet.cabinet_name, channel_fact.chlid, channel_fact.channel_id
    </select>
    <select id="selectEnabledCollectorOptions" resultType="com.battery.business.domain.vo.TestCollectorOptionVo">
        select collector_id collectorId, collector_code collectorCode, collector_name collectorName,
               channel_count channelCount
        from t_collector where status = '0' and del_flag = 0 order by collector_name, collector_id
    </select>
 
 
 
    <select id="selectReceptionChannelForUpdate" parameterType="Long" resultType="com.battery.business.domain.TDetectionChannel">
        select channel_fact.channel_id channelId, channel_fact.adapter_id adapterId, channel_fact.cabinet_id cabinetId,
               channel_fact.devtype devtype, channel_fact.devid devid, channel_fact.subdevid subdevid,
               channel_fact.chlid chlid, channel_fact.display_no displayNo,
               channel_fact.online_status onlineStatus, channel_fact.work_status workStatus,
               channel_fact.last_seen_at_utc lastSeenAtUtc, channel_fact.status status
        from t_detection_channel channel_fact
        join t_detection_cabinet cabinet on cabinet.cabinet_id = channel_fact.cabinet_id
        where channel_fact.channel_id = #{channelId}
          and channel_fact.del_flag = 0 and channel_fact.status = '0'
          and cabinet.del_flag = 0 and cabinet.status = '0'
          and cabinet.registration_status = 'REGISTERED'
        for update
    </select>
 
 
 
 
<select id="hasReceivingTestForAdapter" resultType="int">
        select count(1)
        from t_test_channel_binding binding
        join t_test test_fact on test_fact.test_id = binding.test_id
        join t_detection_channel channel_fact on channel_fact.channel_id = binding.channel_id
        join t_detection_cabinet cabinet on cabinet.cabinet_id = channel_fact.cabinet_id
        where cabinet.adapter_code = #{adapterCode}
          and test_fact.reception_status = 'RECEIVING'
          and test_fact.del_flag = 0 and channel_fact.del_flag = 0
    </select>
    <select id="selectReceivingChannelsForAdapter" resultType="com.battery.business.domain.TDetectionChannel">
        select distinct channel_fact.channel_id, channel_fact.adapter_id,
               channel_fact.cabinet_id, channel_fact.devtype, channel_fact.devid,
               channel_fact.subdevid, channel_fact.chlid, channel_fact.display_no,
               channel_fact.online_status, channel_fact.work_status, channel_fact.last_seen_at_utc,
               channel_fact.status
        from t_test_channel_binding binding
        join t_test test_fact on test_fact.test_id = binding.test_id
        join t_detection_channel channel_fact on channel_fact.channel_id = binding.channel_id
        join t_detection_cabinet cabinet on cabinet.cabinet_id = channel_fact.cabinet_id
        where cabinet.adapter_code = #{adapterCode}
          and test_fact.reception_status = 'RECEIVING'
          and test_fact.del_flag = 0 and channel_fact.del_flag = 0 and channel_fact.status = '0'
    </select>
    <update id="updateReceptionStarted">
        update t_test
        set test_status = 'RUNNING', reception_status = 'RECEIVING',
            started_at_utc = coalesce(started_at_utc, #{startedAtUtc}),
            reception_boundary_at_utc = #{startedAtUtc},
            update_by = #{updateBy}, update_time = #{startedAtUtc}
        where test_id = #{testId} and test_status = 'WAITING' and reception_status = 'NOT_STARTED' and del_flag = 0
    </update>
    <update id="updateReceptionPaused">
        update t_test
        set test_status = 'PAUSED', reception_status = 'PAUSED', update_by = #{updateBy}, update_time = #{updatedAtUtc}
        where test_id = #{testId} and test_status = 'RUNNING' and reception_status = 'RECEIVING' and del_flag = 0
    </update>
    <update id="updateReceptionResumed">
        update t_test
        set test_status = 'RUNNING', reception_status = 'RECEIVING',
            reception_boundary_at_utc = #{updatedAtUtc}, update_by = #{updateBy}, update_time = #{updatedAtUtc}
        where test_id = #{testId} and test_status = 'PAUSED' and reception_status = 'PAUSED' and del_flag = 0
    </update>
    <update id="updateReceptionStopped">
        update t_test
        set test_status = 'COMPLETED', reception_status = 'ENDED', ended_at_utc = #{endedAtUtc},
            update_by = #{updateBy}, update_time = #{endedAtUtc}
        where test_id = #{testId}
          and ((test_status = 'RUNNING' and reception_status = 'RECEIVING')
            or (test_status = 'PAUSED' and reception_status = 'PAUSED'))
          and del_flag = 0
    </update>
 
 
    <insert id="insertDataRevisionAction" parameterType="com.battery.business.domain.TTestDataRevisionAction"
            useGeneratedKeys="true" keyProperty="actionId">
        insert into t_test_data_revision_action
        (test_id, data_type, operation_type, scope_summary, identity_summary, before_content_json, changes_summary,
         reason, operator_id, operator_name, created_at_utc)
        values (#{testId}, #{dataType}, #{operationType}, #{scopeSummary}, cast(#{identitySummary} as json),
                cast(#{beforeContentJson} as json), cast(#{changesSummary} as json), #{reason}, #{operatorId}, #{operatorName}, #{createdAtUtc})
    </insert>
 
 
 
<delete id="deleteRealtimeRecordsByIds">delete from t_test_realtime_record where test_id=#{testId} and record_id in <foreach collection="recordIds" item="id" open="(" separator="," close=")">#{id}</foreach></delete>
<delete id="deleteStepRecordsByIds">delete from t_test_step_record where test_id=#{testId} and step_record_id in <foreach collection="recordIds" item="id" open="(" separator="," close=")">#{id}</foreach></delete>
    <delete id="deleteCycleRecordsByIds">delete from t_test_cycle_record where test_id=#{testId} and cycle_record_id in <foreach collection="recordIds" item="id" open="(" separator="," close=")">#{id}</foreach></delete>
 
    <delete id="deleteTestRealtimeRecordsByTestId">delete from t_test_realtime_record where test_id=#{testId}</delete>
 
    <delete id="deleteTestStepRecordsByTestId">delete from t_test_step_record where test_id=#{testId}</delete>
    <delete id="deleteTestCycleRecordsByTestId">delete from t_test_cycle_record where test_id=#{testId}</delete>
    <delete id="deleteTestDataRevisionActionsByTestId">delete from t_test_data_revision_action where test_id=#{testId}</delete>
 
 
 
<select id="countTestBatteryNo" resultType="int">
        select count(1) from t_test_battery
        where test_id = #{testId} and battery_no = #{batteryNo} and del_flag = 0
    </select>
    <delete id="deleteTestWarningExceptionsByTestId">delete from t_test_warning_exception where test_id=#{testId}</delete>
    <delete id="deleteTestLogicStepMappingsByTestId">delete from t_test_logic_step_mapping where test_id=#{testId}</delete>
    <sql id="dataTable"><choose><when test="dataType == 'REALTIME'">t_test_realtime_record</when><when test="dataType == 'STEP'">t_test_step_record</when><otherwise>t_test_cycle_record</otherwise></choose></sql>
    <select id="wasAggregateDeleted" resultType="boolean">
        select exists(select 1 from t_test_data_revision_action
        where test_id=#{testId} and data_type=#{dataType} and operation_type='DELETE'
          and json_contains(before_content_json, json_object('test_battery_id', #{testBatteryId},
              'source_identity', #{sourceIdentity}, 'dedupe_key', #{dedupeKey})))
    </select>
    <select id="wasRealtimeSlotDeleted" resultType="boolean">
        select exists(select 1 from t_test_data_revision_action
        where test_id=#{testId} and data_type='REALTIME' and operation_type='DELETE'
          and json_contains(before_content_json, json_object('test_battery_id', #{testBatteryId},
              'capture_slot_utc', #{captureSlotMillis})))
    </select>
    <sql id="dataId"><choose><when test="dataType == 'REALTIME'">record_id</when><when test="dataType == 'STEP'">step_record_id</when><otherwise>cycle_record_id</otherwise></choose></sql>
    <!-- 三类数据表按 dataType 动态取表名,resultMap 映射全列:显式列名需随每次迁移同步,故保留 SELECT *。 -->
    <select id="selectDataRecord" resultType="map">
        select * from <include refid="dataTable"/> where test_id=#{testId} and <include refid="dataId"/>=#{recordId} for update
    </select>
    <!-- 列名仅来自服务端固定字段映射,客户端不能传入 SQL 标识符。 -->
    <update id="updateDataRecord">
        update <include refid="dataTable"/> set
        <foreach collection="values" index="column" item="value" separator=",">${column}=#{value}</foreach>
        where test_id=#{testId} and <include refid="dataId"/>=#{recordId}
    </update>
    <delete id="deleteDataRecord">
        delete from <include refid="dataTable"/> where test_id=#{testId} and <include refid="dataId"/>=#{recordId}
    </delete>
    <select id="selectImportBinding" resultType="map">
        select b.test_battery_id, binding.binding_id, cabinet.adapter_code, ch.devtype, ch.devid, ch.subdevid, ch.chlid
        from t_test_battery b join t_test_channel_binding binding on binding.test_battery_id=b.test_battery_id
        join t_detection_channel ch on ch.channel_id=binding.channel_id
        join t_detection_cabinet cabinet on cabinet.cabinet_id=ch.cabinet_id
        where b.test_id=#{testId} and b.battery_no=#{batteryNo}
    </select>
    <!-- 显式按 UTC 日期对象读取,避免 JDBC 驱动将 DATETIME 返回为 LocalDateTime 后破坏幂等比较。 -->
    <resultMap id="ImportDataRecordMap" type="java.util.LinkedHashMap" autoMapping="true">
        <result property="capture_slot_utc" column="capture_slot_utc" javaType="java.util.Date" jdbcType="TIMESTAMP"/>
        <result property="cabinet_device_time_utc" column="cabinet_device_time_utc" javaType="java.util.Date" jdbcType="TIMESTAMP"/>
        <result property="device_time_utc" column="device_time_utc" javaType="java.util.Date" jdbcType="TIMESTAMP"/>
    </resultMap>
    <select id="selectImportDataRecords" resultMap="ImportDataRecordMap">
        select * from <include refid="dataTable"/> where test_id=#{testId}
    </select>
    <insert id="insertImportedDataRecord">
        insert into <include refid="dataTable"/>
        (<foreach collection="values" index="column" item="value" separator=",">${column}</foreach>)
        values (<foreach collection="values" index="column" item="value" separator=",">#{value}</foreach>)
    </insert>
</mapper>