IT-KIMI_SHI\SINOIT.KIMI
2018-06-01 64c40fb427bff513f575f11e4c1e7bd9a1bfe3e3
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
package fine;
 
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.activiti.engine.task.Task;
 
import process.service.IServiceCaller;
import process.service.IdentityService;
import process.service.TaskService;
import process.service.HistoryService;
import foundation.callable.Callable;
import foundation.config.Configer;
import foundation.data.Entity;
import foundation.data.EntitySet;
import foundation.data.Variant;
import foundation.file.download.ClientAction;
import foundation.file.download.HttpResponseWriter;
import foundation.persist.DataHandler;
import foundation.persist.sql.NamedSQL;
import foundation.persist.sql.SQLRunner;
 
public class BusinessConsole extends Callable implements IServiceCaller {
    
    private TaskService taskService;
    private HistoryService historyService;
    private IdentityService identityService;
    
    
    public BusinessConsole() throws Exception {
        taskService = new TaskService(this);
        historyService = new HistoryService(this);
        identityService = new IdentityService(this);
    }
    
    @Override
    protected void publishMethod() {
        addMethod("getTodoAgreement");
        addMethod("newAgreementVersion");
        addMethod("approveAgreement");
        addMethod("preview");
        addMethod("getMyHistotyApprove");
        addMethod("startProcess");
    }
    
    protected void startProcess() throws Exception {
        Variant dataId = getParameter("id");
        // type = tablename  e.g.   agreement 
        String tableName = getParameter("type").getStringValue();
        Entity entity = DataHandler.getLine(tableName, dataId.getStringValue());
        String typecode = entity.getString("typecode");
        dataPool.addParameter("typecode", typecode);
        
        if (tableName.equalsIgnoreCase("feeslit")) {
            calculateRebate(tableName,dataId.getStringValue(),typecode,4);
            
         }
        String processInstanceId = identityService.startProcess();
        
        NamedSQL updateNamedSQL = NamedSQL.getInstance("updateById");
         String fieldNameValues = "workflowId = '" + processInstanceId + "',statuscode='commit'";
        updateNamedSQL.setParam("tablename", tableName);
        updateNamedSQL.setParam("fieldNameId", "id");
        updateNamedSQL.setParam("id", "'"+dataId+"'");
         updateNamedSQL.setParam("fieldNameValues", fieldNameValues);
         updateNamedSQL.exec();
    }
 
    
    private void calculateRebate(String tableName, String dataId, String typecode,int scale) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-DD");
        EntitySet freelitdetailEntitySet = DataHandler.getDataSet(tableName+"detail", "parentid="+dataId);
        List<Entity> agreementList = new ArrayList<Entity>();
        
        for (Entity feesLitDetail: freelitdetailEntitySet) {
            
            //1. update salesflow_month qty
            String flowId = feesLitDetail.getString("flowid");
            Entity salesflowMonth = DataHandler.getLine("salesflow_month", flowId);
            
            BigDecimal qty = feesLitDetail.getBigDecimal("qty");
            BigDecimal qtyBook = salesflowMonth.getBigDecimal("qty_book");
            BigDecimal qtyAvailable = salesflowMonth.getBigDecimal("qty_available");
            BigDecimal qtyUsed = salesflowMonth.getBigDecimal("qty_used");
            BigDecimal qty_available = qtyAvailable.subtract(qty).subtract(qtyUsed);
            qtyBook = qtyBook.add(qty);
            salesflowMonth.set("qty_book", qtyBook);
            salesflowMonth.set("qty_available", qty_available);
            DataHandler.updateLine(salesflowMonth);
            
            //2. calculate rebate
            
            String agentId = feesLitDetail.getString("agentid");
            String productId = feesLitDetail.getString("productid");
            Integer flowYear = feesLitDetail.getInteger("flowyear");
            Integer flowMonth = feesLitDetail.getInteger("flowmonth");
            
            EntitySet agreementEntitySet = DataHandler.getDataSet("agreement", "1=1");
            
            for (Entity agreement : agreementEntitySet) {
                String statusCode = agreement.getString("statuscode");
                
                if (statusCode.equalsIgnoreCase("open")) {
                    String agreementTypeCode = agreement.getString("typecode");
                    String agreementAgentId = agreement.getString("agentid");
                    
                    if (agreementTypeCode.equalsIgnoreCase(typecode) && agreementAgentId.equalsIgnoreCase(agentId)) {
                        int startYear = Integer.valueOf(dateFormat.format(agreement.getDate("begindate")).split("-")[0]);
                        int startMonth = Integer.valueOf(dateFormat.format(agreement.getDate("begindate")).split("-")[1]);
                        int endYear = Integer.valueOf(dateFormat.format(agreement.getDate("enddate")).split("-")[0]);
                        int endMonth = Integer.valueOf(dateFormat.format(agreement.getDate("enddate")).split("-")[1]);
                        
                        if (flowYear >= startYear && flowYear < endYear || flowYear >= startYear && flowYear == endYear && flowMonth >= startMonth && flowMonth <= endMonth) {
                            agreementList.add(agreement);
                        }
                    }
                }
            }
            // size >1 means bad info
            if (agreementList.size() > 1) {
                return ;
            }
            Entity agrement = agreementList.get(0);
            EntitySet agreementFineDetailEntitySet = DataHandler.getDataSet("agreementfinedetail", "parentid="+agrement.getString("id"));
            
            for (Entity agreementFineDetail : agreementFineDetailEntitySet) {
                String agreementProductid = agreementFineDetail.getString("productid");
                
                if (agreementProductid.equalsIgnoreCase(productId)) {
                    //1. linked  agreementFineDetail and feesLitDetail
                    String agreementFineDetailId = agreementFineDetail.getString("id");
                    feesLitDetail.setString("agreementfinedetailid", agreementFineDetailId);
                    
                    //2.calculate 
                    if (typecode.equalsIgnoreCase("PurchaseAndSale")) {
                        BigDecimal priceLowest = new BigDecimal(agreementFineDetail.getString("price_lowest"));
                        BigDecimal priceInvoice = new BigDecimal(agreementFineDetail.getString("price_invoice"));
                        BigDecimal rateTax = new BigDecimal(agreementFineDetail.getString("rate_tax"));
                        
                        BigDecimal singleRebate = priceInvoice.subtract(priceLowest);
                        BigDecimal preTaxPendingRebate = qty.multiply(singleRebate);
                        BigDecimal taxBigDecimal = BigDecimal.valueOf(1).subtract(rateTax);
                        BigDecimal pendingRebate = preTaxPendingRebate.multiply(taxBigDecimal).setScale(scale);
                        feesLitDetail.set("price_rebate", pendingRebate);
                    }
                    else if (typecode.equalsIgnoreCase("others")) {
                        //TODO other type
                    }
                    DataHandler.updateLine(feesLitDetail);
                }
            }
        }
        
        
        
    }
 
    protected void getMyHistotyApprove() throws Exception {
        
        ArrayList<Entity> result = new ArrayList<Entity>();
        EntitySet entitySet = DataHandler.getDataSet("agreement", "1=1");
        List<String> myHistotyApprove = historyService.getMyHistotyApprove();
        
        for (Entity entity : entitySet) {
            String id = entity.getString("workflowid");
            if (myHistotyApprove.contains(id)) {
                result.add(entity);
            }
        }
        resultPool.addValue(result);
    }
 
    protected void getTodoAgreement() throws Exception {
        
        ArrayList<Entity> result = new ArrayList<Entity>();
        String filter = getParameter("filter").getStringValue();
        EntitySet entitySet = DataHandler.getDataSet("agreement", filter);
        List<String> todoTaskId = taskService.getTodoTask();
        
        for (Entity entity : entitySet) {
            String id = entity.getString("id");
            if (todoTaskId.contains(id)) {
                result.add(entity);
            }
        }
        resultPool.addValue(result);
    }
    
    protected void newAgreementVersion() throws Exception {
        identityService.startProcess();
    }
    
    protected void approveAgreement() throws Exception {
        Variant dataId = getParameter("id");
        Variant isReset = getParameter("isReset");
        String tableName = getParameter("type").getStringValue();
 
        
        //1.claim
        String taskid = taskService.claimTask();
        if (taskid == null) {
            return;
        }
        
        dataPool.addParameter("taskid", taskid);
        
        //2.complete
        boolean success = taskService.completeTask();
        if (!success) {
            return;
        }
 
        if (isReset.getBooleanValue()) {
            NamedSQL namedSQL = NamedSQL.getInstance("updateTableStatusCodeById");
            namedSQL.setParam("statuscode", "commit");
            namedSQL.setParam("id", dataId.getStringValue());
            namedSQL.setParam("tablename", tableName);
            namedSQL.exec();
        }
        
        Task task = taskService.geTask();
        if(task != null && task.getTaskDefinitionKey().equalsIgnoreCase("modifyApply")) {
            NamedSQL namedSQL = NamedSQL.getInstance("updateTableStatusCodeById");
            namedSQL.setParam("id", dataId.getStringValue());
            namedSQL.setParam("tablename", tableName);
            namedSQL.setParam("statuscode", "isReset");
            namedSQL.exec();
        }
        
        
        //3.update status
        if (historyService.isTaskFinished()) {
            NamedSQL namedSQL = NamedSQL.getInstance("updateTableStatusCodeById");
            namedSQL.setParam("id", dataId.getStringValue());
            namedSQL.setParam("tablename", tableName);
            if (getParameter("passFlag").getStringValue().equalsIgnoreCase("false")) {
                namedSQL.setParam("statuscode", "close");
            }else {
                namedSQL.setParam("statuscode", "open");
            }
            namedSQL.exec();
        }
        
        resultPool.success();
    }
 
    protected void preview() throws Exception {
        Variant code = dataPool.getParameter("code");
        
        NamedSQL namedSQL = NamedSQL.getInstance("getApplicationTemplatePath");
        namedSQL.setParam("code", code.getStringValue());
        String path = SQLRunner.getString(namedSQL);
        String root = Configer.getParam("applicationTemplateRoot");
        
        File file = new File(root, path);
        
        if (!file.exists()) {
            resultPool.error("file not exists: " + file);
            return;
        }
        
        HttpResponseWriter writer = new HttpResponseWriter(response);
        writer.write(file, ClientAction.AsPDF);
    }
    
    @Override
    public void error(String error) {
        resultPool.error(error);
    }
 
    @Override
    public Variant getParameter(String name) {
        return dataPool.getParameter(name);
    }
}