yeg
2026-09-01 0fcd0642efdff8d4e0584fa991aaea2178bc932b
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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
<?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.ruoyi.system.mapper.TTestMapper">
 
    <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="endedAtUtc" column="ended_at_utc" />
        <result property="runtimeAttach" column="runtime_attach" />
        <result property="backfillStatus" column="backfill_status" />
        <result property="backfillStartedAtUtc" column="backfill_started_at_utc" />
        <result property="backfillCompletedAtUtc" column="backfill_completed_at_utc" />
        <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="batteryCount" column="battery_count" />
        <result property="batteryNo" column="battery_no" />
    </resultMap>
 
    <resultMap id="TTestBatteryResultMap" type="TTestBattery">
        <id property="relationId" column="relation_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="TTestBatteryFieldResultMap" type="TTestBatteryField">
        <id property="fieldId" column="field_id" />
        <result property="relationId" column="relation_id" />
        <result property="fieldName" column="field_name" />
        <result property="fieldValue" column="field_value" />
        <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="battery_relation_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" />
    </resultMap>
 
    <resultMap id="TTestCollectorChannelResultMap" type="TTestCollectorChannel">
        <id property="mappingId" column="mapping_id" />
        <result property="testId" column="test_id" />
        <result property="batteryRelationId" column="battery_relation_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="TTestPlanStepResultMap" type="TTestPlanStep">
        <id property="planStepId" column="plan_step_id" />
        <result property="testId" column="test_id" />
        <result property="cycleNo" column="cycle_no" />
        <result property="stepNo" column="step_no" />
        <result property="stepType" column="step_type" />
        <result property="stepName" column="step_name" />
        <result property="parametersJson" column="parameters_json" />
        <result property="sortOrder" column="sort_order" />
    </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="integrityConclusion" column="integrity_conclusion" />
        <result property="severity" column="severity" />
        <result property="delFlag" column="del_flag" />
    </resultMap>
 
    <resultMap id="TTestResultResultMap" type="TTestResult">
        <id property="resultId" column="result_id" />
        <result property="relationId" column="relation_id" />
        <result property="testId" column="test_id" />
        <result property="channelNo" column="channel_no" />
        <result property="resultValue" column="result_value" />
        <result property="resultTime" column="result_time" />
        <result property="exceptionInfo" column="exception_info" />
        <result property="delFlag" column="del_flag" />
    </resultMap>
    <resultMap id="TTestCollectorExceptionIntervalResultMap" type="TTestCollectorExceptionInterval">
        <id property="intervalId" column="interval_id" />
        <result property="testId" column="test_id" />
        <result property="batteryRelationId" column="battery_relation_id" />
        <result property="collectorId" column="collector_id" />
        <result property="collectorCode" column="collector_code" />
        <result property="collectorName" column="collector_name" />
        <result property="collectorChannelCode" column="collector_channel_code" />
        <result property="measurementName" column="measurement_name" />
        <result property="exceptionType" column="exception_type" />
        <result property="openedAtUtc" column="opened_at_utc" />
        <result property="missingFromUtc" column="missing_from_utc" />
        <result property="recoveredAtUtc" column="recovered_at_utc" />
        <result property="missingToUtc" column="missing_to_utc" />
        <result property="intervalStatus" column="interval_status" />
        <result property="detail" column="detail" />
    </resultMap>
    <resultMap id="TTestReceptionIntervalResultMap" type="TTestReceptionInterval">
        <id property="intervalId" column="interval_id" />
        <result property="testId" column="test_id" />
        <result property="bindingId" column="binding_id" />
        <result property="sourceType" column="source_type" />
        <result property="sourceId" column="source_id" />
        <result property="sourceChannelCode" column="source_channel_code" />
        <result property="actionAtUtc" column="action_at_utc" />
        <result property="startBoundaryAtUtc" column="start_boundary_at_utc" />
        <result property="endBoundaryAtUtc" column="end_boundary_at_utc" />
        <result property="boundaryNote" column="boundary_note" />
        <result property="intervalStatus" column="interval_status" />
    </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,
               case when t.test_status = 'RUNNING'
                         and exists (select 1 from t_test_collector_exception_interval exception_fact
                                     where exception_fact.test_id = t.test_id
                                       and exception_fact.interval_status = 'OPEN')
                    then 'RUNNING_ABNORMAL'
                    else t.test_status end test_status,
               t.reception_status, t.monitor_timeout_minutes,
               t.started_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,
               (select count(1) from t_test_battery b where b.test_id = t.test_id and b.del_flag = 0) battery_count,
               t.runtime_attach runtime_attach, t.backfill_status, t.backfill_started_at_utc,
               t.backfill_completed_at_utc
        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_ABNORMAL' and t.test_status = 'RUNNING'
                        and exists (select 1 from t_test_collector_exception_interval exception_fact
                                    where exception_fact.test_id = t.test_id and exception_fact.interval_status = 'OPEN'))
                    or (#{testStatus} = 'RUNNING' and t.test_status = 'RUNNING'
                        and not exists (select 1 from t_test_collector_exception_interval exception_fact
                                        where exception_fact.test_id = t.test_id and exception_fact.interval_status = 'OPEN'))
                    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, 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, relation_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.ruoyi.system.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="operatorId" column="operator_id"/><result property="operatorName" column="operator_name"/>
        <result property="createdAtUtc" column="created_at_utc"/>
    </resultMap>
    <select id="selectDataRevisionActions" parameterType="com.ruoyi.system.domain.TTestDataRevisionAction" resultMap="TTestDataRevisionActionResultMap">
        select a.action_id, a.test_id, t.test_name, t.reception_status,
               a.data_type, a.operation_type, a.scope_summary,
               cast(a.identity_summary as char) identity_summary,
               cast(a.changes_summary as char) 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>
            <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,
               cast(a.identity_summary as char) identity_summary,
               cast(a.changes_summary as char) 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 reception_status = 'NOT_STARTED' and del_flag = 0
    </update>
 
    <update id="deleteTestById">
        update t_test set del_flag = test_id, update_by = #{updateBy}, update_time = sysdate()
        where test_id = #{testId} and reception_status = 'NOT_STARTED' and del_flag = 0
    </update>
 
    <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="deleteTestPlanStepsByTestId">delete from t_test_plan_step where test_id = #{testId}</delete>
    <update id="deleteTestFieldsByTestId">
        update t_test_battery_field f join t_test_battery b on b.relation_id = f.relation_id
        set f.del_flag = f.field_id where b.test_id = #{testId} and f.del_flag = 0
    </update>
    <update id="deleteTestBatteriesByTestId">
        update t_test_battery set del_flag = relation_id where test_id = #{testId} and del_flag = 0
    </update>
    <update id="deleteTestThresholdsByTestId">
        update t_test_warning_threshold set del_flag = threshold_id where test_id = #{testId} and del_flag = 0
    </update>
 
    <insert id="insertTestPlanStep" parameterType="TTestPlanStep" useGeneratedKeys="true" keyProperty="planStepId">
        insert into t_test_plan_step(test_id, cycle_no, step_no, step_type, step_name, parameters_json, sort_order)
        values(#{testId}, #{cycleNo}, #{stepNo}, #{stepType}, #{stepName}, cast(#{parametersJson} as json), #{sortOrder})
    </insert>
    <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="insertTestBatteryField" parameterType="TTestBatteryField" useGeneratedKeys="true" keyProperty="fieldId">
        insert into t_test_battery_field(relation_id, field_name, field_value, del_flag)
        values(#{relationId}, #{fieldName}, #{fieldValue}, 0)
    </insert>
    <insert id="insertTestChannelBinding" parameterType="TTestChannelBinding" useGeneratedKeys="true" keyProperty="bindingId">
        insert into t_test_channel_binding(test_id, battery_relation_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, battery_relation_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="selectTestPlanSteps" parameterType="Long" resultMap="TTestPlanStepResultMap">
        select plan_step_id, test_id, cycle_no, step_no, step_type, step_name,
               cast(parameters_json as char) parameters_json, sort_order
        from t_test_plan_step where test_id = #{testId} order by sort_order, plan_step_id
    </select>
    <select id="selectTestBatteries" parameterType="Long" resultMap="TTestBatteryResultMap">
        select battery.relation_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.relation_id
    </select>
    <select id="selectTestBatteryFields" parameterType="Long" resultMap="TTestBatteryFieldResultMap">
        select field.* from t_test_battery_field field
        join t_test_battery battery on battery.relation_id = field.relation_id
        where battery.test_id = #{testId} and field.del_flag = 0 order by field.field_id
    </select>
    <select id="selectTestChannelBindings" parameterType="Long" resultMap="TTestBindingResultMap">
        select binding.binding_id, binding.test_id, binding.battery_relation_id, binding.channel_id,
               binding.expected_barcode, binding.claim_status, channel_fact.cabinet_id,
               cabinet.cabinet_code, cabinet.cabinet_name,
               coalesce(channel_fact.adapter_code, cabinet.adapter_code) adapter_code,
               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'
        where binding.test_id = #{testId} order by binding.binding_id
    </select>
    <select id="selectTestCollectorChannels" parameterType="Long" resultMap="TTestCollectorChannelResultMap">
        select mapping_id, test_id, battery_relation_id, collector_id,
               measurement_code, measurement_name, channel_code
        from t_test_collector_channel where test_id = #{testId}
        order by battery_relation_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>
    <select id="selectTestReceptionIntervals" parameterType="Long" resultMap="TTestReceptionIntervalResultMap">
        select interval_id, test_id, binding_id, source_type, source_id, source_channel_code,
               action_at_utc, start_boundary_at_utc, end_boundary_at_utc, boundary_note, interval_status
        from t_test_reception_interval
        where test_id = #{testId}
        order by source_type, source_id, source_channel_code, start_boundary_at_utc, interval_id
    </select>
    <select id="selectReceivingTestIds" resultType="long">
        select test_id from t_test where del_flag = 0 and reception_status = 'RECEIVING' order by test_id
    </select>
    <select id="selectPersistedRecords" resultType="map">
        select sample.sample_id id,
               concat('RD-', channel.devid, '-', channel.chlid, '-', lpad(sample.seq_id, 6, '0')) recordNo,
               battery.battery_no batteryNo, sample.cycle_no cycleNo, sample.step_no stepNo,
               coalesce(sample.step_name, sample.step_type) stepName, sample.step_type stepType, sample.seq_id sequenceId,
               sample.device_time_utc recordedAt, sample.device_time_utc absoluteTime,
               sample.voltage_v voltage, sample.current_a current, sample.capacity_ah capacity,
               sample.energy_wh energy, channel.devid deviceId, channel.chlid channelId
        from t_test_sample sample
        join t_test_battery battery on battery.relation_id = sample.binding_id and battery.del_flag = 0
        join t_detection_channel channel on channel.channel_id = sample.channel_id and channel.del_flag = 0
        where sample.test_id = #{testId}
        order by sample.device_time_utc desc, sample.seq_id desc, sample.sample_id desc
    </select>
    <select id="selectPersistedSteps" resultType="map">
        select concat('step:', channel.devid, ':', channel.chlid, ':', sample.cycle_no, ':', sample.step_no) id,
               concat('STEP-', channel.devid, '-', channel.chlid, '-', sample.cycle_no, '-', sample.step_no) recordNo,
               battery.battery_no batteryNo, sample.cycle_no cycleNo, sample.step_no stepNo,
               coalesce(sample.step_name, sample.step_type) stepName,
               sample.step_type stepType, coalesce(sample.step_name, sample.step_type) actualStepLabel,
               count(*) recordCount,
               min(sample.device_time_utc) recordedAt, min(sample.device_time_utc) absoluteTime,
               timestampdiff(second, min(sample.device_time_utc), max(sample.device_time_utc)) stepDuration,
               max(sample.capacity_ah) capacity, max(sample.energy_wh) energy,
               min(sample.voltage_v) startVoltage,
               max(sample.voltage_v) endVoltage,
               max(case when sample.current_a &gt;= 0 then sample.voltage_v end) chargePeakVoltage,
               min(case when sample.current_a &lt; 0 then sample.voltage_v end) dischargeValleyVoltage,
               channel.devid deviceId, channel.chlid channelId
        from t_test_sample sample
        join t_test_battery battery on battery.relation_id = sample.binding_id and battery.del_flag = 0
        join t_detection_channel channel on channel.channel_id = sample.channel_id and channel.del_flag = 0
        where sample.test_id = #{testId}
        group by sample.binding_id, battery.battery_no, channel.devid, channel.chlid, sample.cycle_no, sample.step_no,
                 sample.step_type, sample.step_name
        order by sample.cycle_no, sample.step_no, battery.battery_no
    </select>
    <select id="selectPersistedCycles" resultType="map">
        select concat('cycle:', channel.devid, ':', channel.chlid, ':', sample.cycle_no) id,
               concat('CYCLE-', channel.devid, '-', channel.chlid, '-', sample.cycle_no) recordNo,
               battery.battery_no batteryNo, sample.cycle_no cycleNo, count(*) recordCount,
               min(sample.device_time_utc) recordedAt, min(sample.device_time_utc) absoluteTime,
               greatest(max(case when sample.current_a &gt;= 0 then sample.capacity_ah end), 0) chargeCapacity,
               greatest(max(case when sample.current_a &lt; 0 then sample.capacity_ah end), 0) dischargeCapacity,
               greatest(max(case when sample.current_a &gt;= 0 then sample.energy_wh end), 0) chargeEnergy,
               greatest(max(case when sample.current_a &lt; 0 then abs(sample.energy_wh) end), 0) dischargeEnergy,
               case when max(case when sample.current_a &gt;= 0 then sample.capacity_ah end) &gt; 0
                    then greatest(max(case when sample.current_a &lt; 0 then sample.capacity_ah end), 0)
                         / max(case when sample.current_a &gt;= 0 then sample.capacity_ah end) * 100
                    else 0 end efficiency,
               channel.devid deviceId, channel.chlid channelId
        from t_test_sample sample
        join t_test_battery battery on battery.relation_id = sample.binding_id and battery.del_flag = 0
        join t_detection_channel channel on channel.channel_id = sample.channel_id and channel.del_flag = 0
        where sample.test_id = #{testId}
        group by sample.binding_id, battery.battery_no, channel.devid, channel.chlid, sample.cycle_no
        order by sample.cycle_no, battery.battery_no
    </select>
    <select id="selectTestResults" parameterType="TTestResult" resultMap="TTestResultResultMap">
        select result.*, battery.test_id from t_test_result result
        join t_test_battery battery on battery.relation_id = result.relation_id
        where battery.test_id = #{testId} and result.del_flag = 0
          and exists (
              select 1 from t_test_audit start_action
              where start_action.test_id = battery.test_id
                and start_action.event_type in ('RECEPTION_STARTED', 'RECEPTION_RESUMED')
                and start_action.occurred_at_utc &lt;= result.result_time
                and not exists (
                    select 1 from t_test_audit pause_action
                    where pause_action.test_id = battery.test_id
                      and pause_action.event_type in ('RECEPTION_PAUSED', 'TEST_STOPPED')
                      and pause_action.occurred_at_utc &gt; start_action.occurred_at_utc
                      and pause_action.occurred_at_utc &lt;= result.result_time
                )
          )
        <if test="relationId != null">and result.relation_id = #{relationId}</if>
        <if test="channelNo != null">and result.channel_no = #{channelNo}</if>
        <if test="beginResultTime != null">and result.result_time &gt;= #{beginResultTime}</if>
        <if test="endResultTime != null">and result.result_time &lt;= #{endResultTime}</if>
        order by result.result_time, result.result_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>
 
    <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.ruoyi.system.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.ruoyi.system.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.ruoyi.system.domain.vo.TestBatteryOptionVo">
        select battery.relation_id relationId, 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.ruoyi.system.domain.vo.TestChannelOptionVo">
        select channel_fact.channel_id channelId, channel_fact.cabinet_id cabinetId,
               cabinet.cabinet_code cabinetCode, cabinet.cabinet_name cabinetName,
               coalesce(channel_fact.adapter_code, cabinet.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
        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.ruoyi.system.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>
 
    <insert id="insertTestAudit">
        insert into t_test_audit
        (test_id, event_type, actor_id, actor_name, occurred_at_utc, previous_value, new_value, correlation_id)
        values
        (#{testId}, #{eventType}, #{actorId}, #{actorName}, utc_timestamp(3),
         <choose><when test="previousValue != null">cast(#{previousValue} as json)</when><otherwise>null</otherwise></choose>,
         <choose><when test="newValue != null">cast(#{newValue} as json)</when><otherwise>null</otherwise></choose>,
         uuid())
    </insert>
 
    <select id="selectReceptionChannelForUpdate" parameterType="Long" resultType="com.ruoyi.system.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="selectTestsForNaturalEnd" resultMap="TTestResultMap">
        <include refid="selectTestBase" />
        where t.del_flag = 0 and t.reception_status in ('RECEIVING', 'PAUSED')
        order by t.test_id
    </select>
    <select id="selectTestsForBackfill" resultMap="TTestResultMap">
        <include refid="selectTestBase" />
        where t.del_flag = 0 and t.reception_status = 'ENDED'
          and t.test_status in ('COMPLETION_PENDING', 'COMPLETED')
          and coalesce(t.backfill_status, 'NOT_STARTED') &lt;&gt; 'COMPLETED'
        order by t.ended_at_utc, t.test_id
    </select>
    <resultMap id="TTestBackfillCursorResultMap" type="com.ruoyi.system.domain.TTestBackfillCursor">
        <id property="cursorId" column="cursor_id" />
        <result property="testId" column="test_id" />
        <result property="bindingId" column="binding_id" />
        <result property="sourceType" column="source_type" />
        <result property="sourceId" column="source_id" />
        <result property="sourceChannelCode" column="source_channel_code" />
        <result property="protocolTestId" column="protocol_test_id" />
        <result property="nextPosition" column="next_position" />
        <result property="sourceStatus" column="source_status" />
        <result property="protocolMetadata" column="protocol_metadata" />
        <result property="lastError" column="last_error" />
        <result property="updatedAtUtc" column="updated_at_utc" />
    </resultMap>
    <select id="selectBackfillCursorForUpdate" resultMap="TTestBackfillCursorResultMap">
        select * from t_test_backfill_cursor
        where test_id = #{testId} and binding_id = #{bindingId}
          and source_type = #{sourceType} and source_id = #{sourceId}
          and (source_channel_code = #{sourceChannelCode} or (source_channel_code is null and #{sourceChannelCode} is null))
        for update
    </select>
    <insert id="insertBackfillCursor" parameterType="com.ruoyi.system.domain.TTestBackfillCursor" useGeneratedKeys="true" keyProperty="cursorId">
        insert into t_test_backfill_cursor
        (test_id, binding_id, source_type, source_id, source_channel_code, protocol_test_id,
         next_position, source_status, protocol_metadata, last_error, updated_at_utc)
        values (#{testId}, #{bindingId}, #{sourceType}, #{sourceId}, #{sourceChannelCode}, #{protocolTestId},
                #{nextPosition}, #{sourceStatus}, cast(#{protocolMetadata} as json), #{lastError}, #{updatedAtUtc})
    </insert>
    <update id="updateBackfillCursor" parameterType="com.ruoyi.system.domain.TTestBackfillCursor">
        update t_test_backfill_cursor set protocol_test_id = #{protocolTestId}, next_position = #{nextPosition},
            source_status = #{sourceStatus}, protocol_metadata = cast(#{protocolMetadata} as json),
            last_error = #{lastError}, updated_at_utc = #{updatedAtUtc}
        where cursor_id = #{cursorId}
    </update>
    <update id="updateTestBackfillStarted">
        update t_test set test_status = 'COMPLETION_PENDING', backfill_status = 'RUNNING',
            backfill_started_at_utc = coalesce(backfill_started_at_utc, #{updatedAtUtc}),
            update_time = #{updatedAtUtc} where test_id = #{testId} and reception_status = 'ENDED'
    </update>
    <update id="updateTestBackfillWaiting">
        update t_test set backfill_status = 'WAITING', update_time = #{updatedAtUtc}, remark = #{error}
        where test_id = #{testId} and reception_status = 'ENDED'
    </update>
    <update id="updateTestBackfillCompleted">
        update t_test set backfill_status = 'COMPLETED', backfill_completed_at_utc = #{updatedAtUtc},
            update_time = #{updatedAtUtc} where test_id = #{testId} and reception_status = 'ENDED'
    </update>
    <update id="updateTestCompleted">
        update t_test set test_status = 'COMPLETED', backfill_status = 'COMPLETED',
            backfill_completed_at_utc = #{updatedAtUtc}, update_time = #{updatedAtUtc}
        where test_id = #{testId} and reception_status = 'ENDED' and test_status = 'COMPLETION_PENDING'
    </update>
    <update id="updateTestNaturallyEnded">
        update t_test set test_status = 'COMPLETION_PENDING', reception_status = 'ENDED',
            ended_at_utc = #{endedAtUtc}, backfill_status = 'NOT_STARTED', update_time = #{endedAtUtc}
        where test_id = #{testId} and reception_status in ('RECEIVING', 'PAUSED')
    </update>
    <select id="selectSampleContentHash" resultType="string">
        select hex(content_sha256) from t_test_sample
        where channel_id = #{channelId} and bts_test_id = #{btsTestId} and seq_id = #{sequenceId}
    </select>
    <select id="selectTestSampleContentHash" resultType="string">
        select hex(content_sha256) from t_test_sample
        where test_id = #{testId} and channel_id = #{channelId} and seq_id = #{sequenceId}
        order by sample_id limit 1
    </select>
    <insert id="insertBtsSample">
        insert ignore into t_test_sample
        (test_id, binding_id, channel_id, reception_interval_id, bts_test_id, seq_id, device_time_utc,
         device_time_raw, received_at_utc, cycle_no, step_no, step_type, step_name, test_time_ms, voltage_v,
         current_a, capacity_ah, energy_wh, content_sha256)
        values (#{testId}, #{bindingId}, #{channelId}, #{intervalId}, #{btsTestId}, #{sequenceId}, #{deviceTimeUtc},
                #{deviceTimeRaw}, #{receivedAtUtc}, #{cycleNo}, #{stepNo}, #{stepType}, #{stepName}, #{testTimeMs}, #{voltageV},
                #{currentA}, #{capacityAh}, #{energyWh}, #{contentSha256})
    </insert>
    <insert id="insertBtsMeasurement">
        insert ignore into t_test_sample_measurement
        (sample_id, metric_code, metric_value, unit, source_type)
        values (#{sampleId}, #{metricCode}, #{metricValue}, #{unit}, #{sourceType})
    </insert>
    <select id="selectBtsSampleId" resultType="long">
        select sample_id from t_test_sample
        where channel_id = #{channelId} and bts_test_id = #{btsTestId} and seq_id = #{sequenceId}
    </select>
    <insert id="insertCollectorSample">
        insert ignore into t_test_collector_sample
        (test_id, binding_id, reception_interval_id, collector_id, collector_channel_code, sequence_id, device_time_utc,
         device_time_raw, server_received_at_utc, metric_code, metric_value, unit, content_sha256)
        values (#{testId}, #{bindingId}, #{intervalId}, #{collectorId}, #{channelCode}, #{sequenceId}, #{deviceTimeUtc},
                #{deviceTimeRaw}, #{receivedAtUtc}, #{metricCode}, #{metricValue}, #{unit}, #{contentSha256})
    </insert>
    <resultMap id="TTestIntegrityIssueResultMap" type="com.ruoyi.system.domain.TTestIntegrityIssue">
        <id property="issueId" column="issue_id"/><result property="testId" column="test_id"/>
        <result property="intervalId" column="interval_id"/><result property="bindingId" column="binding_id"/>
        <result property="sourceType" column="source_type"/><result property="sourceId" column="source_id"/>
        <result property="sourceChannelCode" column="source_channel_code"/><result property="issueType" column="issue_type"/>
        <result property="issueStatus" column="issue_status"/><result property="missingFromSequence" column="missing_from_sequence"/>
        <result property="missingToSequence" column="missing_to_sequence"/><result property="retryCount" column="retry_count"/>
        <result property="detail" column="detail"/><result property="firstDetectedAtUtc" column="first_detected_at_utc"/>
        <result property="lastDetectedAtUtc" column="last_detected_at_utc"/><result property="resolvedAtUtc" column="resolved_at_utc"/>
    </resultMap>
    <select id="selectIntegrityIssues" resultMap="TTestIntegrityIssueResultMap">
        select * from t_test_integrity_issue where test_id = #{testId}
        order by issue_status, last_detected_at_utc desc, issue_id desc
    </select>
    <select id="selectTestExceptionFacts" resultMap="TTestIntegrityIssueResultMap">
        select exception_id issue_id, test_id, null interval_id, null binding_id,
               case when channel_id is null then 'UNKNOWN_SOURCE' else 'CABINET_CHANNEL' end source_type,
               channel_id source_id, null source_channel_code, exception_type issue_type,
               exception_status issue_status, null missing_from_sequence, null missing_to_sequence,
               occurrence_count retry_count, detail, first_occurred_at_utc first_detected_at_utc,
               last_occurred_at_utc last_detected_at_utc, handled_at_utc resolved_at_utc
        from t_test_exception where test_id = #{testId}
        order by exception_status, last_occurred_at_utc desc, exception_id desc
    </select>
    <select id="selectBtsSequencesByInterval" resultType="long">
        select seq_id from t_test_sample where reception_interval_id = #{intervalId} order by seq_id
    </select>
    <select id="selectCollectorSequencesByInterval" resultType="long">
        select distinct sequence_id from t_test_collector_sample where reception_interval_id = #{intervalId} order by sequence_id
    </select>
    <select id="selectOpenIntegrityIssue" resultMap="TTestIntegrityIssueResultMap">
        select * from t_test_integrity_issue where interval_id = #{intervalId} and issue_status = 'OPEN'
          and source_type = #{sourceType} and source_id = #{sourceId}
          and (source_channel_code = #{sourceChannelCode} or (source_channel_code is null and #{sourceChannelCode} is null))
          and (missing_from_sequence = #{missingFrom} or (missing_from_sequence is null and #{missingFrom} is null))
          and (missing_to_sequence = #{missingTo} or (missing_to_sequence is null and #{missingTo} is null)) limit 1
    </select>
    <select id="selectOpenIntegrityIssues" resultMap="TTestIntegrityIssueResultMap">
        select * from t_test_integrity_issue where interval_id = #{intervalId} and issue_status = 'OPEN'
          and source_type = #{sourceType} and source_id = #{sourceId}
          and (source_channel_code = #{sourceChannelCode} or (source_channel_code is null and #{sourceChannelCode} is null))
        order by issue_id
    </select>
    <insert id="insertIntegrityIssue" parameterType="com.ruoyi.system.domain.TTestIntegrityIssue" useGeneratedKeys="true" keyProperty="issueId">
        insert into t_test_integrity_issue
        (test_id, interval_id, binding_id, source_type, source_id, source_channel_code, issue_type, issue_status,
         missing_from_sequence, missing_to_sequence, retry_count, detail, first_detected_at_utc, last_detected_at_utc)
        values (#{testId}, #{intervalId}, #{bindingId}, #{sourceType}, #{sourceId}, #{sourceChannelCode}, #{issueType}, 'OPEN',
                #{missingFromSequence}, #{missingToSequence}, #{retryCount}, #{detail}, #{firstDetectedAtUtc}, #{lastDetectedAtUtc})
    </insert>
    <update id="touchIntegrityIssue">
        update t_test_integrity_issue set retry_count = #{retryCount}, detail = #{detail}, last_detected_at_utc = #{detectedAtUtc}
        where issue_id = #{issueId} and issue_status = 'OPEN'
    </update>
    <update id="rewindBackfillCursor">
        update t_test_backfill_cursor set next_position = least(next_position, #{nextPosition}),
            source_status = 'PENDING', last_error = '区间序号缺口待重试', updated_at_utc = utc_timestamp(3)
        where test_id = #{testId} and binding_id = #{bindingId} and source_type = #{sourceType}
          and source_id = #{sourceId}
          and (source_channel_code = #{sourceChannelCode} or (source_channel_code is null and #{sourceChannelCode} is null))
    </update>
    <update id="resolveIntegrityIssues">
        update t_test_integrity_issue set issue_status = 'RESOLVED', resolved_at_utc = #{resolvedAtUtc}
        where test_id = #{testId} and interval_id = #{intervalId} and issue_status = 'OPEN'
          and source_type = #{sourceType} and source_id = #{sourceId}
          and (source_channel_code = #{sourceChannelCode} or (source_channel_code is null and #{sourceChannelCode} is null))
    </update>
    <update id="resolveIntegrityIssue">
        update t_test_integrity_issue set issue_status = 'RESOLVED', resolved_at_utc = #{resolvedAtUtc}
        where issue_id = #{issueId} and issue_status = 'OPEN'
    </update>
    <select id="countOpenIntegrityIssues" resultType="int">
        select count(1) from t_test_integrity_issue where test_id = #{testId} and issue_status = 'OPEN'
    </select>
    <select id="countOpenExceptions" resultType="int">
        select count(1) from t_test_exception where test_id = #{testId} and exception_status = 'OPEN'
    </select>
    <select id="selectCollectorSampleId" resultType="long">
        select sample_id from t_test_collector_sample
        where collector_id = #{collectorId} and collector_channel_code = #{channelCode}
          and sequence_id = #{sequenceId} and metric_code = #{metricCode}
    </select>
    <select id="selectCollectorSampleContentHash" resultType="string">
        select hex(content_sha256) from t_test_collector_sample
        where collector_id = #{collectorId} and collector_channel_code = #{channelCode}
          and sequence_id = #{sequenceId} and metric_code = #{metricCode}
    </select>
    <insert id="insertBackfillConflict">
        insert into t_test_exception
        (test_id, channel_id, exception_type, exception_status, severity,
         first_occurred_at_utc, last_occurred_at_utc, occurrence_count, detail)
        values (#{testId}, #{channelId}, 'HISTORY_CONTENT_CONFLICT', 'OPEN', 'WARNING', utc_timestamp(3),
                utc_timestamp(3), 1, #{detail})
        on duplicate key update last_occurred_at_utc = utc_timestamp(3), occurrence_count = occurrence_count + 1,
            detail = values(detail)
    </insert>
    <select id="selectChannelLeaseForUpdate" parameterType="Long" resultMap="TTestBindingResultMap">
        select binding.binding_id, binding.test_id, binding.battery_relation_id, binding.channel_id,
               binding.claim_status
        from t_channel_lease lease
        join t_test_channel_binding binding on binding.binding_id = lease.binding_id
        where lease.channel_id = #{channelId}
        for update
    </select>
    <insert id="insertChannelLease">
        insert into t_channel_lease(channel_id, test_id, binding_id, acquired_by, acquired_at_utc)
        values(#{channelId}, #{testId}, #{bindingId}, #{acquiredBy}, #{acquiredAtUtc})
    </insert>
    <insert id="insertCollectorChannelLease">
        insert into t_collector_channel_lease(collector_id, channel_code, test_id, binding_id, acquired_by, acquired_at_utc)
        values(#{collectorId}, #{channelCode}, #{testId}, #{bindingId}, #{acquiredBy}, #{acquiredAtUtc})
    </insert>
    <insert id="insertReceptionInterval">
        insert into t_test_reception_interval
        (test_id, binding_id, source_type, source_id, source_channel_code,
         action_at_utc, start_boundary_at_utc, boundary_note, interval_status)
        values(#{testId}, #{bindingId}, #{sourceType}, #{sourceId}, #{sourceChannelCode},
               #{actionAtUtc}, #{actionAtUtc}, #{boundaryNote}, 'OPEN')
    </insert>
    <update id="closeOpenReceptionIntervals">
        update t_test_reception_interval
        set end_boundary_at_utc = #{endBoundaryAtUtc},
            boundary_note = #{boundaryNote}, interval_status = 'CLOSED'
        where test_id = #{testId} and interval_status = 'OPEN'
    </update>
    <delete id="deleteChannelLeasesByTestId">
        delete from t_channel_lease where test_id = #{testId}
    </delete>
    <delete id="deleteCollectorChannelLeasesByTestId">
        delete from t_collector_channel_lease where test_id = #{testId}
    </delete>
    <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
        where channel_fact.adapter_code = #{adapterCode}
          and test_fact.reception_status = 'RECEIVING'
          and test_fact.del_flag = 0 and channel_fact.del_flag = 0
    </select>
    <select id="hasPausedOrEndedTestForAdapter" 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
        where channel_fact.adapter_code = #{adapterCode}
          and test_fact.reception_status in ('PAUSED', 'ENDED')
          and test_fact.del_flag = 0 and channel_fact.del_flag = 0
    </select>
    <select id="selectReceivingChannelsForAdapter" resultType="com.ruoyi.system.domain.TDetectionChannel">
        select distinct channel_fact.channel_id, channel_fact.adapter_id, channel_fact.adapter_code,
               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
        where channel_fact.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>
    <select id="collectorOnline" resultType="boolean">
        select count(1) &gt; 0 from t_collector
        where collector_id = #{collectorId} and status = '0' and del_flag = 0
          and upper(online_status) in ('ONLINE', '1')
    </select>
    <update id="updateReceptionStarted">
        update t_test
        set test_status = 'RUNNING', reception_status = 'RECEIVING',
            runtime_attach = #{runtimeAttach},
            started_at_utc = coalesce(started_at_utc, #{startedAtUtc}),
            update_by = #{updateBy}, update_time = #{startedAtUtc}
        where test_id = #{testId} 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 reception_status = 'RECEIVING' and del_flag = 0
    </update>
    <update id="updateReceptionResumed">
        update t_test
        set test_status = 'RUNNING', reception_status = 'RECEIVING', update_by = #{updateBy}, update_time = #{updatedAtUtc}
        where test_id = #{testId} 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},
            backfill_status = 'COMPLETED',
            update_by = #{updateBy}, update_time = #{endedAtUtc}
        where test_id = #{testId} and reception_status in ('RECEIVING', 'PAUSED') and del_flag = 0
    </update>
 
    <select id="selectReceivingCollectorSources" resultType="com.ruoyi.system.domain.TTestCollectorSource">
        select test_fact.test_id testId, battery.relation_id batteryRelationId, battery.battery_no batteryNo,
               collector.collector_id collectorId, collector.collector_code collectorCode,
               mapping.channel_code channelCode
        from t_test test_fact
        join t_test_battery battery on battery.test_id = test_fact.test_id and battery.del_flag = 0
        join t_collector collector on collector.collector_id = battery.collector_id
            and collector.del_flag = 0
        join t_test_collector_channel mapping on mapping.battery_relation_id = battery.relation_id
            and mapping.test_id = test_fact.test_id
        where test_fact.reception_status = 'RECEIVING' and test_fact.del_flag = 0
        order by test_fact.test_id, battery.relation_id, mapping.mapping_id
    </select>
    <select id="selectOpenCollectorException" resultMap="TTestCollectorExceptionIntervalResultMap">
        select * from t_test_collector_exception_interval
        where test_id = #{testId} and battery_relation_id = #{batteryRelationId}
          and collector_id = #{collectorId} and collector_channel_code = #{channelCode}
          and exception_type = 'COLLECTOR_DISCONNECTED' and interval_status = 'OPEN'
        order by interval_id desc limit 1
    </select>
    <insert id="insertCollectorExceptionInterval" parameterType="TTestCollectorExceptionInterval" useGeneratedKeys="true" keyProperty="intervalId">
        insert into t_test_collector_exception_interval
        (test_id, battery_relation_id, collector_id, collector_channel_code, exception_type,
         opened_at_utc, missing_from_utc, detail)
        values (#{testId}, #{batteryRelationId}, #{collectorId}, #{collectorChannelCode},
                #{exceptionType}, #{openedAtUtc}, #{missingFromUtc}, #{detail})
    </insert>
    <update id="closeCollectorExceptionInterval">
        update t_test_collector_exception_interval
        set recovered_at_utc = #{recoveredAtUtc}, missing_to_utc = #{missingToUtc}, interval_status = 'CLOSED'
        where interval_id = #{intervalId} and interval_status = 'OPEN'
    </update>
    <select id="selectCollectorExceptionIntervals" parameterType="Long" resultMap="TTestCollectorExceptionIntervalResultMap">
        select exception_fact.*, collector.collector_code, collector.collector_name,
               mapping.measurement_name
        from t_test_collector_exception_interval exception_fact
        left join t_collector collector on collector.collector_id = exception_fact.collector_id
        left join t_test_collector_channel mapping on mapping.battery_relation_id = exception_fact.battery_relation_id
            and mapping.collector_id = exception_fact.collector_id
            and mapping.channel_code = exception_fact.collector_channel_code
        where exception_fact.test_id = #{testId} and exception_fact.interval_status = 'OPEN'
        order by exception_fact.opened_at_utc, exception_fact.interval_id
    </select>
    <resultMap id="TTestDataOverrideResultMap" type="com.ruoyi.system.domain.TTestDataOverride">
        <id property="overrideId" column="override_id"/><result property="testId" column="test_id"/>
        <result property="dataType" column="data_type"/><result property="stableIdentity" column="stable_identity"/>
        <result property="fieldValues" column="field_values"/><result property="deleted" column="deleted"/>
        <result property="actionId" column="action_id"/><result property="createdAtUtc" column="created_at_utc"/>
    </resultMap>
    <insert id="insertDataRevisionAction" parameterType="com.ruoyi.system.domain.TTestDataRevisionAction"
            useGeneratedKeys="true" keyProperty="actionId">
        insert into t_test_data_revision_action
        (test_id, data_type, operation_type, scope_summary, identity_summary, changes_summary,
         reason, operator_id, operator_name, created_at_utc)
        values (#{testId}, #{dataType}, #{operationType}, #{scopeSummary}, cast(#{identitySummary} as json),
                cast(#{changesSummary} as json), #{reason}, #{operatorId}, #{operatorName}, #{createdAtUtc})
    </insert>
    <insert id="upsertDataOverride" parameterType="com.ruoyi.system.domain.TTestDataOverride">
        insert into t_test_data_override
        (test_id, data_type, stable_identity, field_values, deleted, action_id, created_at_utc)
        values (#{testId}, #{dataType}, #{stableIdentity}, cast(#{fieldValues} as json), #{deleted}, #{actionId}, #{createdAtUtc})
        on duplicate key update field_values = values(field_values), deleted = values(deleted),
            action_id = values(action_id), created_at_utc = values(created_at_utc)
    </insert>
    <select id="selectDataOverrides" resultMap="TTestDataOverrideResultMap">
        select override_id, test_id, data_type, stable_identity, field_values, deleted, action_id, created_at_utc
        from t_test_data_override where test_id = #{testId} and data_type = #{dataType}
        order by override_id
    </select>
    <delete id="deleteBtsSamplesByIds">
        delete from t_test_sample where test_id = #{testId} and sample_id in
        <foreach collection="sampleIds" item="id" open="(" separator="," close=")">#{id}</foreach>
    </delete>
    <delete id="deleteBtsMeasurementsBySampleIds">
        delete from t_test_sample_measurement where sample_id in
        <foreach collection="sampleIds" item="id" open="(" separator="," close=")">#{id}</foreach>
    </delete>
    <delete id="deleteCollectorSamplesByIds">
        delete from t_test_collector_sample where test_id = #{testId} and sample_id in
        <foreach collection="sampleIds" item="id" open="(" separator="," close=")">#{id}</foreach>
    </delete>
    <select id="selectBtsSampleIdByDeviceChannelSequence" resultType="long">
        select sample.sample_id
        from t_test_sample sample
        join t_detection_channel channel_fact on channel_fact.channel_id = sample.channel_id
        where sample.test_id = #{testId} and channel_fact.devid = #{deviceId}
          and channel_fact.chlid = #{channelNo} and sample.seq_id = #{sequenceId}
        limit 1
    </select>
    <select id="selectBtsSampleIdsByDeviceChannelStep" resultType="long">
        select sample.sample_id
        from t_test_sample sample
        join t_detection_channel channel_fact on channel_fact.channel_id = sample.channel_id
        where sample.test_id = #{testId} and channel_fact.devid = #{deviceId}
          and channel_fact.chlid = #{channelNo} and sample.cycle_no = #{cycleNo}
          and sample.step_no = #{stepNo}
    </select>
    <select id="selectBtsSampleIdsByDeviceChannelCycle" resultType="long">
        select sample.sample_id
        from t_test_sample sample
        join t_detection_channel channel_fact on channel_fact.channel_id = sample.channel_id
        where sample.test_id = #{testId} and channel_fact.devid = #{deviceId}
          and channel_fact.chlid = #{channelNo} and sample.cycle_no = #{cycleNo}
    </select>
    <insert id="insertConsoleImportRecord" parameterType="com.ruoyi.system.domain.TTestConsoleImportRecord"
            useGeneratedKeys="true" keyProperty="importRecordId">
        insert into t_test_console_import_record
        (test_id, data_type, stable_identity, row_values, action_id, created_at_utc)
        values (#{testId}, #{dataType}, #{stableIdentity}, cast(#{rowValues} as json), #{actionId}, #{createdAtUtc})
    </insert>
    <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>
</mapper>