刘光辉
118 分钟以前 06f314545ac3514d7ce28939920866ae8188d31c
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
package jnpf.elnService.impl;
 
import jnpf.audit.model.AuditEventDTO;
import jnpf.eln.RecordFillSaveCommand;
import jnpf.eln.RecordFillSaveOperation;
import jnpf.elnEntity.runtime.ElnRecordEntity;
import jnpf.elnEntity.runtime.ElnRecordForms;
import jnpf.elnEntity.runtime.ElnRecordRepeatRowEntity;
import jnpf.elnEntity.runtime.ElnRecordRevisionEntity;
import jnpf.elnEntity.runtime.ElnRecordVos;
import jnpf.elnEntity.template.ElnTemplateVos;
import jnpf.elnMapper.ElnRecordMapper;
import jnpf.elnMapper.ElnRecordRepeatRowMapper;
import jnpf.elnMapper.ElnRecordRevisionMapper;
import jnpf.elnService.ElnRecordFillAccessService;
import jnpf.elnService.ElnRecordFillTicketService;
import jnpf.elnService.template.ElnTemplateRepeatGroupService;
import jnpf.exception.DataException;
import jnpf.util.JsonUtil;
import org.junit.Test;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.SimpleTransactionStatus;
 
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
 
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.fail;
 
public class ElnRecordRepeatServiceImplTest {
 
    @Test
    public void appendsOnceAndReplaysThePreparedRowForTheSameOperationCode() {
        ElnRecordEntity record = new ElnRecordEntity();
        record.setId("record-1");
        record.setMubanId("template-1");
        record.setDangqianXiudingId("revision-1");
        ElnRecordRevisionEntity revision = new ElnRecordRevisionEntity();
        revision.setId("revision-1");
        revision.setDianziJiluId("record-1");
        revision.setJiluWendang("file-1");
        revision.setBizStatus("DRAFT");
        AtomicReference<ElnRecordRepeatRowEntity> inserted = new AtomicReference<>();
        AtomicInteger rowSelections = new AtomicInteger();
        AtomicInteger inserts = new AtomicInteger();
        ElnRecordRepeatRowMapper rows = mapper(ElnRecordRepeatRowMapper.class,
                (method, arguments) -> {
                    if ("selectOne".equals(method)) {
                        return rowSelections.incrementAndGet() >= 3 ? inserted.get() : null;
                    }
                    if ("insert".equals(method)) {
                        inserted.set((ElnRecordRepeatRowEntity) arguments[0]);
                        inserts.incrementAndGet();
                        return 1;
                    }
                    if ("selectCount".equals(method)) return 0L;
                    return null;
                });
        RecordingTransactionManager transactions = new RecordingTransactionManager();
        ElnRecordRepeatServiceImpl service = new ElnRecordRepeatServiceImpl(
                mapper(ElnRecordMapper.class,
                        (method, arguments) -> "selectOne".equals(method) ? record : null),
                mapper(ElnRecordRevisionMapper.class,
                        (method, arguments) -> "selectOne".equals(method) ? revision : null),
                rows, repeatGroups(group("measurements", 0, 10),
                        group("results", 0, 2)), allowFill(), transactions,
                ignored -> { },
                new ElnRecordRepeatServiceImpl.TenantRoute() {
                    @Override public void switchTo(String tenantId) { }
                    @Override public void clear() { }
                });
        ElnRecordForms.RepeatAppend form = new ElnRecordForms.RepeatAppend();
        form.setGroupCode("results");
        form.setOperationCode("operation-1");
 
        ElnRecordVos.RepeatRow first = service.append(ticket(), form);
        ElnRecordVos.RepeatRow replay = service.append(ticket(), form);
 
        assertNotNull(first.getRowId());
        assertNotEquals(inserted.get().getId(), inserted.get().getRowId());
        assertEquals(first.getRowId(), replay.getRowId());
        assertEquals(Integer.valueOf(1), first.getRowOrder());
        assertEquals("PREPARED", first.getStatus());
        assertEquals(1, inserts.get());
        assertEquals(2, transactions.commits.get());
    }
 
    @Test
    public void allocatesAnotherPreparedRowForADifferentOperationCode() {
        ElnRecordEntity record = new ElnRecordEntity();
        record.setId("record-1");
        record.setMubanId("template-1");
        record.setDangqianXiudingId("revision-1");
        ElnRecordRevisionEntity revision = new ElnRecordRevisionEntity();
        revision.setId("revision-1");
        revision.setDianziJiluId("record-1");
        revision.setJiluWendang("file-1");
        revision.setBizStatus("DRAFT");
        ElnRecordRepeatRowEntity pending = new ElnRecordRepeatRowEntity();
        pending.setRowId("row-pending");
        pending.setDianziJiluId("record-1");
        pending.setMubanId("template-1");
        pending.setRepeatGroupCode("results");
        pending.setRowOrder(1);
        pending.setOperationStatus("PREPARED");
        AtomicInteger selections = new AtomicInteger();
        AtomicInteger inserts = new AtomicInteger();
        ElnRecordRepeatServiceImpl service = new ElnRecordRepeatServiceImpl(
                mapper(ElnRecordMapper.class,
                        (method, arguments) -> "selectOne".equals(method) ? record : null),
                mapper(ElnRecordRevisionMapper.class,
                        (method, arguments) -> "selectOne".equals(method) ? revision : null),
                mapper(ElnRecordRepeatRowMapper.class, (method, arguments) -> {
                    if ("selectOne".equals(method)) {
                        return selections.incrementAndGet() == 2 ? pending : null;
                    }
                    if ("insert".equals(method)) {
                        inserts.incrementAndGet();
                        return 1;
                    }
                    if ("selectCount".equals(method)) return 1L;
                    return null;
                }), repeatGroups(group("results", 0, 2)), allowFill(),
                new RecordingTransactionManager(), ignored -> { },
                new ElnRecordRepeatServiceImpl.TenantRoute() {
                    @Override public void switchTo(String tenantId) { }
                    @Override public void clear() { }
                });
        ElnRecordForms.RepeatAppend form = new ElnRecordForms.RepeatAppend();
        form.setGroupCode("results");
        form.setOperationCode("operation-after-reopen");
 
        ElnRecordVos.RepeatRow appended = service.append(ticket(), form);
 
        assertNotEquals("row-pending", appended.getRowId());
        assertEquals(Integer.valueOf(2), appended.getRowOrder());
        assertEquals("PREPARED", appended.getStatus());
        assertEquals(1, inserts.get());
    }
 
    @Test
    public void rejectsAppendWhenAllocatedRowsReachTheTargetGroupMaximum() {
        ElnRecordEntity record = record();
        ElnRecordRevisionEntity revision = revision();
        AtomicInteger inserts = new AtomicInteger();
        ElnRecordRepeatRowMapper rows = mapper(ElnRecordRepeatRowMapper.class,
                (method, arguments) -> {
                    if ("selectOne".equals(method)) return null;
                    if ("selectCount".equals(method)) return 2L;
                    if ("insert".equals(method)) inserts.incrementAndGet();
                    return null;
                });
        ElnRecordRepeatServiceImpl service = new ElnRecordRepeatServiceImpl(
                mapper(ElnRecordMapper.class,
                        (method, arguments) -> "selectOne".equals(method) ? record : null),
                mapper(ElnRecordRevisionMapper.class,
                        (method, arguments) -> "selectOne".equals(method) ? revision : null),
                rows, repeatGroups(group("results", 0, 2)), allowFill(),
                new RecordingTransactionManager(), ignored -> { },
                new ElnRecordRepeatServiceImpl.TenantRoute() {
                    @Override public void switchTo(String tenantId) { }
                    @Override public void clear() { }
                });
        ElnRecordForms.RepeatAppend form = new ElnRecordForms.RepeatAppend();
        form.setGroupCode("results");
        form.setOperationCode("operation-over-limit");
 
        try {
            service.append(ticket(), form);
            fail("allocated rows at maxRows must reject append");
        } catch (DataException expected) {
            assertEquals("重复组已达到最大行数 2", expected.getMessage());
        }
        assertEquals(0, inserts.get());
    }
 
    @Test
    public void preparesAndRestoresDeleteIntentIdempotentlyWithAudit() {
        ElnRecordEntity record = record();
        ElnRecordRevisionEntity revision = revision();
        ElnRecordRepeatRowEntity row = activeRow();
        AtomicInteger selections = new AtomicInteger();
        AtomicInteger updates = new AtomicInteger();
        ElnRecordRepeatRowMapper rows = mapper(ElnRecordRepeatRowMapper.class,
                (method, arguments) -> {
                    if ("selectOne".equals(method)) {
                        int selection = selections.incrementAndGet();
                        if (selection == 1) return null;
                        return row;
                    }
                    if ("selectCount".equals(method)) return 2L;
                    if ("updateById".equals(method)) {
                        updates.incrementAndGet();
                        return 1;
                    }
                    return null;
                });
        List<AuditEventDTO> audits = new ArrayList<>();
        ElnRecordRepeatServiceImpl service = new ElnRecordRepeatServiceImpl(
                mapper(ElnRecordMapper.class,
                        (method, arguments) -> "selectOne".equals(method) ? record : null),
                mapper(ElnRecordRevisionMapper.class,
                        (method, arguments) -> "selectOne".equals(method) ? revision : null),
                rows, repeatGroups(group("results", 1, 10)), allowFill(),
                new RecordingTransactionManager(), audits::add,
                new ElnRecordRepeatServiceImpl.TenantRoute() {
                    @Override public void switchTo(String tenantId) { }
                    @Override public void clear() { }
                });
        ElnRecordForms.RepeatDelete delete = new ElnRecordForms.RepeatDelete();
        delete.setGroupCode("results");
        delete.setRowId("row-1");
        delete.setOperationCode("delete-1");
        delete.setReason("录入错误");
 
        ElnRecordVos.RepeatRow prepared = service.requestDelete(ticket(), delete);
        ElnRecordVos.RepeatRow replay = service.requestDelete(ticket(), delete);
 
        assertEquals("DELETE_PREPARED", prepared.getStatus());
        assertEquals("delete-1", prepared.getDeleteOperationCode());
        assertEquals("录入错误", replay.getDeleteReason());
        assertEquals(1, updates.get());
 
        ElnRecordForms.RepeatRestore restore = new ElnRecordForms.RepeatRestore();
        restore.setGroupCode("results");
        restore.setRowId("row-1");
        restore.setOperationCode("delete-1");
        ElnRecordVos.RepeatRow restored = service.restoreDelete(ticket(), restore);
 
        assertEquals("ACTIVE", restored.getStatus());
        assertEquals(null, restored.getDeleteOperationCode());
        assertEquals(2, updates.get());
        assertEquals(Arrays.asList("ELN_RECORD_REPEAT_DELETE_PREPARE",
                        "ELN_RECORD_REPEAT_DELETE_RESTORE"),
                Arrays.asList(audits.get(0).getActionCode(), audits.get(1).getActionCode()));
        assertNotEquals(audits.get(0).getClientEventId(), audits.get(1).getClientEventId());
    }
 
    @Test
    public void rejectsDeleteIntentWhenItWouldFallBelowTheGroupMinimum() {
        ElnRecordRepeatRowEntity row = activeRow();
        AtomicInteger selections = new AtomicInteger();
        ElnRecordRepeatServiceImpl service = new ElnRecordRepeatServiceImpl(
                mapper(ElnRecordMapper.class,
                        (method, arguments) -> "selectOne".equals(method) ? record() : null),
                mapper(ElnRecordRevisionMapper.class,
                        (method, arguments) -> "selectOne".equals(method) ? revision() : null),
                mapper(ElnRecordRepeatRowMapper.class, (method, arguments) -> {
                    if ("selectOne".equals(method)) {
                        return selections.incrementAndGet() == 1 ? null : row;
                    }
                    if ("selectCount".equals(method)) return 1L;
                    return null;
                }), repeatGroups(group("results", 1, 10)), allowFill(),
                new RecordingTransactionManager(), ignored -> { },
                new ElnRecordRepeatServiceImpl.TenantRoute() {
                    @Override public void switchTo(String tenantId) { }
                    @Override public void clear() { }
                });
        ElnRecordForms.RepeatDelete delete = new ElnRecordForms.RepeatDelete();
        delete.setGroupCode("results");
        delete.setRowId("row-1");
        delete.setOperationCode("delete-min");
        delete.setReason("录入错误");
 
        try {
            service.requestDelete(ticket(), delete);
            fail("delete intent below minRows must be rejected");
        } catch (DataException expected) {
            assertEquals("重复组至少保留 1 行", expected.getMessage());
        }
    }
 
    private static ElnRecordRepeatRowEntity activeRow() {
        ElnRecordRepeatRowEntity row = new ElnRecordRepeatRowEntity();
        row.setId("snapshot-1");
        row.setRowId("row-1");
        row.setDianziJiluId("record-1");
        row.setXiudingId("revision-1");
        row.setMubanId("template-1");
        row.setRepeatGroupCode("results");
        row.setRowOrder(1);
        row.setOperationCode("append-1");
        row.setOperationStatus("ACTIVE");
        row.setFTenantId("tenant-1");
        row.setFDeleteMark(0);
        return row;
    }
 
    private static ElnRecordEntity record() {
        ElnRecordEntity record = new ElnRecordEntity();
        record.setId("record-1");
        record.setMubanId("template-1");
        record.setDangqianXiudingId("revision-1");
        return record;
    }
 
    private static ElnRecordRevisionEntity revision() {
        ElnRecordRevisionEntity revision = new ElnRecordRevisionEntity();
        revision.setId("revision-1");
        revision.setDianziJiluId("record-1");
        revision.setJiluWendang("file-1");
        revision.setBizStatus("DRAFT");
        return revision;
    }
 
    private static ElnTemplateVos.RepeatGroup group(String code, int minRows,
                                                     int maxRows) {
        ElnTemplateVos.RepeatGroup group = new ElnTemplateVos.RepeatGroup();
        group.setGroupCode(code);
        group.setMinRows(minRows);
        group.setMaxRows(maxRows);
        return group;
    }
 
    private static ElnTemplateRepeatGroupService repeatGroups(
            ElnTemplateVos.RepeatGroup... groups) {
        List<ElnTemplateVos.RepeatGroup> configured = Arrays.asList(groups);
        return new ElnTemplateRepeatGroupService() {
            @Override public List<ElnTemplateVos.RepeatGroup> list(
                    String tenantId, String templateId) { return configured; }
            @Override public ElnTemplateVos.RepeatGroup ensureConfigured(
                    String tenantId, String templateId, String groupCode,
                    Integer minRows, Integer maxRows, String stepId,
                    String operatorId) { return null; }
            @Override public void copyForVersion(String tenantId, String sourceTemplateId,
                    String targetTemplateId) { }
            @Override public void afterBindingsActivated(String tenantId,
                    String sourceTemplateId, String targetTemplateId,
                    Map<String, String> bindingIdMap) { }
        };
    }
 
    private static ElnRecordFillAccessService allowFill() {
        return new ElnRecordFillAccessService() {
            @Override public boolean canFill(String tenantId, String userId,
                    String recordId, String fileId) { return true; }
            @Override public RecordFillSaveOperation preflight(RecordFillSaveCommand command) { return null; }
            @Override public RecordFillSaveOperation commit(RecordFillSaveCommand command) { return null; }
            @Override public RecordFillSaveOperation abort(RecordFillSaveCommand command) { return null; }
            @Override public RecordFillSaveOperation saveStatus(String tenantId,
                    String operationCode) { return null; }
        };
    }
 
    private static ElnRecordFillTicketService.FillTicketContext ticket() {
        Map<String, String> payload = new LinkedHashMap<>();
        payload.put("scope", ElnRecordFillTicketService.SCOPE);
        payload.put("tenantId", "tenant-1");
        payload.put("userId", "user-1");
        payload.put("fileId", "file-1");
        payload.put("bizDataId", "record-1");
        payload.put("bizModule", ElnRecordFillTicketService.BIZ_MODULE);
        payload.put("bizScene", ElnRecordFillTicketService.BIZ_SCENE);
        payload.put("pluginGuid", "asc.{7F4E8F35-5D66-47F8-A5B4-6AB3FAACF565}");
        return new ElnRecordFillTicketService(
                ignored -> JsonUtil.getObjectToString(payload)).parse("ticket");
    }
 
    @SuppressWarnings("unchecked")
    private static <T> T mapper(Class<T> type, MapperHandler handler) {
        return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[]{type},
                (proxy, method, arguments) -> {
                    if (method.getDeclaringClass() == Object.class) {
                        if ("toString".equals(method.getName())) return type.getSimpleName() + "Fake";
                        if ("hashCode".equals(method.getName())) return System.identityHashCode(proxy);
                        if ("equals".equals(method.getName())) return proxy == arguments[0];
                    }
                    Object result = handler.invoke(method.getName(), arguments);
                    if (result != null) return result;
                    if (method.getReturnType().isPrimitive()) return 0;
                    return null;
                });
    }
 
    @FunctionalInterface
    private interface MapperHandler {
        Object invoke(String method, Object[] arguments);
    }
 
    private static final class RecordingTransactionManager
            implements PlatformTransactionManager {
        private final AtomicInteger commits = new AtomicInteger();
 
        @Override
        public TransactionStatus getTransaction(TransactionDefinition definition) {
            return new SimpleTransactionStatus();
        }
 
        @Override
        public void commit(TransactionStatus status) {
            commits.incrementAndGet();
        }
 
        @Override
        public void rollback(TransactionStatus status) { }
    }
}