4c2a7e712f299ffb7554280b3192ad0b77e78644
[working/Evergreen.git] / Open-ILS / web / js / ui / default / acq / po / view_po.js
1 dojo.require("dijit.form.Button");
2 dojo.require("dojo.string");
3 dojo.require('dijit.layout.ContentPane');
4 dojo.require('openils.PermaCrud');
5
6 var pcrud = new openils.PermaCrud();
7 var PO = null;
8 var liTable;
9 var poItemTable;
10 var poNoteTable;
11 var invoiceLinkDialogManager;
12
13 function AcqPoNoteTable() {
14     var self = this;
15
16     this.notesTbody = dojo.byId("acq-po-notes-tbody");
17     this.notesRow = this.notesTbody.removeChild(dojo.byId("acq-po-notes-row"));
18
19     dojo.byId("acq-po-notes-back-button").onclick = function() { self.hide(); };
20     dojo.byId("acq-po-view-notes").onclick = function() { self.show(); };
21
22     /* widgets' event properties are cased likeThis */
23     acqPoCreateNoteSubmit.onClick = function() {
24         if (!acqPoCreateNoteText.attr("value")) return;
25
26         /* prep new note */
27         var note = new acqpon();
28         note.vendor_public(
29             Boolean(acqPoCreateNoteVendorPublic.attr('checked'))
30         );
31         note.value(acqPoCreateNoteText.attr("value"));
32         note.purchase_order(PO.id());
33         note.isnew(true);
34
35         /* save it */
36         self.updatePoNotes(note);
37
38         /* reset fields for next use */
39         acqPoCreateNoteText.attr("value", "");
40         acqPoCreateNoteVendorPublic.attr("checked", false);
41     };
42
43     this.drawPoNote = function(note) {
44         if (note.isdeleted())
45             return;
46
47         var row = dojo.clone(this.notesRow);
48
49         nodeByName("value", row).innerHTML = note.value();
50
51         if (openils.Util.isTrue(note.vendor_public()))
52             nodeByName("vendor_public", row).innerHTML =
53                 localeStrings.VENDOR_PUBLIC;
54
55         nodeByName("delete", row).onclick = function() {
56             note.isdeleted(true);
57             self.notesTbody.removeChild(row);
58             self.updatePoNotes();
59         };
60
61         if (note.edit_time()) {
62             nodeByName("edit_time", row).innerHTML =
63                 dojo.date.locale.format(
64                     dojo.date.stamp.fromISOString(note.edit_time()),
65                     {"formatLength": "short"}
66                 );
67         }
68
69         self.notesTbody.appendChild(row);
70     };
71
72     this.drawPoNotes = function() {
73         /* sort */
74         PO.notes(
75             PO.notes().sort(
76                 function(a, b) {
77                     return (a.edit_time() < b.edit_time()) ? 1 : -1;
78                 }
79             )
80         );
81
82         /* remove old renderings of notes */
83         dojo.empty(this.notesTbody);
84
85         PO.notes().forEach(function(o) { self.drawPoNote(o); });
86     };
87
88     this.updatePoNotesCount = function() {
89         dojo.byId("acq-po-view-notes").innerHTML =
90             "(" + PO.notes().length + ")";
91     };
92
93     this.updatePoNotes = function(newNote) {
94         var notes = newNote ?
95             [newNote] :
96             PO.notes().filter(
97                 function(o) {
98                     if (o.ischanged() || o.isnew() || o.isdeleted())
99                         return o;
100                 }
101             );
102
103         if (notes.length < 1)
104             return;
105
106         progressDialog.show();
107
108         fieldmapper.standardRequest(
109             ["open-ils.acq", "open-ils.acq.po_note.cud.batch"], {
110                 "async": true,
111                 "params": [openils.User.authtoken, notes],
112                 "onresponse": function(r) {
113                     var resp = openils.Util.readResponse(r);
114                     if (resp) {
115                         progressDialog.update(resp);
116
117                         if (!resp.note.isdeleted()) {
118                             resp.note.isnew(false);
119                             resp.note.ischanged(false);
120                             PO.notes().push(resp.note);
121                         }
122                     }
123                 },
124                 "oncomplete": function() {
125                     if (!newNote) {
126                         /* remove the old changed notes */
127                         var list = [];
128                         PO.notes(
129                             PO.notes().filter(
130                                 function(o) {
131                                     return (!(
132                                         o.ischanged() || o.isnew() ||
133                                         o.isdeleted()
134                                     ));
135                                 }
136                             )
137                         );
138                     }
139
140                     progressDialog.hide();
141                     self.updatePoNotesCount();
142                     self.drawPoNotes();
143                 }
144             }
145         );
146     };
147
148     this.hide = function() {
149         openils.Util.hide("acq-po-notes-div");
150         liTable.show("list");
151         poItemTable.show();
152     };
153
154     this.show = function() {
155         liTable.hide();
156         poItemTable.hide();
157         self.drawPoNotes();
158         openils.Util.show("acq-po-notes-div");
159     };
160 }
161
162 function updatePoState(po_info) {
163     var data = po_info[PO.id()];
164     if (data) {
165         for (var key in data)
166             PO[key](data[key]);
167         renderPo();
168     }
169 }
170
171 function cancellationUpdater(r) {
172     var r = openils.Util.readResponse(r);
173     if (r) {
174         if (r.po) updatePoState(r.po);
175         if (r.li) {
176             for (var id in r.li) {
177                 liTable.liCache[id].state(r.li[id].state);
178                 liTable.liCache[id].cancel_reason(r.li[id].cancel_reason);
179                 liTable.updateLiState(liTable.liCache[id]);
180             }
181         }
182         if (r.lid && liTable.copyCache) {
183             for (var id in r.lid) {
184                 if (liTable.copyCache[id]) {
185                     liTable.copyCache[id].cancel_reason(
186                         r.lid[id].cancel_reason
187                     );
188                     liTable.updateLidState(liTable.copyCache[id]);
189                 }
190             }
191         }
192     }
193 }
194
195 function makeProviderLink(node, provider) {
196     return dojo.create(
197         "a", {
198             "href": oilsBasePath + "/conify/global/acq/provider/" + provider.id(),
199             "innerHTML": provider.name() + " (" + provider.code() + ")",
200         },
201         node,
202         "only"
203     );
204 }
205 function makePrepayWidget(node, prepay) {
206     if (prepay) {
207         openils.Util.addCSSClass(node, "oils-acq-po-prepay");
208         node.innerHTML = localeStrings.YES;
209     } else {
210         openils.Util.removeCSSClass(node, "oils-acq-po-prepay");
211         node.innerHTML = localeStrings.NO;
212     }
213 }
214
215 function makeCancelWidget(node, labelnode) {
216     openils.Util.hide("acq-po-choose-cancel-reason");
217
218     if (PO.cancel_reason()) {
219         labelnode.innerHTML = localeStrings.CANCEL_REASON;
220         node.innerHTML = PO.cancel_reason().description() + " (" +
221             PO.cancel_reason().label() + ")";
222     } else if (["on-order", "pending"].indexOf(PO.state()) == -1) {
223         dojo.destroy(this.oldTip);
224         labelnode.innerHTML = "";
225         node.innerHTML = "";
226     } else {
227         dojo.destroy(this.oldTip);
228         labelnode.innerHTML = localeStrings.CANCEL;
229         node.innerHTML = "";
230         if (!acqPoCancelReasonSubmit._prepared) {
231             var widget = new openils.widget.AutoFieldWidget({
232                 "fmField": "cancel_reason",
233                 "fmClass": "acqpo",
234                 "parentNode": dojo.byId("acq-po-cancel-reason"),
235                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
236                 "forceSync": true
237             });
238             widget.build(
239                 function(w, ww) {
240                     acqPoCancelReasonSubmit.onClick = function() {
241                         if (w.attr("value")) {
242                             if (confirm(localeStrings.PO_CANCEL_CONFIRM)) {
243                                 fieldmapper.standardRequest(
244                                     ["open-ils.acq",
245                                         "open-ils.acq.purchase_order.cancel"],
246                                     {
247                                         "params": [
248                                             openils.User.authtoken,
249                                             PO.id(), 
250                                             w.attr("value")
251                                         ],
252                                         "async": true,
253                                         "oncomplete": cancellationUpdater
254                                     }
255                                 );
256                             }
257                         }
258                     };
259                     acqPoCancelReasonSubmit._prepared = true;
260                 }
261             );
262         }
263         openils.Util.show("acq-po-choose-cancel-reason", "inline");
264     }
265 }
266
267 function prepareInvoiceFeatures() {
268     /* show the count of related invoices on the "view invoices" button */
269     fieldmapper.standardRequest(
270         ["open-ils.acq", "open-ils.acq.invoice.unified_search.atomic"], {
271             "params": [
272                 openils.User.authtoken,
273                 {"acqpo":[{"id": PO.id()}]},
274                 null,
275                 null,
276                 {"id_list": true}
277             ],
278             "async": true,
279             "oncomplete": function(r) {
280                 dojo.byId("acq-po-view-invoice-count").innerHTML =
281                     openils.Util.readResponse(r).length;
282             }
283         }
284     );
285
286     /* view invoices button */
287     dijit.byId("acq-po-view-invoice-link").onClick = function() {
288         location.href = oilsBasePath + "/acq/search/unified?so=" +
289             base64Encode({"acqpo":[{"id": PO.id()}]}) +
290             "&rt=invoice";
291     };
292
293     /* create invoice button */
294     dijit.byId("acq-po-create-invoice-link").onClick = function() {
295         location.href = oilsBasePath +
296             "/acq/invoice/view?create=1&attach_po=" + PO.id();
297     };
298
299     openils.Util.show("acq-po-invoice-stuff", "table-cell");
300 }
301
302 function renderPo() {
303     dojo.byId("acq-po-view-id").innerHTML = PO.id();
304     dojo.byId("acq-po-view-name").innerHTML = PO.name();
305     makeProviderLink(
306         dojo.byId("acq-po-view-provider"),
307         PO.provider()
308     );
309     dojo.byId("acq-po-view-total-li").innerHTML = PO.lineitem_count();
310     dojo.byId("acq-po-view-total-enc").innerHTML = PO.amount_encumbered().toFixed(2);
311     dojo.byId("acq-po-view-total-spent").innerHTML = PO.amount_spent().toFixed(2);
312     dojo.byId("acq-po-view-state").innerHTML = PO.state(); // TODO i18n
313
314     if(PO.order_date()) {
315         openils.Util.show('acq-po-activated-on', 'inline');
316         dojo.byId('acq-po-activated-on').innerHTML = 
317             dojo.string.substitute(
318                 localeStrings.PO_ACTIVATED_ON, [
319                     openils.Util.timeStamp(PO.order_date(), {formatLength:'short'})
320                 ]
321             );
322
323     }
324
325     makePrepayWidget(
326         dojo.byId("acq-po-view-prepay"),
327         openils.Util.isTrue(PO.prepayment_required())
328     );
329     makeCancelWidget(
330         dojo.byId("acq-po-view-cancel-reason"),
331         dojo.byId("acq-po-cancel-label")
332     );
333     // dojo.byId("acq-po-view-notes").innerHTML = PO.notes().length;
334     poNoteTable.updatePoNotesCount();
335
336     if (PO.state() == "pending") {
337         checkCouldActivatePo();
338         if (PO.lineitem_count() > 1)
339             openils.Util.show("acq-po-split");
340     } else {
341         dojo.byId("acq-po-activate-checking").innerHTML = localeStrings.NO;
342     }
343
344     // XXX we probably don't *always* need to do this...
345     poItemTable.reset();
346     PO.po_items().forEach(
347         function(po_item) { poItemTable.addItem(po_item); }
348     );
349     poItemTable.show();
350
351     dojo.attr(
352         "acq-po-view-history", "href",
353         oilsBasePath + "/acq/po/history/" + PO.id()
354     );
355     openils.Util.show("acq-po-view-history", "inline");
356
357     
358     /* if we got here from the search/invoice page with a focused LI,
359      * return to the previous page with the same LI focused */
360     var cgi = new openils.CGI();
361     var source = cgi.param('source');
362     var focus_li = cgi.param('focus_li');
363     if (focus_li && source) {
364         dojo.forEach(
365             ['search', 'invoice'], // perhaps a wee bit too loose
366             function(srcType) {
367                 if (source.match(new RegExp(srcType))) {
368                     openils.Util.show('acq-po-return-to-' + srcType);
369                     var newCgi = new openils.CGI({url : source});
370                     newCgi.param('focus_li', focus_li);
371                     dojo.byId('acq-po-return-to-' + srcType + '-button').onclick = function() {
372                         location.href = newCgi.url();
373                     }
374                 }
375             }
376         );
377     }
378
379     prepareInvoiceFeatures();
380 }
381
382
383 function init() {
384     /* set up li table */
385     liTable = new AcqLiTable();
386     liTable.reset();
387     liTable.isPO = poId;
388     liTable.poUpdateCallback = updatePoState;
389
390     /* set up po notes table */
391     poNoteTable = new AcqPoNoteTable();
392
393     /* retrieve data and populate */
394     fieldmapper.standardRequest(
395         ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
396         {   async: true,
397             params: [openils.User.authtoken, poId, {
398                 "flesh_provider": true,
399                 "flesh_price_summary": true,
400                 "flesh_lineitem_count": true,
401                 "flesh_notes": true,
402                 "flesh_po_items": true
403             }],
404             oncomplete: function(r) {
405                 PO = openils.Util.readResponse(r); /* save PO globally */
406
407                 /* po item table */
408                 poItemTable = new PoItemTable(PO, pcrud);
409
410                 renderPo();
411             }
412         }
413     );
414
415     var totalEstimated = 0;
416     var zeroLi = true;
417     fieldmapper.standardRequest(
418         ['open-ils.acq', 'open-ils.acq.lineitem.search'],
419         {   async: true,
420             params: [
421                 openils.User.authtoken, 
422                 [{purchase_order:poId}, {"order_by": {"jub": "id ASC"}}], 
423                 {flesh_attrs:true, flesh_notes:true, flesh_cancel_reason:true, clear_marc:true}
424             ],
425             onresponse: function(r) {
426                 zeroLi = false;
427                 liTable.show('list');
428                 var li = openils.Util.readResponse(r);
429                 // TODO: Add po_item's to total estimated amount
430                 totalEstimated += (Number(li.item_count() || 0) * Number(li.estimated_unit_price() || 0));
431                 liTable.addLineitem(li);
432             },
433
434             oncomplete : function() {
435                 dojo.byId("acq-po-view-total-estimated").innerHTML = totalEstimated.toFixed(2);
436                 if (liFocus) liTable.drawCopies(liFocus);
437                 if(zeroLi) openils.Util.show('acq-po-no-lineitems');
438             }
439         }
440     );
441
442     pcrud.search(
443         'acqedim', 
444         {purchase_order : poId}, 
445         {
446             id_list : true,
447             oncomplete : function(r) {
448                 var resp = openils.Util.readResponse(r);
449                 // TODO: I18n
450                 if(resp) {
451                     dojo.byId('acq-po-view-edi-messages').innerHTML = '(' + resp.length + ')';
452                     dojo.byId('acq-po-view-edi-messages').setAttribute('href', oilsBasePath + '/acq/po/edi_messages/' + poId);
453                 } else {
454                     dojo.byId('acq-po-view-edi-messages').innerHTML = '0';
455                     dojo.byId('acq-po-view-edi-messages').setAttribute('href', '');
456                 }
457             }
458         }
459     );
460 }
461
462 function checkCouldActivatePo() {
463     var d = dojo.byId("acq-po-activate-checking");
464     var a = dojo.byId("acq-po-activate-link");
465     d.innerHTML = localeStrings.PO_CHECKING;
466     var warnings = [];
467     var stops = [];
468     var other = [];
469
470     fieldmapper.standardRequest(
471         ["open-ils.acq", "open-ils.acq.purchase_order.activate.dry_run"], {
472             "params": [
473                 openils.User.authtoken,
474                 PO.id(),
475                 null,  // vandelay options
476                 {zero_copy_activate : dojo.byId('acq-po-activate-zero-copies').checked}
477             ],
478             "async": true,
479             "onresponse": function(r) {
480                 if ((r = openils.Util.readResponse(r, true /* eventOk */))) {
481                     if (typeof(r.textcode) != "undefined") {
482                         switch(r.textcode) {
483                             case "ACQ_FUND_EXCEEDS_STOP_PERCENT":
484                                 stops.push(r);
485                                 break;
486                             case "ACQ_FUND_EXCEEDS_WARN_PERCENT":
487                                 warnings.push(r);
488                                 break;
489                             default:
490                                 other.push(r);
491                         }
492                     }
493                 }
494             },
495             "oncomplete": function() {
496                 /* XXX in the future, this might be tweaked to display info
497                  * about more than one stop or warning event from the ML. */
498                 if (!(warnings.length || stops.length || other.length)) {
499                     d.innerHTML = localeStrings.PO_COULD_ACTIVATE;
500                     openils.Util.show(a, "inline");
501                 } else {
502                     if (other.length) {
503                         /* XXX make the textcode part a tooltip one day */
504                         d.innerHTML = localeStrings.NO + ": " +
505                             other[0].desc + " (" + other[0].textcode + ")";
506                         openils.Util.hide(a);
507                         
508                         if (other[0].textcode == 'ACQ_LINEITEM_NO_COPIES') {
509                             // when LIs w/ zero LIDs are present, list them
510                             fieldmapper.standardRequest(
511                                 [   'open-ils.acq', 
512                                     'open-ils.acq.purchase_order.no_copy_lineitems.id_list.authoritative.atomic' ],
513                                 {   async : true, 
514                                     params : [openils.User.authtoken, poId],
515                                     oncomplete : function(r) {
516                                         var ids = openils.Util.readResponse(r);
517                                         d.innerHTML += ' (' + ids + ')';
518                                     }
519                                 }
520                             );
521                         }
522                     } else if (stops.length) {
523                         d.innerHTML =
524                             dojo.string.substitute(
525                                 localeStrings.PO_STOP_BLOCKS_ACTIVATION, [
526                                     stops[0].payload.fund.code(),
527                                     stops[0].payload.fund.year()
528                                 ]
529                             );
530                         openils.Util.hide(a);
531                     } else {
532                         PO._warning_hack = true;
533                         d.innerHTML =
534                             dojo.string.substitute(
535                                 localeStrings.PO_WARNING_NO_BLOCK_ACTIVATION, [
536                                     warnings[0].payload.fund.code(),
537                                     warnings[0].payload.fund.year()
538                                 ]
539                             );
540                         openils.Util.show(a, "inline");
541                     }
542                 }
543             }
544         }
545     );
546 }
547
548 function activatePo() {
549     if (openils.Util.isTrue(PO.prepayment_required())) {
550         if (!confirm(localeStrings.PREPAYMENT_REQUIRED_REMINDER))
551             return false;
552     }
553
554     if (PO._warning_hack) {
555         if (!confirm(localeStrings.PO_FUND_WARNING_CONFIRM))
556             return false;
557     }
558
559     liTable.showAssetCreator(activatePoStage2);
560 }
561
562 function activatePoStage2() {
563
564     var want_refresh = false;
565     progressDialog.show(true);
566     fieldmapper.standardRequest(
567         ["open-ils.acq", "open-ils.acq.purchase_order.activate"], {
568             "async": true,
569             "params": [
570                 openils.User.authtoken,
571                 PO.id(),
572                 null,  // vandelay options
573                 {zero_copy_activate : dojo.byId('acq-po-activate-zero-copies').checked}
574             ],
575             "onresponse": function(r) {
576                 want_refresh = Boolean(openils.Util.readResponse(r));
577             },
578             "oncomplete": function() {
579                 progressDialog.hide();
580                 if (want_refresh)
581                     location.href = location.href;
582             }
583         }
584     );
585 }
586
587 function splitPo() {
588     progressDialog.show(true);
589     try {
590         var list;
591         fieldmapper.standardRequest(
592             ['open-ils.acq', 'open-ils.acq.purchase_order.split_by_lineitems'],
593             {   async: true,
594                 params: [openils.User.authtoken, PO.id()],
595                 onresponse : function(r) {
596                     list = openils.Util.readResponse(r);
597                 },
598                 oncomplete : function() {
599                     progressDialog.hide();
600                     if (list) {
601                         location.href = oilsBasePath + '/acq/po/search/' +
602                             list.join(",");
603                     }
604                 }
605             }
606         );
607     } catch(E) {
608         progressDialog.hide();
609         alert(E);
610     }
611 }
612
613 function updatePoName() {
614     var value = prompt('Enter new purchase order name:', PO.name()); // TODO i18n
615     if(!value || value == PO.name()) return;
616     PO.name(value);
617     pcrud.update(PO, {
618         oncomplete : function(r, cudResults) {
619             var stat = cudResults[0];
620             if(stat)
621                 dojo.byId('acq-po-view-name').innerHTML = value;
622         }
623     });
624 }
625
626 openils.Util.addOnLoad(init);