Bug 29407: Make the pickup locations dropdown JS reusable
[koha.git] / koha-tmpl / intranet-tmpl / prog / js / additem.js
1 /* global __ */
2 /* exported addItem checkCount showItem deleteItemBlock clearItemBlock check_additem */
3 function addItem( node, unique_item_fields ) {
4     var index = $(node).closest("div").attr('id');
5     var current_qty = parseInt($("#quantity").val());
6     var max_qty;
7     if($("#quantity_to_receive").length != 0){
8         max_qty = parseInt($("#quantity_to_receive").val());
9     } else  {
10         max_qty = 99999;
11     }
12     if ( $("#items_list table").find('tr[idblock="' + index + '"]').length == 0 ) {
13         if ( current_qty < max_qty ) {
14             if ( current_qty < max_qty - 1 )
15                 cloneItemBlock(index, unique_item_fields);
16             addItemInList(index, unique_item_fields);
17             $("#" + index).find("input[name='buttonPlus']").val( __("Update item") );
18             $("#"+ index).find("input[name='buttonPlusMulti']").remove();
19             $("#" + index).find("input[name='multiValue']").remove();
20             $("#quantity").val(current_qty + 1).change();
21         } else if ( current_qty >= max_qty ) {
22             alert( __("You can't receive any more items") );
23         }
24     } else {
25         if ( current_qty < max_qty )
26             cloneItemBlock(index, unique_item_fields);
27         var tr = constructTrNode(index);
28         $("#items_list table").find('tr[idblock="' + index + '"]:first').replaceWith(tr);
29     }
30     $("#" + index).hide();
31 }
32
33 function addMulti( count, node, unique_item_fields){
34     var index = $(node).closest("div").attr('id');
35     var countItemsBefore = $("#items_list tbody tr").length;
36     var current_qty = parseInt( $('#quantity').val(), 10 );
37     $("#procModal").modal('show');
38     $("#" + index).hide();
39     for(var i=0;i<count;i++){
40         cloneItemBlock(index, unique_item_fields, function(cloneIndex){
41             addItemInList(cloneIndex,unique_item_fields, function(){
42                 if( ($("#items_list tbody tr").length-countItemsBefore)==(count)){
43                     $("#multiValue").val('');
44                     $('#'+index).appendTo('#outeritemblock');
45                     $('#'+index).show();
46                     $('#'+index + ' #add_multiple_copies' ).css("visibility","hidden");
47                     $("#procModal").modal('hide');
48                 }
49             });
50             $("#" + cloneIndex).find("input[name='buttonPlus']").val( ( __("Update item") ) );
51             $("#" + cloneIndex).find("input[name='buttonPlusMulti']").remove();
52             $("#" + cloneIndex).find("input[name='multiValue']").remove();
53             $("#" + cloneIndex).hide();
54             current_qty++;
55             $('#quantity').val( current_qty );
56         });
57     }
58 }
59
60 function checkCount(node, unique_item_fields){
61     var count = parseInt( $("#multiValue").val(), 10 );
62     if ( isNaN( count ) || count <=0) {
63         $("#multiCountModal").modal('show');
64     }
65     else{
66         addMulti( count, node, unique_item_fields);
67     }
68 }
69
70 function showItem(index) {
71     $("#outeritemblock").children("div").each(function(){
72         if ( $(this).attr('id') == index ) {
73             $(this).show();
74         } else {
75             if ( $("#items_list table").find('tr[idblock="' + $(this).attr('id') + '"]').length == 0 ) {
76                 $(this).remove();
77             } else {
78                 $(this).hide();
79             }
80         }
81     });
82 }
83
84 function constructTrNode(index, unique_item_fields) {
85     var fields = ['barcode', 'homebranch', 'holdingbranch', 'notforloan',
86         'restricted', 'location', 'itemcallnumber', 'copynumber',
87         'stocknumber', 'ccode', 'itype', 'materials', 'itemnotes'];
88
89     var result = "<tr idblock='" + index + "'>";
90     var edit_link = "<a href='#itemfieldset' style='text-decoration:none' onclick='showItem(\"" + index + "\");' class='btn btn-default btn-xs'><i class='fa fa-pencil'></i> "
91         + ( __("Edit") ) + "</a>";
92     var del_link = "<a style='cursor:pointer' "
93         + "onclick='deleteItemBlock(this, \"" + index + "\", \"" + unique_item_fields + "\");' class='btn btn-default btn-xs'><i class='fa fa-trash'></i> "
94         + ( __("Delete") ) + "</a>";
95     result += "<td class='actions'>" + edit_link + " " + del_link + "</td>";
96     for(var i in fields) {
97         var field = fields[i];
98         var field_elt = $("#" + index)
99             .find("[name='kohafield'][value='items."+field+"']")
100             .prevAll("[name='field_value']")[0];
101         var field_value;
102         if($(field_elt).is('select')) {
103             field_value = $(field_elt).find("option:selected").text();
104         } else {
105             field_value = $(field_elt).val();
106         }
107         if (field_value == undefined) {
108             field_value = '';
109         }
110         result += "<td>" + field_value + "</td>";
111     }
112     result += "</tr>";
113
114     return result;
115 }
116
117 function addItemInList(index, unique_item_fields, callback) {
118     $("#items_list").show();
119     var tr = constructTrNode(index, unique_item_fields);
120     $("#items_list table tbody").append(tr);
121     if (typeof callback === "function"){
122         callback();
123     }
124 }
125
126 function deleteItemBlock(node_a, index, unique_item_fields) {
127     $("#" + index).remove();
128     var current_qty = parseInt($("#quantity").val());
129     var max_qty;
130     if($("#quantity_to_receive").length != 0) {
131         max_qty = parseInt($("#quantity_to_receive").val());
132     } else {
133         max_qty = 99999;
134     }
135     $("#quantity").val(current_qty - 1).change();
136     $(node_a).parents('tr').remove();
137     if(current_qty - 1 == 0)
138         $("#items_list").hide();
139
140     if ( $("#quantity").val() <= max_qty - 1) {
141         if ( $("#outeritemblock").children("div :visible").length == 0 ) {
142             $("#outeritemblock").children("div:last").show();
143         }
144     }
145     if ( $("#quantity").val() == 0 && $("#outeritemblock > div").length == 0) {
146         cloneItemBlock(0, unique_item_fields);
147     }
148 }
149
150 function cloneItemBlock(index, unique_item_fields, callback) {
151     var original;
152     if(index) {
153         original = $("#" + index); //original <div>
154     }
155     var dont_copy_fields = new Array();
156     if(unique_item_fields) {
157         dont_copy_fields = unique_item_fields.split('|');
158         for(var i in dont_copy_fields) {
159             dont_copy_fields[i] = "items." + dont_copy_fields[i];
160         }
161     }
162
163     $.ajax({
164         url: "/cgi-bin/koha/services/itemrecorddisplay.pl",
165         dataType: 'html',
166         data: {
167             frameworkcode: 'ACQ'
168         },
169         success: function(data) {
170             /* Create the item block */
171             var random = Math.floor(Math.random()*100000); // get a random itemid.
172             var clone = $("<div/>", { id: 'itemblock'+random });
173             $("#outeritemblock").append(clone);
174             $(clone).append(data);
175             /* Change all itemid fields value */
176             $(clone).find("input[name='itemid']").each(function(){
177                 $(this).val(random);
178             });
179             /* Add buttons + and Clear */
180             var buttonPlus = "<fieldset class=\"action\">";
181             buttonPlus += '<input type="button" class="addItemControl" name="buttonPlus" style="cursor:pointer; margin:0 1em;" onclick="addItem(this,\'' + unique_item_fields + '\')" value="' + ( __("Add item") )+ '" />';
182             buttonPlus += '<input type="button" class="addItemControl cancel" name="buttonClear" style="cursor:pointer;" onclick="clearItemBlock(this)" value="' + __("Clear") + '" />';
183             buttonPlus += '<input type="button" class="addItemControl" name="buttonPlusMulti" onclick="javascript:this.nextSibling.style.display=\'inline\'; return false;" style="cursor:pointer; margin:0 1em;" value="' + __("Add multiple items") + '" />';
184             buttonPlus += '<span id="add_multiple_copies" style="display:none">'
185                 +     '<input type="text" inputmode="numeric" pattern="[0-9]*" class="addItemControl" id="multiValue" name="multiValue" placeholder="' + __("Number of items to add") + '" />'
186                 +     '<input type="button" class="addItemControl" name=buttonAddMulti" style="cursor:pointer; margin:0 1em;" onclick="checkCount( this ,\'' + unique_item_fields + '\')" value="' + __("Add") + '" />'
187                 +     '<div class="dialog message">' + __("NOTE: Fields listed in the 'UniqueItemsFields' system preference will not be copied") + '</div>'
188                 + '</span>';
189             buttonPlus += "</fieldset>";
190             $(clone).append(buttonPlus);
191             /* Copy values from the original block (input) */
192             $(original).find("input[name='field_value']").each(function(){
193                 var kohafield = $(this).siblings("input[name='kohafield']").val();
194                 if($(this).val() && $.inArray(kohafield,dont_copy_fields) == -1) {
195                     $(this).parent("div").attr("id").match(/^(subfield.)/);
196                     var id = RegExp.$1;
197                     var value = $(this).val();
198                     $(clone).find("div[id^='"+id+"'] input[name='field_value']").val(value);
199                 }
200             });
201             /* Copy values from the original block (select) */
202             $(original).find("select[name='field_value']").each(function(){
203                 var kohafield = $(this).siblings("input[name='kohafield']").val();
204                 if($(this).val() && $.inArray(kohafield,dont_copy_fields) == -1) {
205                     $(this).parent("div").attr("id").match(/^(subfield.)/);
206                     var id = RegExp.$1;
207                     var value = $(this).val();
208                     $(clone).find("div[id^='"+id+"'] select[name='field_value']").val(value);
209                 }
210             });
211
212             if (typeof callback === "function"){
213                 var cloneIndex = "itemblock"+random;
214                 callback(cloneIndex);
215             }
216             BindPluginEvents(data);
217         }
218     });
219 }
220
221 function BindPluginEvents(data) {
222 // the script tag in data for plugins contains a document ready that binds
223 // the events for the plugin
224 // when we append, this code does not get executed anymore; so we do it here
225     var events= data.match(/BindEventstag_\d+_subfield_._\d+/g);
226     if ( events == null ) return;
227     for(var i=0; i<events.length; i++) {
228         window[events[i]]();
229         if( i<events.length-1 && events[i]==events[i+1] ) { i++; }
230         // normally we find the function name twice
231     }
232 }
233
234 function clearItemBlock(node) {
235     var index = $(node).closest("div").attr('id');
236     var block = $("#"+index);
237     $(block).find("input[type='text']").each(function(){
238         $(this).val("");
239     });
240     $(block).find("select").each(function(){
241         $(this).find("option:first").attr("selected", true);
242     });
243 }
244
245 function check_additem(unique_item_fields) {
246     var success = true;
247     var data = new Object();
248     data['field'] = new Array();
249     data['value'] = new Array();
250     var array_fields = unique_item_fields.split('|');
251     $(".order_error").empty(); // Clear error div
252
253     // Check if a value is duplicated in form
254     for ( var field in array_fields ) {
255         var fieldname = array_fields[field];
256         if (fieldname == '') {
257             continue;
258         }
259         var values = new Array();
260         $("[name='kohafield'][value='items."+ fieldname +"']").each(function(){
261             var input = $(this).prevAll("input[name='field_value']")[0];
262             if($(input).val()) {
263                 values.push($(input).val());
264                 data['field'].push(fieldname);
265                 data['value'].push($(input).val());
266             }
267         });
268
269         var sorted_arr = values.sort();
270         for (var i = 0; i < sorted_arr.length - 1; i += 1) {
271             if (sorted_arr[i + 1] == sorted_arr[i]) {
272                 $(".order_error").append(
273                     fieldname + " '" + sorted_arr[i] + "' "
274                     + __("is duplicated")
275                     + "<br/>");
276                 success = false;
277             }
278         }
279     }
280
281     // If there is a duplication, we raise an error
282     if ( success == false ) {
283         $(".order_error").show();
284         return false;
285     }
286
287     $.ajax({
288         url: '/cgi-bin/koha/acqui/check_uniqueness.pl',
289         async: false,
290         dataType: 'json',
291         data: data,
292         success: function(data) {
293             for (var field in data) {
294                 success = false;
295                 for (var i=0; i < data[field].length; i++) {
296                     var value = data[field][i];
297                     $(".order_error").append(
298                         field + " '" + value + "' "
299                         + __("already exists in database")
300                         + "<br />"
301                     );
302                 }
303             }
304         }
305     });
306
307     if ( success == false ) {
308         $(".order_error").show();
309     }
310     return success;
311 }
312