-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvoiceEdit.widget.jsx
More file actions
591 lines (534 loc) · 20.8 KB
/
Copy pathInvoiceEdit.widget.jsx
File metadata and controls
591 lines (534 loc) · 20.8 KB
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
<BPUI.Page>
<BPUI.FormLayout submitAction={saveInvoices} cancelAction={cancel}>
{/*
* CUSTOM AD-HOC INVOICE FORM
*
*
*/}
{/*
* Account and email Recipient data.
* Loading the Account will retrieve the default email address from the Billing PRofile
*/}
<BPUI.Divider Name="Account Info" style ={{width: 1000 + "px"}}>Account and Delivery Info</BPUI.Divider>
<BPUI.Panel style ={{width: 900 + "px"}}>
<BPUI.Message name="invoice" variables={invoice}/>
<BPUI.InputField variable={billingProfile} field="AccountId" type="LOOKUP" label="Billing Name" onUpdate={accountIdUpdate}/>
<BPUI.OutputField name="AccountStatus" field="Status" variable={account} label="Account Status"/>
<BPUI.OutputField name="InvoiceStatus" field="Status" variable={invoice} label="Invoice Status"/>
<BPUI.OutputField name="ApprovalStatus" field="ApprovalStatus" variable={invoice} label="Approval Status"/>
<BPUI.OutputField name="BillingProfileId" field="BillingProfileId" variable={invoice} label="View Ledger"/>
<BPUI.OutputField name="cycle_name" field="cycle_name" variable={invoice} label="Cycle Type"/>
<BPUI.InputField name="Email" variable={billingProfile} field="Email"/>
<BPUI.InputField variable={invoice} field="BillingCycleStartDate"/>
<BPUI.InputField variable={invoice} field="BillingCycleEndDate"/>
{canClose()
? <BPUI.InputField name="ManualCloseApprovedFlag" variable={invoice} field="ManualCloseApprovedFlag" label="Close this Invoice" type="CHECKBOX" style={{display: canClose() ? '': 'hidden'}}/>
: <div/>}
{canApprove()
? <BPUI.InputField name="ApproveInvoice" variable={approveInvoice} label="Approve this Invoice" type="CHECKBOX" style={{display: canApprove() ? '': 'hidden'}}/>
: <div/>}
</BPUI.Panel>
{/* Spacer Row */}
<BPUI.Panel style ={{width: 900 + "px"}}>
<BPUI.PanelRow style ={{height: 30 + "px"}}>
<BPUI.PanelRowColumn />
</BPUI.PanelRow>
</BPUI.Panel>
<BPUI.Panel style ={{width: 900 + "px"}}>
<BPUI.PanelRow style ={{height: 30 + "px"}}>
<BPUI.PanelRowColumn />
</BPUI.PanelRow>
</BPUI.Panel>
{/*
* Invoice LIne Items (AKA Activity)
* Initialized on the javascript controller with 3 empty lines initially
*/}
<BPUI.Divider Name="ActivityDiv">Invoice Line Items</BPUI.Divider>
<BPUI.Panel style ={{width: 900 + "px"}}>
<BPUI.PanelRow>
<BPUI.PanelRowColumn className="col-sm-11" colSpan="4">
<BPUI.EmbeddedList variable={activities} name="activities" width="100%" onCellBlur={calculateRate} onAdd={addActivity}>
<BPUI.TableColumn name="ActivityDate" type="DATE_SELECTOR" displayTransform={formatDate} index="1" label="Service Date" />
<BPUI.TableColumn name="ProductId" index="2" label="Product"/>
<BPUI.TableColumn name="Quantity" index="3" label="Quantity"/>
<BPUI.TableColumn name="Rate" index="4" label="Rate"/>
<BPUI.TableColumn name="RatedAmount" index="5" label="Amount" editable="false"/>
</BPUI.EmbeddedList>
</BPUI.PanelRowColumn>
</BPUI.PanelRow>
</BPUI.Panel>
{/*
* Action Buttons
* - Add Rows in bulk. Adds 5 new Invoice Line Item (Activity) rows
* - Clear Rows: Clears the contents of all Invoice Line Items
* - Save: Saves the invoice with approval pending. Redirects user to the new Invoice in Record Mode.
* - Save & Send: Saves the invoice with and Approves (sends if email is the delivery option on the BillingProfile)
* - Cancel: Returns to the original Node with the Key in context.
*/}
<BPUI.Panel style ={{width: 900 + "px"}}>
<BPUI.PanelRow style ={{height: 20 + "px"}}>
<BPUI.PanelRowColumn className="col-sm-11 text-right">
<BPUI.Button name="add" title="Add" onClick={addLine}/>
<BPUI.Button name="remove" title="Remove" onClick={removeLine}/>
<BPUI.Button name="clear" title="Clear" onClick={clearLines}/>
</BPUI.PanelRowColumn >
</BPUI.PanelRow>
</BPUI.Panel>
{/* Spacer Row */}
<BPUI.Panel>
<BPUI.PanelRow style ={{height: 20 + "px"}}>
<BPUI.PanelRowColumn />
</BPUI.PanelRow>
</BPUI.Panel>
</BPUI.FormLayout>
</BPUI.Page>
_____________________________________________________________________________________________________________________
.body {}
.formButtons.topBar .col-sm-7{
display: flex;
align-items: center;
}
.formButtons.topBar .return-btn{
transform: translateY(0%) !important;
}
table.embedded-list td {
padding:0 !important;
vertical-align:middle !important;
}
.embedded-list td span,
.embedded-list td input,
.embedded-list td div{
height: 36px;
padding: 10px;
border: none;
background: transparent;
outline: none;
width: 100%;
line-height: 1.2em;
font-size: 13px;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
max-width: 300px;
}
.embedded-list td .icon-close.textbox-clear {
width: initial;
top: 50%;
right: 38px;
padding: 0;
font-size: initial;
height: initial;
/* top: 50%; */
background: #f9f9f9;
transform: translateY(-50%);
}
.embedded-list td .input-group .input-group-btn {
line-height: 29px;
width: initial;
padding: 0;
height: initial;
font-size: initial;
width:30px
}
.embedded-list td .lookup{
padding:0 !important;
}
.embedded-list td .lookup input[type="text"]{
background: initial;
padding:0 !important;
}
___
_____________________________________________________________________________________________________________________
BPActions = BPActions || window.BPActions;
//BPConnection.Activity.query for metadata
// BPConnection.AccountProductQuote.query
//Using the Window Objects enables the ability to debug using the Javascript Console
//
//window.BPSystem.bpRestApiUrl = "http://127.0.0.1:8081/rest/2.0";
window.invoice = new BPUI.ReferenceObject();
window.billingProfile = new BPUI.ReferenceObject();
window.account = new BPUI.ReferenceObject();
window.activities = new BPUI.ReferenceObject();
window.approveInvoice = new BPUI.ReferenceObject(false);
//
//Initialize the BP connection and session for database access
//
BPSystem.initialize();
function formatAmount(amount) {
if (amount) {
return parseFloat(amount).toFixed(2);
} else {
return "0.00";
}
}
function canClose() {
return (invoice.get() && invoice.get().Status !== 'CLOSED');
}
function canApprove() {
return (invoice.get() && invoice.get().Status === 'CLOSED' && invoice.get().ApprovalStatus !== 'APPROVED');
}
//
// Initialize the Form Objects
//
function init() {
var invoiceId = BPSystem.nodeKey;
// var invoiceId = BPSystem.getSelectedEntityId("INVOICE");
try {
var rows = findPageDataSync(invoiceId).elements;
if (rows.length) {
invoice.set(BPSystem.toBPObject({
Id: rows[0].InvoiceId,
BillingProfileId: rows[0].BillingProfileId,
BillingCycleStartDate: rows[0].BillingCycleStartDate,
BillingCycleEndDate: rows[0].BillingCycleEndDate,
Status: rows[0].InvoiceStatus,
ApprovalStatus: rows[0].ApprovalStatus,
cycle_name: rows[0].cycle_name,
}, new Invoice()));
billingProfile.set(BPSystem.toBPObject({
Id: rows[0].BillingProfileId,
AccountId: rows[0].AccountId,
Email: rows[0].Email
}, new BillingProfile()));
account.set(BPSystem.toBPObject({
Id: rows[0].AccountId,
Name: rows[0].Name,
Status: rows[0].AccountStatus
}, new Account()));
activities.set(BPSystem.toBPCollection(rows.map(function(row) {
return {
Id: row.ActivityId,
ProductId: row.ProductId,
SubscriptionFromDate: row.SubscriptionFromDate,
SubscriptionToDate: row.SubscriptionToDate,
ActivityDate: row.ActivityDate,
RatedAmount: formatAmount(row.RatedAmount),
Quantity: row.Quantity,
Rate: formatAmount(row.Rate),
RateOverride: formatAmount(row.RateOverride),
CostOverride: formatAmount(row.CostOverride)
};
}), new Activity()));
}
} catch (e) {
console.error(e);
BPActions.handleError(e, invoice);
}
};
//
//recalculate rates when products or quantities change
//
function calculateRate(row,column,event,scope) {
var activityCollection = activities.get();
var rowElement = activityCollection.elements[row];
console.log("CALCULATE RATE ",column,row,event,scope);
if (column==1||column==2||column==3) {
if (column == 1||column==2) {
console.log("CALCULATE RATE from product", rowElement, rowElement.ProductId, rowElement.ActivityDate);
if(rowElement.ProductId != null && rowElement.Quantity != null)
{
try {
/*BPConnection.Pricing.query("select ProductObj.Name,Rate,EffectiveDate,EndDate,CurrencyCodeObj.Id,UpperBand, CurrencyCodeObj.CurrencySign
from PRICING
where systimestamp BETWEEN EffectiveDate and EndDate and ProductObj.Id=" + rowElement.ProductId).collection().done(function (res) {
rowElement.RateOverride = res.elements[0].Rate;
});*/
var whereClause = "AccountId ="+account.get().Id
+" and ProductId ="+ rowElement.ProductId
+" and Quantity ="+ rowElement.Quantity;
//alert(whereClause);
BPConnection.AccountProductQuote.retrieveFilteredAsync(whereClause).single()
.done(function (res){
console.log('::::::::::::Rate:::::::::::');
console.log(res);
console.log('::::::::::::Rate END:::::::::::');
var rateDetails = $.parseXML(res.RateDetails);
rowElement.Rate = formatAmount($(rateDetails).find('RateDetailsRow > Rate').text());
//alert('::::> '+ res.Rate);
rowElement.RatedAmount = formatAmount($(rateDetails).find('RateDetailsRow > RatedAmount').text());
if (column === 3 || rowElement.RateOverride) {
rowElement.RateOverride = rowElement.Rate;
rowElement.CostOverride = rowElement.RatedAmount;
}
})
.fail(function (fail){console.log(fail.message);
alert(fail.message);
});
} catch (e) {
alert('ERROR: '+e);
console.log(e);
}
}
}
else if (rowElement.Quantity&&rowElement.Rate &&column==3 ) {
rowElement.RatedAmount = (rowElement.Rate*rowElement.Quantity).toFixed(2);
}
if (rowElement.Id) {
if (!activityCollection.updatedelements.filter(function(el) {return el.Id === rowElement.Id;}).length) {
activityCollection.updatedelements.push(rowElement);
}
}
}
}
function cancel()
{
BPSystem.cancel();
}
function addLine() {
addActivity(activities.get().elements.length - 1);
};
function removeLine() {
activities.get().removeFromCollection(activities.get().elements.length - 1);
BPActions.refreshState("activities");
};
function clearLines() {
var coll = activities.get();
for (var idx = coll.elements.length; idx; --idx) {
coll.removeFromCollection(0);
}
BPActions.refreshState("activities");
};
function addActivity(index)
{
activities.get().addNew({}, index + 1); // next item
activities.get().forEach(function(el) {
el.AccountId = account.get().Id;
el.InvoiceId = invoice.get().Id;
});
BPActions.refreshState("activities");
}
function saveInvoices()
{
if (!invoice.get().ManualCloseApprovedFlag) {
$('*').css('cursor', 'wait');
BPActions.clearError();
activities.get().forEach(function(el) {
el.ActivityDate = prepareDate(el.ActivityDate);
});
applyActions(getSaveActions());
} else {
saveAndSendInvoices();
}
};
function saveAndSendInvoices() {
$('*').css('cursor', 'wait');
BPActions.clearError();
activities.get().forEach(function(el) {
el.ActivityDate = prepareDate(el.ActivityDate);
});
// at first we are updating all data
var actions = ('CLOSED' == invoice.get().Status ? [] : getSaveActions());
actions.push(function() {
// after update we are closing invoice
var status = 'CLOSED',
approvalStatus = invoice.get().ApprovalStatus;
debugger;
if (approveInvoice.getValue()) {
approvalStatus = 'APPROVED';
}
return BPConnection.Invoice.update({
Id: invoice.get().Id,
Status: status,
ApprovalStatus: approvalStatus
});
});
//actions.push(function() {
// after closing invoice we can approve it
// but it must be different transaction
// invoice.get().ApprovalStatus = 'APPROVED';
// return BPConnection.Invoice.update(invoice.get());
//});
applyActions(actions);
};
function accountIdUpdate(accountId) {
//On select billingprofile id. Retrieve account to set it in invoices
BPConnection.BillingProfile.retrieveFilteredAsync("AccountId=" + accountId).single().done(function (result) {
window.billingProfile.set(result);
});
};
function getSaveActions() {
var actions = [];
actions.push(function() {
return BPConnection.BillingProfile.update(billingProfile.get());
});
actions.push(function() {
var entity = invoice.get();
if (approveInvoice.getValue()) {
entity.ApprovalStatus = 'APPROVED';
}
return BPConnection.Invoice.update(entity);
});
if (hasAttachment("Attachment1")) {
actions.push(function() {
return BPActions.uploadFile("[data-name=Attachment1] [type=file]", "INVOICE", "Attachment1", invoice.get().Id);
});
}
if (hasAttachment("Attachment2")) {
actions.push(function() {
return BPActions.uploadFile("[data-name=Attachment2] [type=file]", "INVOICE", "Attachment2", invoice.get().Id);
});
}
if (hasAttachment("Attachment3")) {
actions.push(function() {
return BPActions.uploadFile("[data-name=Attachment3] [type=file]", "INVOICE", "Attachment3", invoice.get().Id);
});
}
if (activities.get().deletedelements.length) {
actions.push(function() {
return activities.get().remove();
});
}
if (activities.get().createdelements.length) {
actions.push(function() {
return activities.get().create();
});
}
if (activities.get().updatedelements.length) {
actions.push(function() {
return activities.get().update();
});
}
return actions;
};
function formatDate(val) {
if (val) {
return moment(val).format('MM/DD/YYYY');
} else {
return val;
}
};
function prepareDate(val) {
if (val) {
return moment(val).format('YYYY-MM-DDTHH:mm:ssZ');
} else {
return val;
}
};
function hasAttachment(name) {
return !!$("[data-name=" + name + "] [type=file]").val();
};
function setAttachment(entity, id, name) {
return BPActions.uploadFile("[data-name=" + name + "] [type=file]", entity, name, id);
};
function getPageDataQuery(invoiceId) {
var oldQuery = "select BillingProfileId, "
+ "Status, "
+ "ApprovalStatus, "
+ "ManualCloseApprovedFlag, "
+ "BillingProfileObj.Id, "
+ "BillingProfileObj.Email, "
+ "BillingProfileObj.AccountId, "
+ "BillingProfileObj.AccountObj.Id, "
+ "BillingProfileObj.AccountObj.Name, "
+ "BillingProfileObj.AccountObj.Status, "
+ "(select ProductId,"
+ "SubscriptionFromDate, "
+ "SubscriptionToDate, "
+ "RatedAmount,"
+ "ActivityDate, "
+ "Quantity, "
+ "Rate, "
+ "RateOverride, "
+ "CostOverride "
+ "from Activity.InvoiceObj "
+ "order by ActivityDate) "
+ "from INVOICE where Id=" + invoiceId;
return "select inv.Id as InvoiceId, "
+ "inv.BillingProfileId, "
+ "to_char(inv.BillingCycleStartDate, 'YYYY-MM-DD') as BillingCycleStartDate, "
+ "to_char(inv.BillingCycleEndDate, 'YYYY-MM-DD') as BillingCycleEndDate, "
+ "inv.Status as InvoiceStatus, "
+ "inv.ApprovalStatus, "
+ "inv.ManualCloseApprovedFlag, "
+ "bp.Email, "
+ "bp.AccountId, "
+ "acc.Name, "
+ "acc.Status as AccountStatus, "
+ "act.Id as ActivityId, "
+ "act.ProductId, "
+ "to_char(act.SubscriptionFromDate, 'YYYY-MM-DD') as SubscriptionFromDate, "
+ "to_char(act.SubscriptionToDate, 'YYYY-MM-DD') as SubscriptionToDate, "
+ "to_char(act.ActivityDate, 'YYYY-MM-DD') as ActivityDate, "
+ "act.RatedAmount, "
+ "act.Quantity, "
+ "act.Rate, "
+ "c.name AS cycle_name,"
+ "act.RateOverride "
+ "from INVOICE inv "
+ "left join BILLING_PROFILE bp on inv.BillingProfileId=bp.Id "
+ "left join ACCOUNT acc on bp.AccountId=acc.Id "
+ "left join ACTIVITY act on inv.Id=act.InvoiceId "
+ "LEFT JOIN event_invoice_cycle c ON inv.eventinvoicecycleid = c.id "
+ "where inv.Id=" + invoiceId + " "
+ "and rownum < 1000 "
+ "order by act.ActivityDate";
};
function findPageDataSync(invoiceId) {
return BPConnection.Invoice.query(getPageDataQuery(invoiceId)).collection();
};
function findPageDataAsync(invoiceId) {
return BPConnection.Invoice.queryAsync(getPageDataQuery(invoiceId)).single();
};
function notifySuccess(result) {
BPSystem.cancel('R');
};
function notifyFailure(result, message) {
$('*').css('cursor', 'default');
var text = message + ": " + JSON.stringify(result);
console.log(result);
console.warn(text);
console.warn(result);
BPActions.handleError(result, invoice);
//BPActions.showError(text, "invoice", invoice);
};
function assert(value, message) {
if (!value) console.error(message);
};
function assertDone(promise, message) {
var deferred = $.Deferred();
promise.done(function(result) {
var errorCode = result || [];
errorCode = errorCode[0] || {};
errorCode = errorCode.ErrorCode;
if (errorCode === "0") {
notifySuccess(result);
deferred.resolve(result);
} else {
notifyFailure(result, message);
deferred.reject(result);
}
}).fail(function(result) {
notifyFailure(result, message);
deferred.reject(result);
});
return deferred.promise();
};
function applyActions(funcs) {
var func = funcs.shift();
if (func) {
func().done(function(result) {
BPActions.handleError(result);
applyActions(funcs);
}).fail(function(result) {
notifyFailure(result, "Failed to perform sequence of actions");
});
} else {
notifySuccess();
}
};
window.onerror = function(e) {
notifyFailure(e, "Javascript Error");
};
init();
BPUI.afterRender = function () {
if(invoice.get().Status == 'CLOSED')
BPActions.changeState("ManualCloseApprovedFlag", {type: "LABEL"});
//* * * * fast lookup fix (init text from data). If it crash the widget need to remove it and fix LookUP propertly
try{
BPDispatcher._callbacks.ID_2({
type:BPActions.CONSTANTS.LOAD_DATA,
data:{NAME:account.get().Name},
NODE_KEY:billingProfile.get().Id})
}catch(e){console.error('lookup fix',e)}
//* * * *
}