]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/acq/po/view_po.js
LP#1058321: Possible to receive a pending purchase order
[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         if(PO.state() == "on-order") {
323             dojo.removeAttr('receive_po', 'disabled');
324         } else if(PO.state() == "received") {
325             dojo.removeAttr('rollback_receive_po', 'disabled');
326         }
327     }
328
329     makePrepayWidget(
330         dojo.byId("acq-po-view-prepay"),
331         openils.Util.isTrue(PO.prepayment_required())
332     );
333     makeCancelWidget(
334         dojo.byId("acq-po-view-cancel-reason"),
335         dojo.byId("acq-po-cancel-label")
336     );
337     // dojo.byId("acq-po-view-notes").innerHTML = PO.notes().length;
338     poNoteTable.updatePoNotesCount();
339
340     if (PO.state() == "pending") {
341         checkCouldActivatePo();
342         if (PO.lineitem_count() > 1)
343             openils.Util.show("acq-po-split");
344     } else {
345         dojo.byId("acq-po-activate-checking").innerHTML = localeStrings.NO;
346     }
347
348     // XXX we probably don't *always* need to do this...
349     poItemTable.reset();
350     PO.po_items().forEach(
351         function(po_item) { poItemTable.addItem(po_item); }
352     );
353     poItemTable.show();
354
355     dojo.attr(
356         "acq-po-view-history", "href",
357         oilsBasePath + "/acq/po/history/" + PO.id()
358     );
359     openils.Util.show("acq-po-view-history", "inline");
360
361     
362     /* if we got here from the search/invoice page with a focused LI,
363      * return to the previous page with the same LI focused */
364     var cgi = new openils.CGI();
365     var source = cgi.param('source');
366     var focus_li = cgi.param('focus_li');
367     if (focus_li && source) {
368         dojo.forEach(
369             ['search', 'invoice'], // perhaps a wee bit too loose
370             function(srcType) {
371                 if (source.match(new RegExp(srcType))) {
372                     openils.Util.show('acq-po-return-to-' + srcType);
373                     var newCgi = new openils.CGI({url : source});
374                     newCgi.param('focus_li', focus_li);
375                     dojo.byId('acq-po-return-to-' + srcType + '-button').onclick = function() {
376                         location.href = newCgi.url();
377                     }
378                 }
379             }
380         );
381     }
382
383     prepareInvoiceFeatures();
384 }
385
386
387 function init() {
388     /* set up li table */
389     liTable = new AcqLiTable();
390     liTable.reset();
391     liTable.isPO = poId;
392     liTable.poUpdateCallback = updatePoState;
393
394     /* set up po notes table */
395     poNoteTable = new AcqPoNoteTable();
396
397     /* retrieve data and populate */
398     fieldmapper.standardRequest(
399         ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
400         {   async: true,
401             params: [openils.User.authtoken, poId, {
402                 "flesh_provider": true,
403                 "flesh_price_summary": true,
404                 "flesh_lineitem_count": true,
405                 "flesh_notes": true,
406                 "flesh_po_items": true
407             }],
408             oncomplete: function(r) {
409                 PO = openils.Util.readResponse(r); /* save PO globally */
410
411                 /* po item table */
412                 poItemTable = new PoItemTable(PO, pcrud);
413
414                 renderPo();
415             }
416         }
417     );
418
419     var totalEstimated = 0;
420     var zeroLi = true;
421     fieldmapper.standardRequest(
422         ['open-ils.acq', 'open-ils.acq.lineitem.search'],
423         {   async: true,
424             params: [
425                 openils.User.authtoken, 
426                 [{purchase_order:poId}, {"order_by": {"jub": "id ASC"}}], 
427                 {flesh_attrs:true, flesh_notes:true, flesh_cancel_reason:true, clear_marc:true}
428             ],
429             onresponse: function(r) {
430                 zeroLi = false;
431                 liTable.show('list');
432                 var li = openils.Util.readResponse(r);
433                 // TODO: Add po_item's to total estimated amount
434                 totalEstimated += (Number(li.item_count() || 0) * Number(li.estimated_unit_price() || 0));
435                 liTable.addLineitem(li);
436             },
437
438             oncomplete : function() {
439                 dojo.byId("acq-po-view-total-estimated").innerHTML = totalEstimated.toFixed(2);
440                 if (liFocus) liTable.drawCopies(liFocus);
441                 if(zeroLi) openils.Util.show('acq-po-no-lineitems');
442             }
443         }
444     );
445
446     pcrud.search(
447         'acqedim', 
448         {purchase_order : poId}, 
449         {
450             id_list : true,
451             oncomplete : function(r) {
452                 var resp = openils.Util.readResponse(r);
453                 // TODO: I18n
454                 if(resp) {
455                     dojo.byId('acq-po-view-edi-messages').innerHTML = '(' + resp.length + ')';
456                     dojo.byId('acq-po-view-edi-messages').setAttribute('href', oilsBasePath + '/acq/po/edi_messages/' + poId);
457                 } else {
458                     dojo.byId('acq-po-view-edi-messages').innerHTML = '0';
459                     dojo.byId('acq-po-view-edi-messages').setAttribute('href', '');
460                 }
461             }
462         }
463     );
464 }
465
466 function checkCouldActivatePo() {
467     var d = dojo.byId("acq-po-activate-checking");
468     var a = dojo.byId("acq-po-activate-link");
469     d.innerHTML = localeStrings.PO_CHECKING;
470     var warnings = [];
471     var stops = [];
472     var other = [];
473
474     fieldmapper.standardRequest(
475         ["open-ils.acq", "open-ils.acq.purchase_order.activate.dry_run"], {
476             "params": [
477                 openils.User.authtoken,
478                 PO.id(),
479                 null,  // vandelay options
480                 {zero_copy_activate : dojo.byId('acq-po-activate-zero-copies').checked}
481             ],
482             "async": true,
483             "onresponse": function(r) {
484                 if ((r = openils.Util.readResponse(r, true /* eventOk */))) {
485                     if (typeof(r.textcode) != "undefined") {
486                         switch(r.textcode) {
487                             case "ACQ_FUND_EXCEEDS_STOP_PERCENT":
488                                 stops.push(r);
489                                 break;
490                             case "ACQ_FUND_EXCEEDS_WARN_PERCENT":
491                                 warnings.push(r);
492                                 break;
493                             default:
494                                 other.push(r);
495                         }
496                     }
497                 }
498             },
499             "oncomplete": function() {
500                 /* XXX in the future, this might be tweaked to display info
501                  * about more than one stop or warning event from the ML. */
502                 if (!(warnings.length || stops.length || other.length)) {
503                     d.innerHTML = localeStrings.PO_COULD_ACTIVATE;
504                     openils.Util.show(a, "inline");
505                 } else {
506                     if (other.length) {
507                         /* XXX make the textcode part a tooltip one day */
508                         d.innerHTML = localeStrings.NO + ": " +
509                             other[0].desc + " (" + other[0].textcode + ")";
510                         openils.Util.hide(a);
511                         
512                         if (other[0].textcode == 'ACQ_LINEITEM_NO_COPIES') {
513                             // when LIs w/ zero LIDs are present, list them
514                             fieldmapper.standardRequest(
515                                 [   'open-ils.acq', 
516                                     'open-ils.acq.purchase_order.no_copy_lineitems.id_list.authoritative.atomic' ],
517                                 {   async : true, 
518                                     params : [openils.User.authtoken, poId],
519                                     oncomplete : function(r) {
520                                         var ids = openils.Util.readResponse(r);
521                                         d.innerHTML += ' (' + ids + ')';
522                                     }
523                                 }
524                             );
525                         }
526                     } else if (stops.length) {
527                         d.innerHTML =
528                             dojo.string.substitute(
529                                 localeStrings.PO_STOP_BLOCKS_ACTIVATION, [
530                                     stops[0].payload.fund.code(),
531                                     stops[0].payload.fund.year()
532                                 ]
533                             );
534                         openils.Util.hide(a);
535                     } else {
536                         PO._warning_hack = true;
537                         d.innerHTML =
538                             dojo.string.substitute(
539                                 localeStrings.PO_WARNING_NO_BLOCK_ACTIVATION, [
540                                     warnings[0].payload.fund.code(),
541                                     warnings[0].payload.fund.year()
542                                 ]
543                             );
544                         openils.Util.show(a, "inline");
545                     }
546                 }
547             }
548         }
549     );
550 }
551
552 function activatePo() {
553     if (openils.Util.isTrue(PO.prepayment_required())) {
554         if (!confirm(localeStrings.PREPAYMENT_REQUIRED_REMINDER))
555             return false;
556     }
557
558     if (PO._warning_hack) {
559         if (!confirm(localeStrings.PO_FUND_WARNING_CONFIRM))
560             return false;
561     }
562
563     liTable.showAssetCreator(activatePoStage2);
564 }
565
566 function activatePoStage2() {
567
568     var want_refresh = false;
569     progressDialog.show(true);
570     fieldmapper.standardRequest(
571         ["open-ils.acq", "open-ils.acq.purchase_order.activate"], {
572             "async": true,
573             "params": [
574                 openils.User.authtoken,
575                 PO.id(),
576                 null,  // vandelay options
577                 {zero_copy_activate : dojo.byId('acq-po-activate-zero-copies').checked}
578             ],
579             "onresponse": function(r) {
580                 want_refresh = Boolean(openils.Util.readResponse(r));
581             },
582             "oncomplete": function() {
583                 progressDialog.hide();
584                 if (want_refresh)
585                     location.href = location.href;
586             }
587         }
588     );
589 }
590
591 function splitPo() {
592     progressDialog.show(true);
593     try {
594         var list;
595         fieldmapper.standardRequest(
596             ['open-ils.acq', 'open-ils.acq.purchase_order.split_by_lineitems'],
597             {   async: true,
598                 params: [openils.User.authtoken, PO.id()],
599                 onresponse : function(r) {
600                     list = openils.Util.readResponse(r);
601                 },
602                 oncomplete : function() {
603                     progressDialog.hide();
604                     if (list) {
605                         location.href = oilsBasePath + '/acq/po/search/' +
606                             list.join(",");
607                     }
608                 }
609             }
610         );
611     } catch(E) {
612         progressDialog.hide();
613         alert(E);
614     }
615 }
616
617 function updatePoName() {
618     var value = prompt('Enter new purchase order name:', PO.name()); // TODO i18n
619     if(!value || value == PO.name()) return;
620     PO.name(value);
621     pcrud.update(PO, {
622         oncomplete : function(r, cudResults) {
623             var stat = cudResults[0];
624             if(stat)
625                 dojo.byId('acq-po-view-name').innerHTML = value;
626         }
627     });
628 }
629
630 openils.Util.addOnLoad(init);