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