P15GEN2\59518
2024-05-29 d4210c7c4b04abde20037ea8aa0f54ef8a2649aa
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
package book.rebate.amt;
 
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
 
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
 
import book.BookResult;
import book.FlowTable;
import book.FreezeCondition;
import book.QtyCommand;
import book.RecordOperator;
import book.rebate.BookCommand;
import book.rebate.BookCommandBucket;
import book.rebate.BookCommandMeta;
import foundation.action.ActionProvider;
import foundation.dao.DataPackage;
import foundation.dao.DataSource;
import foundation.dao.Filter;
import foundation.data.entity.Entity;
import foundation.data.entity.EntitySet;
import foundation.data.object.DataObject;
import foundation.data.object.EntitySaver;
import foundation.io.IOContext;
import foundation.persist.NamedSQL;
import foundation.persist.SQLRunner;
import foundation.util.ID;
import foundation.util.Util;
 
public class BookWriter extends ActionProvider {
    
    private static Logger logger;
    public static final String FieldName_BatchMark = "batch_mark";
    
    static {
        logger = LogManager.getLogger(BookWriter.class);
    }
 
    public BookWriter() {
 
    }
    
    @Override
    protected void publishMethod() {
        //1. 获取库存记账描述列表
        addMethod("getBookCommandList");
        
        //2. 获取库存记账描述
        addMethod("getBookCommand");
        
        //3. 记账
        addMethod("write");
    }
    
    public void getBookCommandList() {
        BookCommandBucket bucket = BookCommandBucket.getInstance();
        dataWriter.addValue("data", bucket);
    }
 
    public void getBookCommand() {
        String commandCode = dataReader.getString("code");
        List<BookCommandMeta> metas = BookCommandBucket.getMeta(commandCode);
        
        if (metas == null) {
            logger.error("rebateAmt book command [{}] can not find: ", commandCode);
            return;
        }
        
        dataWriter.addValue("data", metas);
    }
    
    public void write() throws Exception {
        String commandCode = context.getStepParam();
 
        if (Util.isEmpty(commandCode)) {
            commandCode = context.getParam();
        }
        
        List<BookCommand> bookCommands = BookCommandBucket.get(commandCode); 
        
        if (bookCommands == null || (bookCommands.isEmpty())) {
            throw new Exception("rebateAmt book command [{" + commandCode + "}] can not find: ");
        }
        
        
        //2. 获取公司及仓库
        for (BookCommand bookCommand: bookCommands) {
             getOrgAndWarehouse(bookCommand);
        }
        
        //3. 账本加锁
        lockStockBook(bookCommands);
        
        //4. 创建流水表(FlowTable)并进行校验
        boolean isContinue = true;
        for (BookCommand bookCommand: bookCommands) {
             isContinue = isContinue && getFlowTableAndValidate(bookCommand, bookCommand.getDataSource());
        }
        
        if (!isContinue) {
            logger.error("validate not success, skip...");
            return;
        }
        
        //5. 根据Command和FlowTable记账
        for (BookCommand bookCommand: bookCommands) {
             doWriteBook(bookCommand);
        }
    }
    
    private void getOrgAndWarehouse(BookCommand bookCommand) throws Exception {
        IOContext ioContext = context.getContext(IOContext.class);
            
        if(ioContext != null ) {
            bookCommand.setIoBatchId(ioContext.getIoBatchId());
            bookCommand.setBatchDocument(ioContext.getToDateObject());
            bookCommand.setBatchDocumentDetail(ioContext.getToTempDateObject());
            bookCommand.setOperate("import");
        }else {
            bookCommand.setDocument(dataReader.getDataPackage());
            bookCommand.setOperate(dataReader.getOperator());
        }
    }
    
    private void lockStockBook(List<BookCommand> bookCommands) throws Exception {
        for (BookCommand bookCommand: bookCommands) {
            NamedSQL lockRebateBook = NamedSQL.getInstance("lockRebateBook");
            lockRebateBook.setParam("documentTable", bookCommand.getDocumentTableName());
            lockRebateBook.setParam("document_id", bookCommand.getDocumentId());
            SQLRunner.execSQL(lockRebateBook);
        }
        
    }
    private boolean getFlowTableAndValidate(BookCommand bookCommand, DataSource dataSource) throws Exception {
        if (DataSource.Request == dataSource) {
            return getFlowTableAndValidateFromRequest(bookCommand);
        }
        
        return getFlowTableAndValidate(bookCommand);
    }
    
 
    private boolean getFlowTableAndValidateFromRequest(BookCommand bookCommand) throws Exception {
        boolean result = true;
        FlowTable flowTable = bookCommand.getFlowTable();
        
        //1. 根据【单据】+【明细账】获取记账工作表
        DataPackage dataPackage = bookCommand.getDocument();
        EntitySet detailSet = dataPackage.getItemEntitySet(bookCommand.getDocumentDetailTableName(), DataSource.Request);
 
        //2. 获取数据
        NamedSQL getRebateAmtBookFlow = NamedSQL.getInstance("getRebateAmtBookFlowBasicFields");
        
        getRebateAmtBookFlow.setParam("rebateId", bookCommand.getRebateId());
        getRebateAmtBookFlow.setParam("batch_mark", bookCommand.getBatchMark());
        getRebateAmtBookFlow.setParam("tableName", bookCommand.getDocumentTableName());
        getRebateAmtBookFlow.setParam("documentDetailParentId", "document_detail.parent_id" );
        getRebateAmtBookFlow.setParam("documentTypeCode" ,bookCommand.getConfigDocTypeSegment());
        getRebateAmtBookFlow.setParam("detailTableName", bookCommand.getDocumentDetailTableName());
        
        for (Entity entity: detailSet) {
            String rebateId = entity.getString(bookCommand.getRebateId());
            getRebateAmtBookFlow.setParam("rebateId", Util.quotedStr(rebateId));
            getRebateAmtBookFlow.setParam("document_num", bookCommand.getDocumentAmtSegment());
            
            Filter filter = new Filter();
            filter.add(bookCommand.getFilter());
            filter.add("document_detail.id", entity.getString("id"));
            getRebateAmtBookFlow.setFilter(filter);    
 
            
            EntitySet entitySet = SQLRunner.getEntitySet(getRebateAmtBookFlow);
            flowTable.appendEntitySet(entitySet);
        }
        
        return result;
    }
 
    private boolean getFlowTableAndValidate(BookCommand bookCommand) throws Exception {
        boolean result = true;
        String operate = bookCommand.getOperate();
        
        //1. 根据【单据】+【明细账】获取记账工作表
        NamedSQL getRebateAmtBookFlow = NamedSQL.getInstance("getRebateAmtBookFlowBasicFields");
        Filter filter = new Filter();
        filter.add(bookCommand.getFilter());
        getRebateAmtBookFlow.setParam("tableName", bookCommand.getDocumentTableName());
        getRebateAmtBookFlow.setParam("rebateId", "document_detail." + bookCommand.getRebateId());    
        getRebateAmtBookFlow.setParam("documentTypeCode" ,bookCommand.getConfigDocTypeSegment());
        
        if ((!Util.isEmpty(operate)) && "import".equalsIgnoreCase(operate)) {
            getRebateAmtBookFlow.setParam("detailTableName", bookCommand.getDocumentDetailTableName());
            getRebateAmtBookFlow.setParam("documentDetailParentId", "document_detail.id" );
            
            filter.add("document_detail.io_batch_id",bookCommand.getIoBatchId());
        }
        else if (bookCommand.getDetailTableName().equalsIgnoreCase(bookCommand.getDocumentDetailTableName())) {
            getRebateAmtBookFlow.setParam("detailTableName", bookCommand.getDocumentDetailTableName());
            getRebateAmtBookFlow.setParam("documentDetailParentId", "document_detail.id" );
            
            filter.add("document.id", bookCommand.getDocumentId());
        }
        else {
            getRebateAmtBookFlow.setParam("detailTableName", bookCommand.getDocumentAmtDetailTableName());
            getRebateAmtBookFlow.setParam("documentDetailParentId", "document_detail.parent_id" );
            
            filter.add("document.id",bookCommand.getDocumentId());
        }
        
        getRebateAmtBookFlow.setFilter(filter);    
        getRebateAmtBookFlow.setParam("batch_mark", bookCommand.getBatchMark());
        getRebateAmtBookFlow.setParam("document_num", bookCommand.getDocumentAmtSegment());
        
        //2. 获取数据
        EntitySet entitySet = SQLRunner.getEntitySet(getRebateAmtBookFlow);
        
        FlowTable flowTable = bookCommand.getFlowTable();
        flowTable.setEntitySet(entitySet);
        
        return result;
    }
 
    public void doWriteBook(BookCommand bookCommand) throws Exception {
        //1. 记库存流水
        writeStockFlow(bookCommand);
 
        if (bookCommand.getDocumentTableName().equalsIgnoreCase(bookCommand.getDocumentDetailTableName())) {
            return ;
        }
        
        //2. 记库存明细
        writeStockDetail(bookCommand);
    }
 
    private void writeStockFlow(BookCommand bookCommand) throws Exception {
        QtyCommand qtyCommand = bookCommand.getQtyCommand();
        if (qtyCommand.isDoNothing()) {
            return;
        }
        
        //1. 记录流水账
        DataObject dataObject = DataObject.getInstance(bookCommand.getFlowTableName());
        String batchMark = bookCommand.getBatchMark();
        FlowTable flowTable = bookCommand.getFlowTable();
        
        for (Entity flow : flowTable) {
            BigDecimal qty = flow.getBigDecimal("amt", BigDecimal.ZERO);
            
            if (BigDecimal.ZERO.equals(qty)) {
                continue;
            }
            EntitySaver saver = dataObject.createEntitySaver();
            
            saver.set("id", ID.newValue());    
            saver.set("rebate_id", flow.getValue("rebate_id"));
            saver.set("rebate_code", flow.getValue("rebate_code"));
            saver.set("operate_name", flow.getValue("operate_name"));
            saver.set("year", flow.getValue("year"));
            saver.set("season", flow.getValue("season"));
            saver.set("doc_date", flow.getValue("doc_date"));
            saver.set("doc_code", flow.getValue("doc_code"));
            
            saver.set("org_id", flow.getValue("org_id"));
            saver.set("account_id", flow.getValue("account_id"));
            saver.set("account_code", flow.getValue("account_code"));
            saver.set("account_name", flow.getString("account_name"));
            
            saver.set("bu_id", flow.getValue("bu_id"));
            saver.set("bu_name", flow.getValue("bu_name"));
            saver.set("company_id", flow.getValue("company_id"));
            saver.set("company_name", flow.getValue("company_name"));
            
            
            saver.set("valid_from", flow.getValue("valid_from"));
            saver.set("valid_to", flow.getValue("valid_to"));
            
            
            boolean qtyChanged = false;
            RecordOperator recordOperate = RecordOperator.Insert;
            boolean negativeConver = bookCommand.isNegativeConvert();
            
            if (qtyCommand.isSetAdd()) {
                BigDecimal qty_add = qty.multiply(qtyCommand.getAddOperator());
                
                if (qty_add.compareTo(BigDecimal.ZERO) < 0 && negativeConver) {
                    saver.set("num_used", BigDecimal.ZERO.subtract(qty_add));
                }
                else {
                    saver.set("num_return", qty_add);
                }
                recordOperate = RecordOperator.Update;
                qtyChanged = true;
            }    
            
            if (qtyCommand.isSetDelete()) {
                BigDecimal qty_delete = qty.multiply(qtyCommand.getDeleteOperator());
                
                if (qty_delete.compareTo(BigDecimal.ZERO) < 0 && negativeConver) {
                    saver.set("num_return", BigDecimal.ZERO.subtract(qty_delete));
                }
                else {
                    saver.set("num_used", qty_delete);
                }
                
                recordOperate = RecordOperator.Update;
                qtyChanged = true;
            }
        
            FreezeCondition freezeCondition = bookCommand.getFreezeCondition();
                    
            if (qtyCommand.isSetFreeze()) {
                BigDecimal qty_freeze = qty.multiply(qtyCommand.getFreezeOperator());
                
                //1. 例如:库存调整单,只有调减审批的时候才需要正数记冻结,只有调减审批不通过才能用负数记冻结
                if (freezeCondition.isCompatible(qty_freeze)) {
                    saver.set("num_freeze", qty_freeze);
                    qtyChanged = true;
                }
                recordOperate = RecordOperator.Update;
            }
            
            if (qtyCommand.isSetUnfreeze()) {
                BigDecimal qty_unfreeze = qty.multiply(qtyCommand.getUnfreezeOperator()); 
                
                //2. 例如:库存调整单,只有调减审批通过的时候才需要减少冻结
                if (freezeCondition.isCompatible(qty_unfreeze)) {
                    saver.set("num_unfreeze", qty_unfreeze);
                    qtyChanged = true;
                }
                recordOperate = RecordOperator.Update;
            }
            saver.set("record_operator", recordOperate.name());
            saver.set("batch_mark", batchMark);
            
            if(qtyChanged) {
                saver.insert();
            }
        }
 
    }
 
    private void writeStockDetail(BookCommand bookCommand) throws Exception {
        BookResult result = new BookResult();
        
        String batchMark = bookCommand.getBatchMark();
        Date bookDate = bookCommand.getBookDate();
        
        //1. 计入已使用
        NamedSQL writeUpdateStockDetail = NamedSQL.getInstance("writeUpdateRebateAmtDetail");
        writeUpdateStockDetail.setParam("batch_mark", batchMark);
        writeUpdateStockDetail.setParam("update_time", bookDate);        
        int updateCount = SQLRunner.execSQL(writeUpdateStockDetail);
        result.setUpdateCount(updateCount);
        
        //2. 补充明细账字段(余额,可用金额)
        NamedSQL resetStockDetailOtherFields = NamedSQL.getInstance("resetRebateAmtDetailOtherFields");
        resetStockDetailOtherFields.setParam("batch_mark", bookCommand.getBatchMark());
        resetStockDetailOtherFields.execute();        
        
        //3. 检查余额,可用余额
        NamedSQL getNegativeStockDetail = NamedSQL.getInstance("getNegativeRebateAmtDetail");
        getNegativeStockDetail.setParam("batch_mark", batchMark);
        int negativeCount = SQLRunner.getInteger(getNegativeStockDetail); 
        
        if (negativeCount > 0) {
            dataWriter.reportOneError("余额校验", "余额不足,无法抵扣");
            throw new Exception("余额不足,无法抵扣");
        }        
        
        //4. 日志并校验
        logger.debug("折扣明细>>计划记账{}条, 插入{} 条,修改{}条, 删除{}条;批次号:{}", 
            result.getPlanCount(), result.getInsertCount(), 
            result.getUpdateCount(), result.getDeleteCount(), batchMark);
        
        if (!result.isValid()) {
//                    throw new Exception("库存明细记账时存在错误,操作已经终止并回滚");
        }        
    }
 
    public Object tranferDocumentDocType(Object doc_type) {
        if ("普通销售出库".equals(doc_type)) {
            return "普通销售入库";
        }
        return doc_type;
    } 
}