yeg
2026-09-02 409b5ac5a3b160eacb1fefa6a10bf97b5f6860d7
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.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="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="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>
 
    <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.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
        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, 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="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.device_time_utc deviceTime, sample.received_at_utc serverReceivedAt,
               sample.voltage_v voltage, sample.current_a current, sample.capacity_ah capacity,
               sample.energy_wh energy, channel.adapter_id adapterId, channel.adapter_code adapterCode,
               channel.devtype devtype, channel.devid deviceId, channel.subdevid subdevid, 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="selectPersistedCollectorRecords" resultType="map">
        select concat('collector:', sample.collector_id, ':', sample.collector_channel_code, ':',
                      sample.sequence_id, ':', sample.metric_code) id,
               concat('collector:', sample.collector_id, ':', sample.collector_channel_code, ':',
                      sample.sequence_id, ':', sample.metric_code) stableIdentity,
               concat('CR-', sample.collector_id, '-', sample.collector_channel_code, '-',
                      lpad(sample.sequence_id, 6, '0'), '-', sample.metric_code) recordNo,
               'COLLECTOR' sourceType, battery.battery_no batteryNo,
               sample.sequence_id sequenceId, sample.device_time_utc recordedAt,
               sample.device_time_utc absoluteTime, sample.device_time_utc deviceTime,
               sample.server_received_at_utc serverReceivedAt, sample.sample_id sampleId,
               sample.metric_code metricCode,
               sample.metric_value metricValue, sample.unit, sample.collector_id collectorId,
               collector.collector_code collectorCode, sample.collector_channel_code channelCode,
               sample.adapter_code adapterCode
        from t_test_collector_sample sample
        join t_test_channel_binding binding on binding.binding_id = sample.binding_id
        join t_test_battery battery on battery.relation_id = binding.battery_relation_id and battery.del_flag = 0
        join t_collector collector on collector.collector_id = sample.collector_id
        where sample.test_id = #{testId}
        order by sample.device_time_utc desc, sample.sequence_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,
               max(sample.received_at_utc) serverReceivedAt,
               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.adapter_id adapterId, channel.adapter_code adapterCode, channel.devtype devtype,
               channel.devid deviceId, channel.subdevid subdevid, 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.adapter_id, channel.adapter_code, channel.devtype,
                 channel.devid, channel.subdevid, 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,
               max(sample.received_at_utc) serverReceivedAt,
               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.adapter_id adapterId, channel.adapter_code adapterCode, channel.devtype devtype,
               channel.devid deviceId, channel.subdevid subdevid, 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.adapter_id, channel.adapter_code, channel.devtype,
                 channel.devid, channel.subdevid, 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="selectBtsSampleContentHash" resultType="string">
        select hex(content_sha256) from t_test_sample
        where channel_id = #{channelId} and bts_test_id = #{btsTestId} 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, 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}, #{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>
    <insert id="insertCollectorSample">
        insert ignore into t_test_collector_sample
        (test_id, binding_id, collector_id, adapter_code, 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}, #{collectorId}, #{adapterCode}, #{channelCode}, #{sequenceId}, #{deviceTimeUtc},
                #{deviceTimeRaw}, #{receivedAtUtc}, #{metricCode}, #{metricValue}, #{unit}, #{contentSha256})
    </insert>
    <select id="selectCollectorSampleContentHash" resultType="string">
        select lower(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}
        limit 1
    </select>
    <insert id="insertSampleConflict">
        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}, 'SAMPLE_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="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="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>
    <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},
            update_by = #{updateBy}, update_time = #{endedAtUtc}
        where test_id = #{testId} and reception_status in ('RECEIVING', 'PAUSED') and del_flag = 0
    </update>
 
    <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>
    <select id="selectConsoleImportRecords" resultType="map">
        select stable_identity stableIdentity, cast(row_values as char) rowValues
        from t_test_console_import_record
        where test_id = #{testId} and data_type = #{dataType}
        order by import_record_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>