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