06397315919188a5538d157b0e8ba99a42cf5db8
[kivitendo-erp.git] / bin / mozilla / ic.pl
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger, Accounting
9 # Copyright (c) 2001
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #======================================================================
29 #
30 # Inventory Control module
31 #
32 #======================================================================
33
34 use POSIX qw(strftime);
35 use List::Util qw(max);
36 use List::MoreUtils qw(any);
37
38 use SL::AM;
39 use SL::IC;
40 use SL::ReportGenerator;
41
42 #use SL::PE;
43
44 # use strict;
45 #use warnings;
46
47 # global imports
48 our ($form, $locale, %myconfig, $lxdebug);
49
50 require "bin/mozilla/io.pl";
51 require "bin/mozilla/invoice_io.pl";
52 require "bin/mozilla/common.pl";
53 require "bin/mozilla/reportgenerator.pl";
54
55 1;
56
57 # Parserhappy(R):
58 # type=submit $locale->text('Add Part')
59 # type=submit $locale->text('Add Service')
60 # type=submit $locale->text('Add Assembly')
61 # type=submit $locale->text('Edit Part')
62 # type=submit $locale->text('Edit Service')
63 # type=submit $locale->text('Edit Assembly')
64 # $locale->text('Parts')
65 # $locale->text('Services')
66 # $locale->text('Inventory quantity must be zero before you can set this part obsolete!')
67 # $locale->text('Inventory quantity must be zero before you can set this assembly obsolete!')
68 # $locale->text('Part Number missing!')
69 # $locale->text('Service Number missing!')
70 # $locale->text('Assembly Number missing!')
71 # $locale->text('ea');
72
73 # end of main
74
75 sub add {
76   $lxdebug->enter_sub();
77
78   $auth->assert('part_service_assembly_edit');
79
80   $form->{title}           = $locale->text('Add ' . ucfirst $form->{item});
81   $form->{callback}        = "$form->{script}?action=add&item=$form->{item}" unless $form->{callback};
82   $form->{unit_changeable} = 1;
83
84   IC->get_pricegroups(\%myconfig, \%$form);
85   &link_part;
86   &display_form;
87
88   $lxdebug->leave_sub();
89 }
90
91 sub search {
92   $lxdebug->enter_sub();
93
94   $auth->assert('part_service_assembly_edit');
95
96   $form->{revers}       = 0;  # switch for backward sorting
97   $form->{lastsort}     = ""; # memory for which table was sort at last time
98   $form->{ndxs_counter} = 0;  # counter for added entries to top100
99
100   my %is_xyz     = map { +"is_$_" => ($form->{searchitems} eq $_) } qw(part service assembly);
101
102   $form->{title} = (ucfirst $form->{searchitems}) . "s";
103   $form->{title} = $locale->text($form->{title});
104   $form->{title} = $locale->text('Assemblies') if ($is_xyz{is_assembly});
105
106   $form->{jsscript} = 1;
107
108   $form->header;
109
110   print $form->parse_html_template('ic/search', { %is_xyz,
111                                                   dateformat => $myconfig{dateformat}, });
112
113   $lxdebug->leave_sub();
114 }    #end search()
115
116 sub search_update_prices {
117   $lxdebug->enter_sub();
118
119   $auth->assert('part_service_assembly_edit');
120
121   my $pricegroups = IC->get_pricegroups(\%myconfig, \%$form);
122
123   $form->header;
124
125   print $form->parse_html_template('ic/search_update_prices', { PRICE_ROWS => $pricegroups });
126
127   $lxdebug->leave_sub();
128 }    #end search()
129
130 sub confirm_price_update {
131   $lxdebug->enter_sub();
132
133   $auth->assert('part_service_assembly_edit');
134
135   my @errors      = ();
136   my $value_found = false;
137
138   foreach my $idx (qw(sellprice listprice), (1..$form->{price_rows})) {
139     my $name      = $idx =~ m/\d/ ? $form->{"pricegroup_${idx}"}      : $idx eq 'sellprice' ? $locale->text('Sell Price') : $locale->text('List Price');
140     my $type      = $idx =~ m/\d/ ? $form->{"pricegroup_type_${idx}"} : $form->{"${idx}_type"};
141     my $value_idx = $idx =~ m/\d/ ? "price_${idx}" : $idx;
142     my $value     = $form->parse_amount(\%myconfig, $form->{$value_idx});
143
144     if ((0 > $value) && ($type eq 'percent')) {
145       push @errors, $locale->text('You cannot adjust the price for pricegroup "#1" by a negative percentage.', $name);
146
147     } elsif (!$value && ($form->{$value_idx} ne '')) {
148       push @errors, $locale->text('No valid number entered for pricegroup "#1".', $name);
149
150     } elsif (0 < $value) {
151       $value_found = 1;
152     }
153   }
154
155   push @errors, $locale->text('No prices will be updated because no prices have been entered.') if (!$value_found);
156
157   my $num_matches = IC->get_num_matches_for_priceupdate();
158
159   $form->header();
160
161   if (@errors) {
162     $form->show_generic_error(join('<br>', @errors), 'back_button' => 1);
163   }
164
165   $form->{nextsub} = "update_prices";
166
167   map { delete $form->{$_} } qw(action header);
168
169   print $form->parse_html_template('ic/confirm_price_update', { HIDDENS     => [ map { name => $_, value => $form->{$_} }, keys %$form ],
170                                                                 num_matches => $num_matches });
171
172   $lxdebug->leave_sub();
173 }
174
175 sub update_prices {
176   $lxdebug->enter_sub();
177
178   $auth->assert('part_service_assembly_edit');
179
180   my $num_updated = IC->update_prices(\%myconfig, \%$form);
181
182   if (-1 != $num_updated) {
183     $form->redirect($locale->text('#1 prices were updated.', $num_updated));
184   } else {
185     $form->error($locale->text('Could not update prices!'));
186   }
187
188   $lxdebug->leave_sub();
189 }
190
191 #sub choice {
192 #  $lxdebug->enter_sub();
193 #
194 #  $auth->assert('part_service_assembly_edit');
195 #
196 #  our ($j, $lastndx);
197 #  my ($totop100);
198 #
199 #  $form->{title} = $locale->text('Top 100 hinzufuegen');
200 #
201 #  $form->header;
202 #
203 #  push @custom_hiddens, qw(searchitems title bom titel revers lastsort sort ndxs_counter extras);
204 #  push @custom_hiddens, qw(itemstatus l_linetotal l_partnumber l_description l_onhand l_unit l_sellprice l_linetotalsellprice);
205 #  my @HIDDENS = (
206 #        +{ name => 'row',     value => $j              },
207 #        +{ name => 'nextsub', value => 'item_selected' },
208 #        +{ name => 'test',    value => 'item_selected' },
209 #        +{ name => 'lastndx', value => $lastndx        },
210 #    map(+{ name => $_,        value => $form->{$_}     }, @custom_hiddens),
211 #  );
212 #
213 #  my ($partnumber, $description, $unit, $sellprice, $soldtotal);
214 #  # if choice set data
215 ##  if ($form->{ndx}) {
216 ##    for my $i (0 .. $form->{ndxs_counter}) {
217 ##
218 ##      # insert data into top100
219 ##      push @{ $form->{parts} },
220 ##        { number      => "",
221 ##          partnumber  => $form->{"totop100_partnumber_$j"},
222 ##          description => $form->{"totop100_description_$j"},
223 ##          unit        => $form->{"totop100_unit_$j"},
224 ##          sellprice   => $form->{"totop100_sellprice_$j"},
225 ##          soldtotal   => $form->{"totop100_soldtotal_$j"},
226 ##        };
227 ##    }    #rof
228 ##  }    #fi
229 #
230 #  $totop100 = "";
231 #
232 #  # set data for next page
233 #  for my $i (1 .. $form->{ndxs_counter}) {
234 #    $partnumber  = $form->{"totop100_partnumber_$i"};
235 #    $description = $form->{"totop100_description_$i"};
236 #    $unit        = $form->{"totop100_unit_$i"};
237 #    $sellprice   = $form->{"totop100_sellprice_$i"};
238 #    $soldtotal   = $form->{"totop100_soldtotal_$i"};
239 #
240 #  push @PARTS, {
241 #    totop100_partnumber  => $form->{"totop100_partnumber_$i"},
242 #    totop100_description => $form->{"totop100_description_$i"},
243 #    totop100_unit        => $form->{"totop100_unit_$i"},
244 #    totop100_sellprice   => $form->{"totop100_sellprice_$i"},
245 #    totop100_soldtotal   => $form->{"totop100_soldtotal_$i"},
246 #  }
247 #
248 ##    $totop100 .= qq|
249 ##<input type=hidden name=totop100_partnumber_$i value=$form->{"totop100_partnumber_$i"}>
250 ##<input type=hidden name=totop100_description_$i value=$form->{"totop100_description_$i"}>
251 ##<input type=hidden name=totop100_unit_$i value=$form->{"totop100_unit_$i"}>
252 ##<input type=hidden name=totop100_sellprice_$i value=$form->{"totop100_sellprice_$i"}>
253 ##<input type=hidden name=totop100_soldtotal_$i value=$form->{"totop100_soldtotal_$i"}>
254 ##    |;
255 #  }    #rof
256 #
257 #  print $form->parse_html_template('ic/choice', +{ HIDDENS => \@HIDDENS, PARTS => \@PARTS });
258 #
259 #  $lxdebug->leave_sub();
260 #}    #end choice
261
262 #sub list {
263 #  $lxdebug->enter_sub();
264 #
265 #  $auth->assert('part_service_assembly_edit');
266 #
267 #  our ($lastndx);
268 #  our ($partnumber, $description, $unit, $sellprice, $soldtotal);
269 #
270 #  my @sortorders = ("", "partnumber", "description", "all");
271 #  my $sortorder = $sortorders[($form->{description} ? 2 : 0) + ($form->{partnumber} ? 1 : 0)];
272 #  IC->get_parts(\%myconfig, \%$form, $sortorder);
273 #
274 #  $form->{title} = $locale->text('Top 100 hinzufuegen');
275 #
276 #  $form->header;
277 #
278 #  print qq|
279 #<body>
280 #  <form method=post action=ic.pl>
281 #    <table width=100%>
282 #     <tr>
283 #      <th class=listtop colspan=6>| . $locale->text('choice part') . qq|</th>
284 #     </tr>
285 #        <tr height="5"></tr>
286 #       <tr class=listheading>
287 #         <th>&nbsp;</th>
288 #         <th class=listheading>| . $locale->text('Part Number') . qq|</th>
289 #         <th class=listheading>| . $locale->text('Part Description') . qq|</th>
290 #         <th class=listheading>| . $locale->text('Unit of measure') . qq|</th>
291 #         <th class=listheading>| . $locale->text('Sell Price') . qq|</th>
292 #         <th class=listheading>| . $locale->text('soldtotal') . qq|</th>
293 #       </tr>|;
294 #
295 #  my $j = 0;
296 #  my $i = $form->{rows};
297 #
298 #  for ($j = 1; $j <= $i; $j++) {
299 #
300 #    print qq|
301 #        <tr class=listrow| . ($j % 2) . qq|>|;
302 #    if ($j == 1) {
303 #      print qq|
304 #           <td><input name=ndx class=radio type=radio value=$j checked></td>|;
305 #    } else {
306 #      print qq|
307 #         <td><input name=ndx class=radio type=radio value=$j></td>|;
308 #    }
309 #    print qq|
310 #         <td><input name="new_partnumber_$j" type=hidden value="$form->{"partnumber_$j"}">$form->{"partnumber_$j"}</td>
311 #         <td><input name="new_description_$j" type=hidden value="$form->{"description_$j"}">$form->{"description_$j"}</td>
312 #         <td><input name="new_unit_$j" type=hidden value="$form->{"unit_$j"}">$form->{"unit_$j"}</td>
313 #         <td><input name="new_sellprice_$j" type=hidden value="$form->{"sellprice_$j"}">$form->{"sellprice_$j"}</td>
314 #         <td><input name="new_soldtotal_$j" type=hidden value="$form->{"soldtotal_$j"}">$form->{"soldtotal_$j"}</td>
315 #        </tr>
316 #
317 #       <input name="new_id_$j" type=hidden value="$form->{"id_$j"}">|;
318 #  }
319 #
320 #  print qq|
321 #
322 #</table>
323 #
324 #<br>
325 #
326 #
327 #<input type=hidden name=itemstatus value="$form->{itemstatus}">
328 #<input type=hidden name=l_linetotal value="$form->{l_linetotal}">
329 #<input type=hidden name=l_partnumber value="$form->{l_partnumber}">
330 #<input type=hidden name=l_description value="$form->{l_description}">
331 #<input type=hidden name=l_onhand value="$form->{l_onhand}">
332 #<input type=hidden name=l_unit value="$form->{l_unit}">
333 #<input type=hidden name=l_sellprice value="$form->{l_sellprice}">
334 #<input type=hidden name=l_linetotalsellprice value="$form->{l_linetotalsellprice}">
335 #<input type=hidden name=sort value="$form->{sort}">
336 #<input type=hidden name=revers value="$form->{revers}">
337 #<input type=hidden name=lastsort value="$form->{lastsort}">
338 #
339 #<input type=hidden name=bom value="$form->{bom}">
340 #<input type=hidden name=titel value="$form->{titel}">
341 #<input type=hidden name=searchitems value="$form->{searchitems}">
342 #
343 #<input type=hidden name=row value=$j>
344 #
345 #<input type=hidden name=nextsub value=item_selected>
346 #
347 #<input name=lastndx type=hidden value=$lastndx>
348 #
349 #<input name=ndxs_counter type=hidden value=$form->{ndxs_counter}>|;
350 #
351 #  my $totop100 = "";
352 #
353 #  if (($form->{ndxs_counter}) > 0) {
354 #    for ($i = 1; ($i < $form->{ndxs_counter} + 1); $i++) {
355 #
356 #      $partnumber  = $form->{"totop100_partnumber_$i"};
357 #      $description = $form->{"totop100_description_$i"};
358 #      $unit        = $form->{"totop100_unit_$i"};
359 #      $sellprice   = $form->{"totop100_sellprice_$i"};
360 #      $soldtotal   = $form->{"totop100_soldtotal_$i"};
361 #
362 #      $totop100 .= qq|
363 #<input type=hidden name=totop100_partnumber_$i value=$form->{"totop100_partnumber_$i"}>
364 #<input type=hidden name=totop100_description_$i value=$form->{"totop100_description_$i"}>
365 #<input type=hidden name=totop100_unit_$i value=$form->{"totop100_unit_$i"}>
366 #<input type=hidden name=totop100_sellprice_$i value=$form->{"totop100_sellprice_$i"}>
367 #<input type=hidden name=totop100_soldtotal_$i value=$form->{"totop100_soldtotal_$i"}>
368 #      |;
369 #    }    #rof
370 #  }    #fi
371 #
372 #  print $totop100;
373 #
374 #  print qq|
375 #<input class=submit type=submit name=action value="|
376 #    . $locale->text('TOP100') . qq|">
377 #
378 #</form>
379 #</body>
380 #</html>
381 #|;
382 #  $lxdebug->leave_sub();
383 #}    #end list()
384
385 sub top100 {
386   $lxdebug->enter_sub();
387
388   $auth->assert('part_service_assembly_edit');
389
390   if ($form->{ndx}) {
391     $form->{ndxs_counter}++;
392
393     if ($form->{ndxs_counter} > 0) {
394
395       my $index = $form->{ndx};
396
397       $form->{"totop100_partnumber_$form->{ndxs_counter}"} = $form->{"new_partnumber_$index"};
398       $form->{"totop100_description_$form->{ndxs_counter}"} = $form->{"new_description_$index"};
399       $form->{"totop100_unit_$form->{ndxs_counter}"} = $form->{"new_unit_$index"};
400       $form->{"totop100_sellprice_$form->{ndxs_counter}"} = $form->{"new_sellprice_$index"};
401       $form->{"totop100_soldtotal_$form->{ndxs_counter}"} = $form->{"new_soldtotal_$index"};
402     }    #fi
403   }    #fi
404   &addtop100();
405   $lxdebug->leave_sub();
406 }    #end top100
407
408 sub addtop100 {
409   $lxdebug->enter_sub();
410
411   $auth->assert('part_service_assembly_edit');
412
413   my ($revers, $lastsort, $callback, $option, $description, $sameitem,
414       $partnumber, $unit, $sellprice, $soldtotal, $totop100, $onhand, $align);
415   my (@column_index, %column_header, %column_data);
416   my ($totalsellprice, $totallastcost, $totallistprice, $subtotalonhand, $subtotalsellprice, $subtotallastcost, $subtotallistprice);
417
418   $form->{top100}      = "top100";
419   $form->{l_soldtotal} = "Y";
420   $form->{soldtotal}   = "soldtotal";
421   $form->{sort}        = "soldtotal";
422   $form->{l_qty}       = "N";
423   $form->{l_linetotal} = "";
424   $form->{revers}      = 1;
425   $form->{number}      = "position";
426   $form->{l_number}    = "Y";
427
428   $totop100 = "";
429
430   $form->{title} = $locale->text('Top 100');
431
432   $revers   = $form->{revers};
433   $lastsort = $form->{lastsort};
434
435   if (($form->{lastsort} eq "") && ($form->{sort} eq undef)) {
436     $form->{revers}   = 0;
437     $form->{lastsort} = "partnumber";
438     $form->{sort}     = "partnumber";
439   }    #fi
440
441   $callback =
442     "$form->{script}?action=top100&searchitems=$form->{searchitems}&itemstatus=$form->{itemstatus}&bom=$form->{bom}&l_linetotal=$form->{l_linetotal}&title="
443     . $form->escape($form->{title}, 1);
444
445   # if we have a serialnumber limit search
446   if ($form->{serialnumber} || $form->{l_serialnumber}) {
447     $form->{l_serialnumber} = "Y";
448     unless (   $form->{bought}
449             || $form->{sold}
450             || $form->{rfq}
451             || $form->{quoted}) {
452       $form->{bought} = $form->{sold} = 1;
453     }
454   }
455   IC->all_parts(\%myconfig, \%$form);
456
457   if ($form->{itemstatus} eq 'active') {
458     $option .= $locale->text('Active') . " : ";
459   }
460   if ($form->{itemstatus} eq 'obsolete') {
461     $option .= $locale->text('Obsolete') . " : ";
462   }
463   if ($form->{itemstatus} eq 'orphaned') {
464     $option .= $locale->text('Orphaned') . " : ";
465   }
466   if ($form->{itemstatus} eq 'onhand') {
467     $option .= $locale->text('On Hand') . " : ";
468     $form->{l_onhand} = "Y";
469   }
470   if ($form->{itemstatus} eq 'short') {
471     $option .= $locale->text('Short') . " : ";
472     $form->{l_onhand} = "Y";
473   }
474   if ($form->{onorder}) {
475     $form->{l_ordnumber} = "Y";
476     $callback .= "&onorder=$form->{onorder}";
477     $option   .= $locale->text('On Order') . " : ";
478   }
479   if ($form->{ordered}) {
480     $form->{l_ordnumber} = "Y";
481     $callback .= "&ordered=$form->{ordered}";
482     $option   .= $locale->text('Ordered') . " : ";
483   }
484   if ($form->{rfq}) {
485     $form->{l_quonumber} = "Y";
486     $callback .= "&rfq=$form->{rfq}";
487     $option   .= $locale->text('RFQ') . " : ";
488   }
489   if ($form->{quoted}) {
490     $form->{l_quonumber} = "Y";
491     $callback .= "&quoted=$form->{quoted}";
492     $option   .= $locale->text('Quoted') . " : ";
493   }
494   if ($form->{bought}) {
495     $form->{l_invnumber} = "Y";
496     $callback .= "&bought=$form->{bought}";
497     $option   .= $locale->text('Bought') . " : ";
498   }
499   if ($form->{sold}) {
500     $form->{l_invnumber} = "Y";
501     $callback .= "&sold=$form->{sold}";
502     $option   .= $locale->text('Sold') . " : ";
503   }
504   if (   $form->{bought}
505       || $form->{sold}
506       || $form->{onorder}
507       || $form->{ordered}
508       || $form->{rfq}
509       || $form->{quoted}) {
510
511     $form->{l_lastcost} = "";
512     $form->{l_name}     = "Y";
513     if ($form->{transdatefrom}) {
514       $callback .= "&transdatefrom=$form->{transdatefrom}";
515       $option   .= "\n<br>"
516         . $locale->text('From')
517         . "&nbsp;"
518         . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
519     }
520     if ($form->{transdateto}) {
521       $callback .= "&transdateto=$form->{transdateto}";
522       $option   .= "\n<br>"
523         . $locale->text('To')
524         . "&nbsp;"
525         . $locale->date(\%myconfig, $form->{transdateto}, 1);
526     }
527   }
528
529   $option .= "<br>";
530
531   if ($form->{partnumber}) {
532     $callback .= "&partnumber=$form->{partnumber}";
533     $option   .= $locale->text('Part Number') . qq| : $form->{partnumber}<br>|;
534   }
535   if ($form->{ean}) {
536     $callback .= "&partnumber=$form->{ean}";
537     $option   .= $locale->text('EAN') . qq| : $form->{ean}<br>|;
538   }
539   if ($form->{partsgroup}) {
540     $callback .= "&partsgroup=$form->{partsgroup}";
541     $option   .= $locale->text('Group') . qq| : $form->{partsgroup}<br>|;
542   }
543   if ($form->{serialnumber}) {
544     $callback .= "&serialnumber=$form->{serialnumber}";
545     $option   .= $locale->text('Serial Number') . qq| : $form->{serialnumber}<br>|;
546   }
547   if ($form->{description}) {
548     $callback   .= "&description=$form->{description}";
549     $description = $form->{description};
550     $description =~ s/\n/<br>/g;
551     $option     .= $locale->text('Part Description') . qq| : $form->{description}<br>|;
552   }
553   if ($form->{make}) {
554     $callback .= "&make=$form->{make}";
555     $option   .= $locale->text('Make') . qq| : $form->{make}<br>|;
556   }
557   if ($form->{model}) {
558     $callback .= "&model=$form->{model}";
559     $option   .= $locale->text('Model') . qq| : $form->{model}<br>|;
560   }
561   if ($form->{drawing}) {
562     $callback .= "&drawing=$form->{drawing}";
563     $option   .= $locale->text('Drawing') . qq| : $form->{drawing}<br>|;
564   }
565   if ($form->{microfiche}) {
566     $callback .= "&microfiche=$form->{microfiche}";
567     $option   .= $locale->text('Microfiche') . qq| : $form->{microfiche}<br>|;
568   }
569   if ($form->{l_soldtotal}) {
570     $callback .= "&soldtotal=$form->{soldtotal}";
571     $option   .= $locale->text('soldtotal') . qq| : $form->{soldtotal}<br>|;
572   }
573
574   my @columns = $form->sort_columns(
575     qw(number partnumber ean description partsgroup bin onhand rop unit listprice linetotallistprice sellprice linetotalsellprice lastcost linetotallastcost priceupdate weight image drawing microfiche invnumber ordnumber quonumber name serialnumber soldtotal)
576   );
577
578   if ($form->{l_linetotal}) {
579     $form->{l_onhand} = "Y";
580     $form->{l_linetotalsellprice} = "Y" if $form->{l_sellprice};
581     if ($form->{l_lastcost}) {
582       $form->{l_linetotallastcost} = "Y";
583       if (($form->{searchitems} eq 'assembly') && !$form->{bom}) {
584         $form->{l_linetotallastcost} = "";
585       }
586     }
587     $form->{l_linetotallistprice} = "Y" if $form->{l_listprice};
588   }
589
590   if ($form->{searchitems} eq 'service') {
591
592     # remove bin, weight and rop from list
593     map { $form->{"l_$_"} = "" } qw(bin weight rop);
594
595     $form->{l_onhand} = "";
596
597     # qty is irrelevant unless bought or sold
598     if (   $form->{bought}
599         || $form->{sold}
600         || $form->{onorder}
601         || $form->{ordered}
602         || $form->{rfq}
603         || $form->{quoted}) {
604       $form->{l_onhand} = "Y";
605     } else {
606       $form->{l_linetotalsellprice} = "";
607       $form->{l_linetotallastcost}  = "";
608     }
609   }
610
611   foreach my $item (@columns) {
612     if ($form->{"l_$item"} eq "Y") {
613       push @column_index, $item;
614
615       # add column to callback
616       $callback .= "&l_$item=Y";
617     }
618   }
619
620   if ($form->{l_subtotal} eq 'Y') {
621     $callback .= "&l_subtotal=Y";
622   }
623
624   $column_header{number} =
625     qq|<th class=listheading nowrap>| . $locale->text('number') . qq|</th>|;
626   $column_header{partnumber} =
627     qq|<th nowrap><a class=listheading href=$callback&sort=partnumber&revers=$form->{revers}&lastsort=$form->{lastsort}>|
628     . $locale->text('Part Number')
629     . qq|</a></th>|;
630   $column_header{description} =
631     qq|<th nowrap><a class=listheading href=$callback&sort=description&revers=$form->{revers}&lastsort=$form->{lastsort}>|
632     . $locale->text('Part Description')
633     . qq|</a></th>|;
634   $column_header{partsgroup} =
635       qq|<th nowrap><a class=listheading href=$callback&sort=partsgroup>|
636     . $locale->text('Group')
637     . qq|</a></th>|;
638   $column_header{bin} =
639       qq|<th><a class=listheading href=$callback&sort=bin>|
640     . $locale->text('Bin')
641     . qq|</a></th>|;
642   $column_header{priceupdate} =
643       qq|<th nowrap><a class=listheading href=$callback&sort=priceupdate>|
644     . $locale->text('Updated')
645     . qq|</a></th>|;
646   $column_header{onhand} =
647     qq|<th nowrap><a  class=listheading href=$callback&sort=onhand&revers=$form->{revers}&lastsort=$form->{lastsort}>|
648     . $locale->text('Qty')
649     . qq|</th>|;
650   $column_header{unit} =
651     qq|<th class=listheading nowrap>| . $locale->text('Unit') . qq|</th>|;
652   $column_header{listprice} =
653       qq|<th class=listheading nowrap>|
654     . $locale->text('List Price')
655     . qq|</th>|;
656   $column_header{lastcost} =
657     qq|<th class=listheading nowrap>| . $locale->text('Last Cost') . qq|</th>|;
658   $column_header{rop} =
659     qq|<th class=listheading nowrap>| . $locale->text('ROP') . qq|</th>|;
660   $column_header{weight} =
661     qq|<th class=listheading nowrap>| . $locale->text('Weight') . qq|</th>|;
662
663   $column_header{invnumber} =
664       qq|<th nowrap><a class=listheading href=$callback&sort=invnumber>|
665     . $locale->text('Invoice Number')
666     . qq|</a></th>|;
667   $column_header{ordnumber} =
668       qq|<th nowrap><a class=listheading href=$callback&sort=ordnumber>|
669     . $locale->text('Order Number')
670     . qq|</a></th>|;
671   $column_header{quonumber} =
672       qq|<th nowrap><a class=listheading href=$callback&sort=quonumber>|
673     . $locale->text('Quotation')
674     . qq|</a></th>|;
675
676   $column_header{name} =
677       qq|<th nowrap><a class=listheading href=$callback&sort=name>|
678     . $locale->text('Name')
679     . qq|</a></th>|;
680
681   $column_header{sellprice} =
682       qq|<th class=listheading nowrap>|
683     . $locale->text('Sell Price')
684     . qq|</th>|;
685   $column_header{linetotalsellprice} =
686     qq|<th class=listheading nowrap>| . $locale->text('Extended') . qq|</th>|;
687   $column_header{linetotallastcost} =
688     qq|<th class=listheading nowrap>| . $locale->text('Extended') . qq|</th>|;
689   $column_header{linetotallistprice} =
690     qq|<th class=listheading nowrap>| . $locale->text('Extended') . qq|</th>|;
691
692   $column_header{image} =
693     qq|<th class=listheading nowrap>| . $locale->text('Image') . qq|</a></th>|;
694   $column_header{drawing} =
695       qq|<th nowrap><a class=listheading href=$callback&sort=drawing>|
696     . $locale->text('Drawing')
697     . qq|</a></th>|;
698   $column_header{microfiche} =
699       qq|<th nowrap><a class=listheading href=$callback&sort=microfiche>|
700     . $locale->text('Microfiche')
701     . qq|</a></th>|;
702
703   $column_header{serialnumber} =
704       qq|<th nowrap><a class=listheading href=$callback&sort=serialnumber>|
705     . $locale->text('Serial Number')
706     . qq|</a></th>|;
707   $column_header{soldtotal} =
708     qq|<th nowrap><a class=listheading href=$callback&sort=soldtotal&revers=$form->{revers}&lastsort=$form->{lastsort}>|
709     . $locale->text('soldtotal')
710     . qq|</a></th>|;
711
712   $form->header;
713   my $colspan = $#column_index + 1;
714
715   print qq|
716 <body>
717
718 <table width=100%>
719   <tr>
720     <th class=listtop colspan=$colspan>$form->{title}</th>
721   </tr>
722   <tr height="5"></tr>
723
724   <tr><td colspan=$colspan>$option</td></tr>
725
726   <tr class=listheading>
727 |;
728
729   map { print "\n$column_header{$_}" } @column_index;
730
731   print qq|
732   </tr>
733   |;
734
735   # add order to callback
736   $form->{callback} = $callback .= "&sort=$form->{sort}";
737
738   # escape callback for href
739   $callback = $form->escape($callback);
740
741   if (@{ $form->{parts} }) {
742     $sameitem = $form->{parts}->[0]->{ $form->{sort} };
743   }
744
745   # insert numbers for top100
746   my $j = 0;
747   foreach my $ref (@{ $form->{parts} }) {
748     $j++;
749     $ref->{number} = $j;
750   }
751
752   # if avaible -> insert choice here
753   if (($form->{ndxs_counter}) > 0) {
754     for (my $i = 1; ($i < $form->{ndxs_counter} + 1); $i++) {
755       $partnumber  = $form->{"totop100_partnumber_$i"};
756       $description = $form->{"totop100_description_$i"};
757       $unit        = $form->{"totop100_unit_$i"};
758       $sellprice   = $form->{"totop100_sellprice_$i"};
759       $soldtotal   = $form->{"totop100_soldtotal_$i"};
760
761       $totop100 .= qq|
762 <input type=hidden name=totop100_partnumber_$i value=$form->{"totop100_partnumber_$i"}>
763 <input type=hidden name=totop100_description_$i value=$form->{"totop100_description_$i"}>
764 <input type=hidden name=totop100_unit_$i value=$form->{"totop100_unit_$i"}>
765 <input type=hidden name=totop100_sellprice_$i value=$form->{"totop100_sellprice_$i"}>
766 <input type=hidden name=totop100_soldtotal_$i value=$form->{"totop100_soldtotal_$i"}>
767       |;
768
769       # insert into list
770       push @{ $form->{parts} },
771         { number      => "",
772           partnumber  => "$partnumber",
773           description => "$description",
774           unit        => "$unit",
775           sellprice   => "$sellprice",
776           soldtotal   => "$soldtotal" };
777     }    #rof
778   }    #fi
779        # build data for columns
780   my $i = 0;
781   foreach my $ref (@{ $form->{parts} }) {
782
783     if ($form->{l_subtotal} eq 'Y' && !$ref->{assemblyitem}) {
784       if ($sameitem ne $ref->{ $form->{sort} }) {
785         &parts_subtotal;
786         $sameitem = $ref->{ $form->{sort} };
787       }
788     }
789
790     $ref->{exchangerate} = 1 unless $ref->{exchangerate};
791     $ref->{sellprice} *= $ref->{exchangerate};
792     $ref->{listprice} *= $ref->{exchangerate};
793     $ref->{lastcost}  *= $ref->{exchangerate};
794
795     # use this for assemblies
796     $onhand = $ref->{onhand};
797
798     $align = "left";
799     if ($ref->{assemblyitem}) {
800       $align = "right";
801       $onhand = 0 if ($form->{sold});
802     }
803
804     $ref->{description} =~ s/\n/<br>/g;
805
806     $column_data{number} =
807         "<td align=right>"
808       . $form->format_amount(\%myconfig, $ref->{number})
809       . "</td>";
810     $column_data{partnumber} =
811       "<td align=$align>$ref->{partnumber}&nbsp;</a></td>";
812     $column_data{description} = "<td>$ref->{description}&nbsp;</td>";
813     $column_data{partsgroup}  = "<td>$ref->{partsgroup}&nbsp;</td>";
814
815     $column_data{onhand} =
816         "<td align=right>"
817       . $form->format_amount(\%myconfig, $ref->{onhand})
818       . "</td>";
819     $column_data{sellprice} =
820         "<td align=right>"
821       . $form->format_amount(\%myconfig, $ref->{sellprice})
822       . "</td>";
823     $column_data{listprice} =
824         "<td align=right>"
825       . $form->format_amount(\%myconfig, $ref->{listprice})
826       . "</td>";
827     $column_data{lastcost} =
828         "<td align=right>"
829       . $form->format_amount(\%myconfig, $ref->{lastcost})
830       . "</td>";
831
832     $column_data{linetotalsellprice} = "<td align=right>"
833       . $form->format_amount(\%myconfig, $ref->{onhand} * $ref->{sellprice}, 2)
834       . "</td>";
835     $column_data{linetotallastcost} = "<td align=right>"
836       . $form->format_amount(\%myconfig, $ref->{onhand} * $ref->{lastcost}, 2)
837       . "</td>";
838     $column_data{linetotallistprice} = "<td align=right>"
839       . $form->format_amount(\%myconfig, $ref->{onhand} * $ref->{listprice}, 2)
840       . "</td>";
841
842     if (!$ref->{assemblyitem}) {
843       $totalsellprice += $onhand * $ref->{sellprice};
844       $totallastcost  += $onhand * $ref->{lastcost};
845       $totallistprice += $onhand * $ref->{listprice};
846
847       $subtotalonhand    += $onhand;
848       $subtotalsellprice += $onhand * $ref->{sellprice};
849       $subtotallastcost  += $onhand * $ref->{lastcost};
850       $subtotallistprice += $onhand * $ref->{listprice};
851     }
852
853     $column_data{rop} =
854       "<td align=right>"
855       . $form->format_amount(\%myconfig, $ref->{rop}) . "</td>";
856     $column_data{weight} =
857         "<td align=right>"
858       . $form->format_amount(\%myconfig, $ref->{weight})
859       . "</td>";
860     $column_data{unit}        = "<td>$ref->{unit}&nbsp;</td>";
861     $column_data{bin}         = "<td>$ref->{bin}&nbsp;</td>";
862     $column_data{priceupdate} = "<td>$ref->{priceupdate}&nbsp;</td>";
863
864     $column_data{invnumber} =
865       ($ref->{module} ne 'oe')
866       ? "<td><a href=$ref->{module}.pl?action=edit&type=invoice&id=$ref->{trans_id}&callback=$callback>$ref->{invnumber}</a></td>"
867       : "<td>$ref->{invnumber}</td>";
868     $column_data{ordnumber} =
869       ($ref->{module} eq 'oe')
870       ? "<td><a href=$ref->{module}.pl?action=edit&type=$ref->{type}&id=$ref->{trans_id}&callback=$callback>$ref->{ordnumber}</a></td>"
871       : "<td>$ref->{ordnumber}</td>";
872     $column_data{quonumber} =
873       ($ref->{module} eq 'oe' && !$ref->{ordnumber})
874       ? "<td><a href=$ref->{module}.pl?action=edit&type=$ref->{type}&id=$ref->{trans_id}&callback=$callback>$ref->{quonumber}</a></td>"
875       : "<td>$ref->{quonumber}</td>";
876
877     $column_data{name} = "<td>$ref->{name}</td>";
878
879     $column_data{image} =
880       ($ref->{image})
881       ? "<td><a href=$ref->{image}><img src=$ref->{image} height=32 border=0></a></td>"
882       : "<td>&nbsp;</td>";
883     $column_data{drawing} =
884       ($ref->{drawing})
885       ? "<td><a href=$ref->{drawing}>$ref->{drawing}</a></td>"
886       : "<td>&nbsp;</td>";
887     $column_data{microfiche} =
888       ($ref->{microfiche})
889       ? "<td><a href=$ref->{microfiche}>$ref->{microfiche}</a></td>"
890       : "<td>&nbsp;</td>";
891
892     $column_data{serialnumber} = "<td>$ref->{serialnumber}</td>";
893
894     $column_data{soldtotal} = "<td  align=right>$ref->{soldtotal}</td>";
895
896     $i++;
897     $i %= 2;
898     print "<tr class=listrow$i>";
899
900     map { print "\n$column_data{$_}" } @column_index;
901
902     print qq|
903     </tr>
904 |;
905   }
906
907   if ($form->{l_subtotal} eq 'Y') {
908     &parts_subtotal;
909   }    #fi
910
911   if ($form->{"l_linetotal"}) {
912     map { $column_data{$_} = "<td>&nbsp;</td>" } @column_index;
913     $column_data{linetotalsellprice} =
914         "<th class=listtotal align=right>"
915       . $form->format_amount(\%myconfig, $totalsellprice, 2)
916       . "</th>";
917     $column_data{linetotallastcost} =
918         "<th class=listtotal align=right>"
919       . $form->format_amount(\%myconfig, $totallastcost, 2)
920       . "</th>";
921     $column_data{linetotallistprice} =
922         "<th class=listtotal align=right>"
923       . $form->format_amount(\%myconfig, $totallistprice, 2)
924       . "</th>";
925
926     print "<tr class=listtotal>";
927
928     map { print "\n$column_data{$_}" } @column_index;
929
930     print qq|</tr>
931     |;
932   }
933
934   print qq|
935   <tr><td colspan=$colspan><hr size=3 noshade></td></tr>
936 </table>
937
938 |;
939
940   print qq|
941
942 <br>
943
944 <form method=post action=$form->{script}>
945
946 <input type=hidden name=itemstatus value="$form->{itemstatus}">
947 <input type=hidden name=l_linetotal value="$form->{l_linetotal}">
948 <input type=hidden name=l_partnumber value="$form->{l_partnumber}">
949 <input type=hidden name=l_description value="$form->{l_description}">
950 <input type=hidden name=l_onhand value="$form->{l_onhand}">
951 <input type=hidden name=l_unit value="$form->{l_unit}">
952 <input type=hidden name=l_sellprice value="$form->{l_sellprice}">
953 <input type=hidden name=l_linetotalsellprice value="$form->{l_linetotalsellprice}">
954 <input type=hidden name=sort value="$form->{sort}">
955 <input type=hidden name=revers value="$form->{revers}">
956 <input type=hidden name=lastsort value="$form->{lastsort}">
957 <input type=hidden name=parts value="$form->{parts}">
958
959 <input type=hidden name=bom value="$form->{bom}">
960 <input type=hidden name=titel value="$form->{titel}">
961 <input type=hidden name=searchitems value="$form->{searchitems}">|;
962
963   print $totop100;
964
965   print qq|
966 <!--    <input type=hidden name=ndxs_counter value="$form->{ndxs_counter}">-->
967
968     <input class=submit type=submit name=action value="|
969     . $locale->text('choice') . qq|">
970
971   </form>
972
973 </body>
974 </html>
975 |;
976
977   $lxdebug->leave_sub();
978 }    # end addtop100
979
980 #
981 # Report for Wares.
982 # Warning, deep magic ahead.
983 # This function parses the requested details, sanity checks them, and converts them into a format thats usable for IC->all_parts
984 #
985 # flags coming from the form:
986 # hardcoded:
987 #  searchitems=part revers=0 lastsort=''
988 #
989 # filter:
990 # partnumber ean description partsgroup serialnumber make model drawing microfiche
991 # transdatefrom transdateto
992 #
993 # radio:
994 #  itemstatus = active | onhand | short | obsolete | orphaned
995 #  action     = continue | top100
996 #
997 # checkboxes:
998 #  bought sold onorder ordered rfq quoted
999 #  l_partnumber l_description l_serialnumber l_unit l_listprice l_sellprice l_lastcost
1000 #  l_linetotal l_priceupdate l_bin l_rop l_weight l_image l_drawing l_microfiche
1001 #  l_partsgroup l_subtotal l_soldtotal l_deliverydate
1002 #
1003 # hiddens:
1004 #  nextsub revers lastsort sort ndxs_counter
1005 #
1006 sub generate_report {
1007   $lxdebug->enter_sub();
1008
1009   $auth->assert('part_service_assembly_edit');
1010
1011   my ($revers, $lastsort, $description);
1012
1013   $form->{title} = (ucfirst $form->{searchitems}) . "s";
1014   $form->{title} =~ s/ys$/ies/;
1015   $form->{title} = $locale->text($form->{title});
1016
1017   my $revers     = $form->{revers};
1018   my $lastsort   = $form->{lastsort};
1019
1020   # sorting and direction of sorting
1021   # ToDO: change this to the simpler field+direction method
1022   if (($form->{lastsort} eq "") && ($form->{sort} eq undef)) {
1023     $form->{revers}   = 0;
1024     $form->{lastsort} = "partnumber";
1025     $form->{sort}     = "partnumber";
1026   } else {
1027     if ($form->{lastsort} eq $form->{sort}) {
1028       $form->{revers} = 1 - $form->{revers};
1029     } else {
1030       $form->{revers} = 0;
1031       $form->{lastsort} = $form->{sort};
1032     }    #fi
1033   }    #fi
1034
1035   # special case if we have a serialnumber limit search
1036   # serialnumbers are only given in invoices and orders,
1037   # so they can only pop up in bought, sold, rfq, and quoted stuff
1038   $form->{no_sn_joins} = 'Y' if (   !$form->{bought} && !$form->{sold}
1039                                  && !$form->{rfq}    && !$form->{quoted}
1040                                  && ($form->{l_serialnumber} || $form->{serialnumber}));
1041
1042   # special case for any checkbox of bought | sold | onorder | ordered | rfq | quoted.
1043   # if any of these are ticked the behavior changes slightly for lastcost
1044   # since all those are aggregation checks for the legder tables this is an internal switch
1045   # refered to as ledgerchecks
1046   $form->{ledgerchecks} = 'Y' if (   $form->{bought} || $form->{sold} || $form->{onorder}
1047                                   || $form->{ordered} || $form->{rfq} || $form->{quoted});
1048
1049   # if something should be activated if something else is active, enter it here
1050   my %dependencies = (
1051     onhand       => [ qw(l_onhand) ],
1052     short        => [ qw(l_onhand) ],
1053     onorder      => [ qw(l_ordnumber) ],
1054     ordered      => [ qw(l_ordnumber) ],
1055     rfq          => [ qw(l_quonumber) ],
1056     quoted       => [ qw(l_quonumber) ],
1057     bought       => [ qw(l_invnumber) ],
1058     sold         => [ qw(l_invnumber) ],
1059     ledgerchecks => [ qw(l_name) ],
1060     serialnumber => [ qw(l_serialnumber) ],
1061     no_sn_joins  => [ qw(bought sold) ],
1062   );
1063
1064   # these strings get displayed at the top of the results to indicate the user which switches were used
1065   my %optiontexts = (
1066     active        => $locale->text('Active'),
1067     obsolete      => $locale->text('Obsolete'),
1068     orphaned      => $locale->text('Orphaned'),
1069     onhand        => $locale->text('On Hand'),
1070     short         => $locale->text('Short'),
1071     onorder       => $locale->text('On Order'),
1072     ordered       => $locale->text('Ordered'),
1073     rfq           => $locale->text('RFQ'),
1074     quoted        => $locale->text('Quoted'),
1075     bought        => $locale->text('Bought'),
1076     sold          => $locale->text('Sold'),
1077     transdatefrom => $locale->text('From')       . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1),
1078     transdateto   => $locale->text('To (time)')  . " " . $locale->date(\%myconfig, $form->{transdateto}, 1),
1079     partnumber    => $locale->text('Part Number')      . ": '$form->{partnumber}'",
1080     partsgroup    => $locale->text('Group')            . ": '$form->{partsgroup}'",
1081     serialnumber  => $locale->text('Serial Number')    . ": '$form->{serialnumber}'",
1082     description   => $locale->text('Part Description') . ": '$form->{description}'",
1083     make          => $locale->text('Make')             . ": '$form->{make}'",
1084     model         => $locale->text('Model')            . ": '$form->{model}'",
1085     drawing       => $locale->text('Drawing')          . ": '$form->{drawing}'",
1086     microfiche    => $locale->text('Microfiche')       . ": '$form->{microfiche}'",
1087     l_soldtotal   => $locale->text('soldtotal'),
1088   );
1089
1090   my @itemstatus_keys = qw(active obsolete orphaned onhand short);
1091   my @callback_keys   = qw(onorder ordered rfq quoted bought sold partnumber partsgroup serialnumber description make model
1092                            drawing microfiche l_soldtotal l_deliverydate transdatefrom transdateto ean);
1093
1094   # calculate dependencies
1095   for (@itemstatus_keys, @callback_keys) {
1096     next if ($form->{itemstatus} ne $_ && !$form->{$_});
1097     map { $form->{$_} = 'Y' } @{ $dependencies{$_} } if $dependencies{$_};
1098   }
1099
1100   # generate callback and optionstrings
1101   my @options;
1102   for my  $key (@itemstatus_keys, @callback_keys) {
1103     next if ($form->{itemstatus} ne $key && !$form->{$key});
1104     push @options, $optiontexts{$key};
1105   }
1106
1107   # special case for lastcost
1108   $form->{l_lastcost} = "" if $form->{ledgerchecks};
1109
1110   if ($form->{description}) {
1111     $description = $form->{description};
1112     $description =~ s/\n/<br>/g;
1113   }
1114
1115   if ($form->{l_linetotal}) {
1116     $form->{l_onhand} = "Y";
1117     $form->{l_linetotalsellprice} = "Y" if $form->{l_sellprice};
1118     if ($form->{l_lastcost}) {
1119       $form->{l_linetotallastcost} = "Y";
1120       if (($form->{searchitems} eq 'assembly') && !$form->{bom}) {
1121         $form->{l_linetotallastcost} = "";
1122       }
1123     }
1124     $form->{l_linetotallistprice} = "Y" if $form->{l_listprice};
1125   }
1126
1127   if ($form->{searchitems} eq 'service') {
1128
1129     # remove bin, weight and rop from list
1130     map { $form->{"l_$_"} = "" } qw(bin weight rop);
1131
1132     $form->{l_onhand} = "";
1133
1134     # qty is irrelevant unless bought or sold
1135     if (   $form->{bought}
1136         || $form->{sold}
1137         || $form->{onorder}
1138         || $form->{ordered}
1139         || $form->{rfq}
1140         || $form->{quoted}) {
1141       $form->{l_onhand} = "Y";
1142     } else {
1143       $form->{l_linetotalsellprice} = "";
1144       $form->{l_linetotallastcost}  = "";
1145     }
1146   }
1147
1148   IC->all_parts(\%myconfig, \%$form);
1149
1150   my @columns =
1151     qw(partnumber description partsgroup bin onhand rop unit listprice linetotallistprice sellprice linetotalsellprice lastcost linetotallastcost
1152        priceupdate weight image drawing microfiche invnumber ordnumber quonumber name serialnumber soldtotal deliverydate);
1153
1154   my %column_defs = (
1155     'bin'                => { 'text' => $locale->text('Bin'), },
1156     'deliverydate'       => { 'text' => $locale->text('deliverydate'), },
1157     'description'        => { 'text' => $locale->text('Part Description'), },
1158     'drawing'            => { 'text' => $locale->text('Drawing'), },
1159     'image'              => { 'text' => $locale->text('Image'), },
1160     'invnumber'          => { 'text' => $locale->text('Invoice Number'), },
1161     'lastcost'           => { 'text' => $locale->text('Last Cost'), },
1162     'linetotallastcost'  => { 'text' => $locale->text('Extended'), },
1163     'linetotallistprice' => { 'text' => $locale->text('Extended'), },
1164     'linetotalsellprice' => { 'text' => $locale->text('Extended'), },
1165     'listprice'          => { 'text' => $locale->text('List Price'), },
1166     'microfiche'         => { 'text' => $locale->text('Microfiche'), },
1167     'name'               => { 'text' => $locale->text('Name'), },
1168     'onhand'             => { 'text' => $locale->text('Qty'), },
1169     'ordnumber'          => { 'text' => $locale->text('Order Number'), },
1170     'partnumber'         => { 'text' => $locale->text('Part Number'), },
1171     'partsgroup'         => { 'text' => $locale->text('Group'), },
1172     'priceupdate'        => { 'text' => $locale->text('Updated'), },
1173     'quonumber'          => { 'text' => $locale->text('Quotation'), },
1174     'rop'                => { 'text' => $locale->text('ROP'), },
1175     'sellprice'          => { 'text' => $locale->text('Sell Price'), },
1176     'serialnumber'       => { 'text' => $locale->text('Serial Number'), },
1177     'soldtotal'          => { 'text' => $locale->text('soldtotal'), },
1178     'unit'               => { 'text' => $locale->text('Unit'), },
1179     'weight'             => { 'text' => $locale->text('Weight'), },
1180   );
1181
1182   map { $column_defs{$_}->{visible} = $form->{"l_$_"} ? 1 : 0 } @columns;
1183   map { $column_defs{$_}->{align}   = 'right' } qw(onhand sellprice listprice lastcost linetotalsellprice linetotallastcost linetotallistprice rop weight soldtotal);
1184
1185   my @hidden_variables = (qw(l_subtotal l_linetotal searchitems itemstatus bom), @itemstatus_keys, @callback_keys, map { "l_$_" } @columns);
1186   my $callback         = build_std_url('action=generate_report', grep { $form->{$_} } @hidden_variables);
1187
1188   my @sort_full        = qw(partnumber description onhand soldtotal deliverydate);
1189   my @sort_no_revers   = qw(partsgroup bin priceupdate invnumber ordnumber quonumber name image drawing serialnumber);
1190
1191   foreach my $col (@sort_full) {
1192     $column_defs{$col}->{link} = join '&', $callback, "sort=$col", map { "$_=" . E($form->{$_}) } qw(revers lastsort);
1193   }
1194   map { $column_defs{$_}->{link} = "${callback}&sort=$_" } @sort_no_revers;
1195
1196   # add order to callback
1197   $form->{callback} = join '&', ($callback, map { "${_}=" . E($form->{$_}) } qw(sort revers));
1198
1199   my $report = SL::ReportGenerator->new(\%myconfig, $form);
1200
1201   my %attachment_basenames = (
1202     'part'     => $locale->text('part_list'),
1203     'service'  => $locale->text('service_list'),
1204     'assembly' => $locale->text('assembly_list'),
1205   );
1206
1207   $report->set_options('top_info_text'         => $locale->text('Options') . ': ' . join(', ', grep $_, @options),
1208                        'raw_bottom_info_text'  => $form->parse_html_template('ic/generate_report_bottom'),
1209                        'output_format'         => 'HTML',
1210                        'title'                 => $form->{title},
1211                        'attachment_basename'   => $attachment_basenames{$form->{searchitems}} . strftime('_%Y%m%d', localtime time),
1212   );
1213   $report->set_options_from_form();
1214
1215   $report->set_columns(%column_defs);
1216   $report->set_column_order(@columns);
1217
1218   $report->set_export_options('generate_report', @hidden_variables, qw(sort revers));
1219
1220   $report->set_sort_indicator($form->{sort}, $form->{revers} ? 0 : 1);
1221
1222   my @subtotal_columns = qw(sellprice listprice lastcost);
1223   my %subtotals = map { $_ => 0 } ('onhand', @subtotal_columns);
1224   my %totals    = map { $_ => 0 } @subtotal_columns;
1225   my $idx       = 0;
1226   my $same_item = $form->{parts}[0]{ $form->{sort} } if (scalar @{ $form->{parts} });
1227
1228   my $defaults  = AM->get_defaults();
1229
1230   # postprocess parts
1231   foreach my $ref (@{ $form->{parts} }) {
1232
1233     # fresh row, for inserting later
1234     my $row = { map { $_ => { 'data' => $ref->{$_} } } @columns };
1235
1236     $ref->{exchangerate} ||= 1;
1237     $ref->{price_factor} ||= 1;
1238     $ref->{sellprice}     *= $ref->{exchangerate} / $ref->{price_factor};
1239     $ref->{listprice}     *= $ref->{exchangerate} / $ref->{price_factor};
1240     $ref->{lastcost}      *= $ref->{exchangerate} / $ref->{price_factor};
1241
1242     # use this for assemblies
1243     my $onhand = $ref->{onhand};
1244
1245     if ($ref->{assemblyitem}) {
1246       $row->{partnumber}{align}   = 'right';
1247       $row->{onhand}{data}        = 0;
1248       $onhand                     = 0 if ($form->{sold});
1249     }
1250
1251     my $edit_link               = build_std_url('action=edit', 'id=' . E($ref->{id}), 'callback');
1252     $row->{partnumber}->{link}  = $edit_link;
1253     $row->{description}->{link} = $edit_link;
1254
1255     foreach (qw(sellprice listprice lastcost)) {
1256       $row->{$_}{data}            = $form->format_amount(\%myconfig, $ref->{$_}, -2);
1257       $row->{"linetotal$_"}{data} = $form->format_amount(\%myconfig, $ref->{onhand} * $ref->{$_}, 2);
1258     }
1259
1260     map { $row->{$_}{data} = $form->format_amount(\%myconfig, $ref->{$_}); } qw(onhand rop weight soldtotal);
1261
1262     $row->{weight}->{data} .= ' ' . $defaults->{weightunit};
1263
1264     if (!$ref->{assemblyitem}) {
1265       foreach my $col (@subtotal_columns) {
1266         $totals{$col}    += $onhand * $ref->{$col};
1267         $subtotals{$col} += $onhand * $ref->{$col};
1268       }
1269
1270       $subtotals{onhand} += $onhand;
1271     }
1272
1273     # set module stuff
1274     if ($ref->{module} eq 'oe') {
1275       my $edit_oe_link = build_std_url("script=oe.pl", 'action=edit', 'type=' . E($ref->{customer_id} ne '' ? 'sales_order' : 'purchase_order'), 'id=' . E($ref->{trans_id}), 'callback');
1276       $row->{ordnumber}{link} = $edit_oe_link;
1277       $row->{quonumber}{link} = $edit_oe_link if (!$ref->{ordnumber});
1278
1279     } else {
1280       $row->{invnumber}{link} = build_std_url("script=$ref->{module}.pl", 'action=edit', 'type=invoice', 'id=' . E($ref->{trans_id}), 'callback');
1281     }
1282
1283     # set properties of images
1284     if ($ref->{image} && (lc $report->{options}->{output_format} eq 'html')) {
1285       $row->{image}{data}     = '';
1286       $row->{image}{raw_data} = '<a href="' . H($ref->{image}) . '"><img src="' . H($ref->{image}) . '" height="32" border="0"></a>';
1287     }
1288     map { $row->{$_}{link} = $ref->{$_} } qw(drawing microfiche);
1289
1290     $report->add_data($row);
1291
1292     my $next_ref = $form->{parts}[$idx + 1];
1293
1294     # insert subtotal rows
1295     if (($form->{l_subtotal} eq 'Y') &&
1296         (!$next_ref ||
1297          (!$next_ref->{assemblyitem} && ($same_item ne $next_ref->{ $form->{sort} })))) {
1298       my $row = { map { $_ => { 'class' => 'listsubtotal', } } @columns };
1299
1300       if (($form->{searchitems} ne 'assembly') || !$form->{bom}) {
1301         $row->{onhand}->{data} = $form->format_amount(\%myconfig, $subtotals{onhand});
1302       }
1303
1304       map { $row->{"linetotal$_"}->{data} = $form->format_amount(\%myconfig, $subtotals{$_}, 2) } @subtotal_columns;
1305       map { $subtotals{$_} = 0 } ('onhand', @subtotal_columns);
1306
1307       $report->add_data($row);
1308
1309       $same_item = $next_ref->{ $form->{sort} };
1310     }
1311
1312     $idx++;
1313   }
1314
1315   if ($form->{"l_linetotal"}) {
1316     my $row = { map { $_ => { 'class' => 'listtotal', } } @columns };
1317
1318     map { $row->{"linetotal$_"}->{data} = $form->format_amount(\%myconfig, $totals{$_}, 2) } @subtotal_columns;
1319
1320     $report->add_separator();
1321     $report->add_data($row);
1322   }
1323
1324   $report->generate_with_headers();
1325
1326   $lxdebug->leave_sub();
1327 }    #end generate_report
1328
1329 sub parts_subtotal {
1330   $lxdebug->enter_sub();
1331
1332   $auth->assert('part_service_assembly_edit');
1333
1334   # imports
1335   our (%column_data, @column_index);
1336   our ($subtotalonhand, $totalsellprice, $totallastcost, $totallistprice, $subtotalsellprice, $subtotallastcost, $subtotallistprice);
1337
1338   map { $column_data{$_} = "<td>&nbsp;</td>" } @column_index;
1339   $subtotalonhand = 0 if ($form->{searchitems} eq 'assembly' && $form->{bom});
1340
1341   $column_data{onhand} =
1342       "<th class=listsubtotal align=right>"
1343     . $form->format_amount(\%myconfig, $subtotalonhand)
1344     . "</th>";
1345
1346   $column_data{linetotalsellprice} =
1347       "<th class=listsubtotal align=right>"
1348     . $form->format_amount(\%myconfig, $subtotalsellprice, 2)
1349     . "</th>";
1350   $column_data{linetotallistprice} =
1351       "<th class=listsubtotal align=right>"
1352     . $form->format_amount(\%myconfig, $subtotallistprice, 2)
1353     . "</th>";
1354   $column_data{linetotallastcost} =
1355       "<th class=listsubtotal align=right>"
1356     . $form->format_amount(\%myconfig, $subtotallastcost, 2)
1357     . "</th>";
1358
1359   $subtotalonhand    = 0;
1360   $subtotalsellprice = 0;
1361   $subtotallistprice = 0;
1362   $subtotallastcost  = 0;
1363
1364   print "<tr class=listsubtotal>";
1365
1366   map { print "\n$column_data{$_}" } @column_index;
1367
1368   print qq|
1369   </tr>
1370 |;
1371
1372   $lxdebug->leave_sub();
1373 }
1374
1375 sub edit {
1376   $lxdebug->enter_sub();
1377
1378   $auth->assert('part_service_assembly_edit');
1379
1380   # show history button
1381   $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
1382   #/show hhistory button
1383   IC->get_part(\%myconfig, \%$form);
1384
1385   $form->{"original_partnumber"} = $form->{"partnumber"};
1386
1387   $form->{title} = $locale->text('Edit ' . ucfirst $form->{item});
1388
1389   &link_part;
1390   &display_form;
1391
1392   $lxdebug->leave_sub();
1393 }
1394
1395 sub link_part {
1396   $lxdebug->enter_sub();
1397
1398   $auth->assert('part_service_assembly_edit');
1399
1400   IC->create_links("IC", \%myconfig, \%$form);
1401
1402   # currencies
1403   map({ $form->{selectcurrency} .= "<option>$_\n" }
1404       split(/:/, $form->{currencies}));
1405
1406   # parts and assemblies have the same links
1407   my $item = $form->{item};
1408   if ($form->{item} eq 'assembly') {
1409     $item = 'part';
1410   }
1411
1412   # build the popup menus
1413   $form->{taxaccounts} = "";
1414   foreach my $key (keys %{ $form->{IC_links} }) {
1415     foreach my $ref (@{ $form->{IC_links}{$key} }) {
1416
1417       # if this is a tax field
1418       if ($key =~ /IC_tax/) {
1419         if ($key =~ /\Q$item\E/) {
1420           $form->{taxaccounts} .= "$ref->{accno} ";
1421           $form->{"IC_tax_$ref->{accno}_description"} =
1422             "$ref->{accno}--$ref->{description}";
1423
1424           if ($form->{id}) {
1425             if ($form->{amount}{ $ref->{accno} }) {
1426               $form->{"IC_tax_$ref->{accno}"} = "checked";
1427             }
1428           } else {
1429             $form->{"IC_tax_$ref->{accno}"} = "checked";
1430           }
1431         }
1432       } else {
1433
1434         $form->{"select$key"} .=
1435           "<option $ref->{selected}>$ref->{accno}--$ref->{description}\n";
1436         if ($form->{amount}{$key} eq $ref->{accno}) {
1437           $form->{$key} = "$ref->{accno}--$ref->{description}";
1438         }
1439
1440       }
1441     }
1442   }
1443   chop $form->{taxaccounts};
1444
1445   if (($form->{item} eq "part") || ($form->{item} eq "assembly")) {
1446     $form->{selectIC_income}  = $form->{selectIC_sale};
1447     $form->{selectIC_expense} = $form->{selectIC_cogs};
1448     $form->{IC_income}        = $form->{IC_sale};
1449     $form->{IC_expense}       = $form->{IC_cogs};
1450   }
1451
1452   delete $form->{IC_links};
1453   delete $form->{amount};
1454
1455   $form->get_partsgroup(\%myconfig, { all => 1 });
1456
1457   $form->{partsgroup} = "$form->{partsgroup}--$form->{partsgroup_id}";
1458
1459   if (@{ $form->{all_partsgroup} }) {
1460     $form->{selectpartsgroup} = qq|<option>\n|;
1461     map { $form->{selectpartsgroup} .= qq|<option value="$_->{partsgroup}--$_->{id}">$_->{partsgroup}\n| } @{ $form->{all_partsgroup} };
1462   }
1463
1464   if ($form->{item} eq 'assembly') {
1465
1466     foreach my $i (1 .. $form->{assembly_rows}) {
1467       if ($form->{"partsgroup_id_$i"}) {
1468         $form->{"partsgroup_$i"} =
1469           qq|$form->{"partsgroup_$i"}--$form->{"partsgroup_id_$i"}|;
1470       }
1471     }
1472     $form->get_partsgroup(\%myconfig);
1473
1474     if (@{ $form->{all_partsgroup} }) {
1475       $form->{selectassemblypartsgroup} = qq|<option>\n|;
1476
1477       map {
1478         $form->{selectassemblypartsgroup} .=
1479           qq|<option value="$_->{partsgroup}--$_->{id}">$_->{partsgroup}\n|
1480       } @{ $form->{all_partsgroup} };
1481     }
1482   }
1483   $lxdebug->leave_sub();
1484 }
1485
1486 sub form_header {
1487   $lxdebug->enter_sub();
1488
1489   $auth->assert('part_service_assembly_edit');
1490
1491   $form->{eur}              = $eur; # config dumps into namespace - yuck
1492   $form->{pg_keys}          = sub { "$_[0]->{partsgroup}--$_[0]->{id}" };
1493   $form->{description_area} = ($form->{rows} = $form->numtextrows($form->{description}, 40)) > 1;
1494   $form->{notes_rows}       =  max 4, $form->numtextrows($form->{notes}, 40), $form->numtextrows($form->{formel}, 40);
1495
1496   map { $form->{"is_$_"}  = ($form->{item} eq $_) } qw(part service assembly);
1497   map { $form->{$_}       =~ s/"/&quot;/g;        } qw(unit);
1498
1499   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS',
1500                    'partsgroup'    => 'all_partsgroup',
1501                    'vendors'       => 'ALL_VENDORS',);
1502
1503
1504   IC->retrieve_buchungsgruppen(\%myconfig, $form);
1505   @{ $form->{BUCHUNGSGRUPPEN} } = grep { $_->{id} eq $form->{buchungsgruppen_id} || ($form->{id} && $form->{orphaned}) || !$form->{id} } @{ $form->{BUCHUNGSGRUPPEN} };
1506
1507   # use JavaScript Calendar or not (yes!)
1508   $form->{jsscript} = 1;
1509
1510   $units = AM->retrieve_units(\%myconfig, $form);
1511   $form->{ALL_UNITS} = [ map +{ name => $_ }, sort { $units->{$a}{sortkey} <=> $units->{$b}{sortkey} } keys %$units ];
1512
1513   $form->{defaults} = AM->get_defaults();
1514
1515   $form->{fokus} = "ic.partnumber";
1516
1517   $form->header;
1518   #print $form->parse_html_template('ic/form_header', { ALL_PRICE_FACTORS => $form->{ALL_PRICE_FACTORS},
1519   #                                                     ALL_UNITS         => $form->{ALL_UNITS},
1520   #                                                     BUCHUNGSGRUPPEN   => $form->{BUCHUNGSGRUPPEN},
1521   #                                                     payment_terms     => $form->{payment_terms},
1522   #                                                     all_partsgroup    => $form->{all_partsgroup}});
1523   print $form->parse_html_template('ic/form_header');
1524   $lxdebug->leave_sub();
1525 }
1526
1527 sub form_footer {
1528   $lxdebug->enter_sub();
1529
1530   $auth->assert('part_service_assembly_edit');
1531
1532   print $form->parse_html_template('ic/form_footer');
1533
1534   $lxdebug->leave_sub();
1535 }
1536
1537 sub makemodel_row {
1538   $lxdebug->enter_sub();
1539   my ($numrows) = @_;
1540
1541   my @mm_data = grep { any { $_ ne '' } @$_{qw(make model)} } map +{ make => $form->{"make_$_"}, model => $form->{"model_$_"} }, 1 .. $numrows;
1542   delete @{$form}{grep { m/^make_\d+/ || m/^model_\d+/ } keys %{ $form }};
1543   print $form->parse_html_template('ic/makemodel', { MM_DATA => [ @mm_data, {} ], mm_rows => scalar @mm_data + 1 });
1544
1545   $lxdebug->leave_sub();
1546 }
1547
1548 sub assembly_row {
1549   $lxdebug->enter_sub();
1550   my ($numrows) = @_;
1551   my (@column_index);
1552   my ($nochange, $callback, $previousform, $linetotal, $line_purchase_price, $href);
1553
1554   our ($deliverydate); # ToDO: cjeck if this indeed comes from global context
1555
1556   @column_index = qw(runningnumber qty unit bom partnumber description partsgroup lastcost total);
1557
1558   if ($form->{previousform}) {
1559     $nochange     = 1;
1560     @column_index = qw(qty unit bom partnumber description partsgroup total);
1561   } else {
1562
1563     # change callback
1564     $form->{old_callback} = $form->{callback};
1565     $callback             = $form->{callback};
1566     $form->{callback}     = "$form->{script}?action=display_form";
1567
1568     # delete action
1569     map { delete $form->{$_} } qw(action header);
1570
1571     # save form variables in a previousform variable
1572     $previousform = $form->escape($form->escape(join '&', map {
1573       sprintf "%s=%s", Q($_), /^listprice|lastcost|sellprice$/ ? $form->format_amount(\%myconfig, $form->{$key}) : $form->{$key}
1574     } grep { ref $form->{$_} eq '' && $form->{$_} } grep { !/^select/ } sort keys %$form ));
1575
1576     $form->{callback} = $callback;
1577     $form->{assemblytotal} = 0;
1578     $form->{assembly_purchase_price_total} = 0;
1579     $form->{weight}        = 0;
1580   }
1581
1582   my %header = (
1583    runningnumber => { text =>  $locale->text('No.'),              nowrap => 1, width => '5%'  },
1584    qty           => { text =>  $locale->text('Qty'),              nowrap => 1, width => '10%' },
1585    unit          => { text =>  $locale->text('Unit'),             nowrap => 1, width => '5%'  },
1586    partnumber    => { text =>  $locale->text('Part Number'),      nowrap => 1, width => '20%' },
1587    description   => { text =>  $locale->text('Part Description'), nowrap => 1, width => '50%' },
1588    lastcost      => { text =>  $locale->text('Purchase Prices'),  nowrap => 1, width => '50%' },
1589    total         => { text =>  $locale->text('Sale Prices'),      nowrap => 1,                },
1590    bom           => { text =>  $locale->text('BOM'),                                          },
1591    partsgroup    => { text =>  $locale->text('Group'),                                        },
1592   );
1593
1594   my @ROWS;
1595
1596   for my $i (1 .. $numrows) {
1597     my (%row, @row_hiddens);
1598
1599     $form->{"partnumber_$i"} =~ s/\"/&quot;/g;
1600
1601     $linetotal           = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / ($form->{"price_factor_$i"} || 1), 4);
1602     $line_purchase_price = $form->round_amount($form->{"lastcost_$i"} *  $form->{"qty_$i"} / ($form->{"price_factor_$i"} || 1), 4);
1603     $form->{assemblytotal}                  += $linetotal;
1604     $form->{assembly_purchase_price_total}  += $line_purchase_price;
1605     $form->{"qty_$i"}    = $form->format_amount(\%myconfig, $form->{"qty_$i"});
1606     $linetotal           = $form->format_amount(\%myconfig, $linetotal, 2);
1607     $line_purchase_price = $form->format_amount(\%myconfig, $line_purchase_price, 2);
1608     $href                = qq|$form->{script}?action=edit&id=$form->{"id_$i"}&rowcount=$i&previousform=$previousform|;
1609     map { $row{$_}{data} = "" } qw(qty unit partnumber description bom partsgroup runningnumber);
1610
1611     # last row
1612     if (($i >= 1) && ($i == $numrows)) {
1613       if (!$form->{previousform}) {
1614         $row{partnumber}{data}  = qq|<input name="partnumber_$i" size=15 value="$form->{"partnumber_$i"}">|;
1615         $row{qty}{data}         = qq|<input name="qty_$i" size=5 value="$form->{"qty_$i"}">|;
1616         $row{description}{data} = qq|<input name="description_$i" size=40 value="$form->{"description_$i"}">|;
1617         $row{partsgroup}{data}  = qq|<input name="partsgroup_$i" size=10 value="$form->{"partsgroup_$i"}">|;
1618       }
1619     # other rows
1620     } else {
1621       if ($form->{previousform}) {
1622         push @row_hiddens,          qw(qty bom);
1623         $row{partnumber}{data}    = $form->{"partnumber_$i"};
1624         $row{qty}{data}           = $form->{"qty_$i"};
1625         $row{bom}{data}           = $form->{"bom_$i"} ? "x" : "&nbsp;";
1626         $row{qty}{align}          = 'right';
1627       } else {
1628         $row{partnumber}{data}    = qq|<a href=$href>$form->{"partnumber_$i"}</a>|;
1629         $row{qty}{data}           = qq|<input name="qty_$i" size=5 value="$form->{"qty_$i"}">|;
1630         $row{runningnumber}{data} = qq|<input name="runningnumber_$i" size=3 value="$i">|;
1631         $row{bom}{data}   = sprintf qq|<input name="bom_$i" type=checkbox class=checkbox value=1 %s>|,
1632                                        $form->{"bom_$i"} ? 'checked' : '';
1633       }
1634       push @row_hiddens,        qw(unit description partnumber partsgroup);
1635       $row{unit}{data}        = $form->{"unit_$i"};
1636       $row{description}{data} = $form->{"description_$i"};
1637       $row{partsgroup}{data}  = $form->{"partsgroup_$i"};
1638       $row{bom}{align}        = 'center';
1639     }
1640
1641     $row{lastcost}{data}      = $line_purchase_price;
1642     $row{total}{data}         = $linetotal;
1643     $row{deliverydate}{data}  = $deliverydate;
1644     $row{lastcost}{align}     = 'right';
1645     $row{total}{align}        = 'right';
1646     $row{deliverydate}{align} = 'right';
1647
1648     push @row_hiddens, qw(id sellprice lastcost weight price_factor_id price_factor);
1649     $row{hiddens} = [ map +{ name => "${_}_$i", value => $form->{"${_}_$i"} }, @row_hiddens ];
1650
1651     push @ROWS, \%row;
1652   }
1653
1654   print $form->parse_html_template('ic/assembly_row', { COLUMNS => \@column_index, ROWS => \@ROWS, HEADER => \%header });
1655
1656   $lxdebug->leave_sub();
1657 }
1658
1659 sub update {
1660   $lxdebug->enter_sub();
1661
1662   # parse pricegroups. and no, don't rely on check_form for this...
1663   map { $form->{"price_$_"} = $form->parse_amount(\%myconfig, $form->{"price_$_"}) } 1 .. $form->{price_rows};
1664
1665   if ($form->{item} eq "assembly") {
1666     my $i = $form->{assembly_rows};
1667
1668     # if last row is empty check the form otherwise retrieve item
1669     if (   ($form->{"partnumber_$i"} eq "")
1670         && ($form->{"description_$i"} eq "")
1671         && ($form->{"partsgroup_$i"}  eq "")) {
1672
1673       &check_form;
1674
1675     } else {
1676
1677       IC->assembly_item(\%myconfig, \%$form);
1678
1679       my $rows = scalar @{ $form->{item_list} };
1680
1681       if ($rows) {
1682         $form->{"qty_$i"} = 1 unless ($form->{"qty_$i"});
1683
1684         if ($rows > 1) {
1685           $form->{makemodel_rows}--;
1686           &select_item;
1687           exit;
1688         } else {
1689           map { $form->{item_list}[$i]{$_} =~ s/\"/&quot;/g }
1690             qw(partnumber description unit partsgroup);
1691           map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} }
1692             keys %{ $form->{item_list}[0] };
1693           $form->{"runningnumber_$i"} = $form->{assembly_rows};
1694           $form->{assembly_rows}++;
1695
1696           &check_form;
1697
1698         }
1699
1700       } else {
1701
1702         $form->{rowcount} = $i;
1703         $form->{assembly_rows}++;
1704
1705         &new_item;
1706
1707       }
1708     }
1709
1710   } elsif (($form->{item} eq 'part') || ($form->{item} eq 'service')) {
1711     &check_form;
1712   }
1713
1714   $lxdebug->leave_sub();
1715 }
1716
1717 sub save {
1718   $lxdebug->enter_sub();
1719
1720   $auth->assert('part_service_assembly_edit');
1721
1722   my ($parts_id, %newform, $previousform, $amount, $callback);
1723
1724   # check if there is a part number - commented out, cause there is an automatic allocation of numbers
1725   # $form->isblank("partnumber", $locale->text(ucfirst $form->{item}." Part Number missing!"));
1726
1727   # check if there is a description
1728   $form->isblank("description", $locale->text("Part Description missing!"));
1729
1730   if ($form->{obsolete}) {
1731     $form->error(
1732       $locale->text(
1733         "Inventory quantity must be zero before you can set this $form->{item} obsolete!"
1734       ))
1735       if ($form->{onhand} * 1);
1736   }
1737
1738   if (!$form->{buchungsgruppen_id}) {
1739     $form->error($locale->text("Parts must have an entry type.") . " " .
1740      $locale->text("If you see this message, you most likely just setup your LX-Office and haven't added any entry types. If this is the case, the option is accessible for administrators in the System menu.")
1741     );
1742   }
1743
1744   $form->error($locale->text('Description must not be empty!')) unless $form->{description};
1745   $form->error($locale->text('Partnumber must not be set to empty!')) if $form->{id} && !$form->{partnumber};
1746
1747   # save part
1748   $lxdebug->message($LXDebug::DEBUG1, "ic.pl: sellprice in save = $form->{sellprice}\n");
1749   if (IC->save(\%myconfig, \%$form) == 3) {
1750     $form->error($locale->text('Partnumber not unique!'));
1751   }
1752   # saving the history
1753   if(!exists $form->{addition}) {
1754     $form->{snumbers} = qq|partnumber_| . $form->{partnumber};
1755         $form->{addition} = "SAVED";
1756         $form->save_history($form->dbconnect(\%myconfig));
1757   }
1758   # /saving the history
1759   $parts_id = $form->{id};
1760
1761   my $i;
1762   # load previous variables
1763   if ($form->{previousform}) {
1764
1765     # save the new form variables before splitting previousform
1766     map { $newform{$_} = $form->{$_} } keys %$form;
1767
1768     $previousform = $form->unescape($form->{previousform});
1769
1770     # don't trample on previous variables
1771     map { delete $form->{$_} } keys %newform;
1772
1773     # now take it apart and restore original values
1774     foreach my $item (split /&/, $previousform) {
1775       my ($key, $value) = split m/=/, $item, 2;
1776       $value =~ s/%26/&/g;
1777       $form->{$key} = $value;
1778     }
1779     $form->{taxaccounts} = $newform{taxaccount2};
1780
1781     if ($form->{item} eq 'assembly') {
1782
1783       # undo number formatting
1784       map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1785         qw(weight listprice sellprice rop);
1786
1787       $form->{assembly_rows}--;
1788       $i = $newform{rowcount};
1789       $form->{"qty_$i"} = 1 unless ($form->{"qty_$i"});
1790
1791       $form->{sellprice} -= $form->{"sellprice_$i"} * $form->{"qty_$i"};
1792       $form->{weight}    -= $form->{"weight_$i"} * $form->{"qty_$i"};
1793
1794       # change/add values for assembly item
1795       map { $form->{"${_}_$i"} = $newform{$_} } qw(partnumber description bin unit weight listprice sellprice inventory_accno income_accno expense_accno price_factor_id);
1796
1797       # das ist __voll__ bekloppt, dass so auszurechnen jb 22.5.09
1798       #$form->{sellprice} += $form->{"sellprice_$i"} * $form->{"qty_$i"};
1799       $form->{weight}    += $form->{"weight_$i"} * $form->{"qty_$i"};
1800
1801     } else {
1802
1803       # set values for last invoice/order item
1804       $i = $form->{rowcount};
1805       $form->{"qty_$i"} = 1 unless ($form->{"qty_$i"});
1806
1807       map { $form->{"${_}_$i"} = $newform{$_} } qw(partnumber description bin unit listprice inventory_accno income_accno expense_accno sellprice lastcost price_factor_id);
1808
1809       $form->{"longdescription_$i"} = $newform{notes};
1810
1811       $form->{"sellprice_$i"} = $newform{lastcost} if ($form->{vendor_id});
1812
1813       if ($form->{exchangerate} != 0) {
1814         $form->{"sellprice_$i"} /= $form->{exchangerate};
1815       }
1816
1817       $lxdebug->message($LXDebug::DEBUG1, qq|sellprice_$i in previousform 2 = | . $form->{"sellprice_$i"} . qq|\n|);
1818
1819       map { $form->{"taxaccounts_$i"} .= "$_ " } split / /, $newform{taxaccount};
1820       chop $form->{"taxaccounts_$i"};
1821       foreach my $item (qw(description rate taxnumber)) {
1822         my $index = $form->{"taxaccounts_$i"} . "_$item";
1823         $form->{$index} = $newform{$index};
1824       }
1825
1826       # credit remaining calculation
1827       $amount = $form->{"sellprice_$i"} * (1 - $form->{"discount_$i"} / 100) * $form->{"qty_$i"};
1828
1829       map { $form->{"${_}_base"} += $amount } (split / /, $form->{"taxaccounts_$i"});
1830       map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
1831
1832       $form->{creditremaining} -= $amount;
1833
1834       # redo number formatting, because invoice parse them!
1835       map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}) } qw(weight listprice sellprice rop);
1836     }
1837
1838     $form->{"id_$i"} = $parts_id;
1839
1840     # Get the actual price factor (not just the ID) for the marge calculation.
1841     $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
1842     foreach my $pfac (@{ $form->{ALL_PRICE_FACTORS} }) {
1843       next if ($pfac->{id} != $newform{price_factor_id});
1844       $form->{"marge_price_factor_$i"} = $pfac->{factor};
1845       last;
1846     }
1847     delete $form->{ALL_PRICE_FACTORS};
1848
1849     delete $form->{action};
1850
1851     # restore original callback
1852     $callback = $form->unescape($form->{callback});
1853     $form->{callback} = $form->unescape($form->{old_callback});
1854     delete $form->{old_callback};
1855
1856     $form->{makemodel_rows}--;
1857
1858     # put callback together
1859     foreach my $key (keys %$form) {
1860
1861       # do single escape for Apache 2.0
1862       my $value = $form->escape($form->{$key}, 1);
1863       $callback .= qq|&$key=$value|;
1864     }
1865     $form->{callback} = $callback;
1866   }
1867   $lxdebug->message($LXDebug::DEBUG1, qq|ic.pl: sellprice_$i nach sub save = | . $form->{"sellprice_$i"} . qq|\n|);
1868
1869   # redirect
1870   $form->redirect;
1871
1872   $lxdebug->leave_sub();
1873 }
1874
1875 sub save_as_new {
1876   $lxdebug->enter_sub();
1877
1878   $auth->assert('part_service_assembly_edit');
1879
1880   # saving the history
1881   if(!exists $form->{addition}) {
1882     $form->{snumbers} = qq|partnumber_| . $form->{partnumber};
1883         $form->{addition} = "SAVED AS NEW";
1884         $form->save_history($form->dbconnect(\%myconfig));
1885   }
1886   # /saving the history
1887   $form->{id} = 0;
1888   if ($form->{"original_partnumber"} &&
1889       ($form->{"partnumber"} eq $form->{"original_partnumber"})) {
1890     $form->{partnumber} = "";
1891   }
1892   &save;
1893   $lxdebug->leave_sub();
1894 }
1895
1896 sub delete {
1897   $lxdebug->enter_sub();
1898
1899   $auth->assert('part_service_assembly_edit');
1900
1901   # saving the history
1902   if(!exists $form->{addition}) {
1903     $form->{snumbers} = qq|partnumber_| . $form->{partnumber};
1904         $form->{addition} = "DELETED";
1905         $form->save_history($form->dbconnect(\%myconfig));
1906   }
1907   # /saving the history
1908   my $rc = IC->delete(\%myconfig, \%$form);
1909
1910   # redirect
1911   $form->redirect($locale->text('Item deleted!')) if ($rc > 0);
1912   $form->error($locale->text('Cannot delete item!'));
1913
1914   $lxdebug->leave_sub();
1915 }
1916
1917 sub price_row {
1918   $lxdebug->enter_sub();
1919
1920   $auth->assert('part_service_assembly_edit');
1921
1922   my ($numrows) = @_;
1923
1924   my @PRICES = map +{
1925     pricegroup    => $form->{"pricegroup_$_"},
1926     pricegroup_id => $form->{"pricegroup_id_$_"},
1927     price         => $form->{"price_$_"},
1928   }, 1 .. $numrows;
1929
1930   print $form->parse_html_template('ic/price_row', { PRICES => \@PRICES });
1931
1932   $lxdebug->leave_sub();
1933 }
1934
1935 sub parts_language_selection {
1936   $lxdebug->enter_sub();
1937
1938   $auth->assert('part_service_assembly_edit');
1939
1940   our ($onload);
1941
1942   my $languages = IC->retrieve_languages(\%myconfig, $form);
1943
1944   if ($form->{language_values} ne "") {
1945     foreach $item (split(/---\+\+\+---/, $form->{language_values})) {
1946       my ($language_id, $translation, $longdescription) = split(/--\+\+--/, $item);
1947
1948       foreach my $language (@{ $languages }) {
1949         next unless ($language->{id} == $language_id);
1950
1951         $language->{translation}     = $translation;
1952         $language->{longdescription} = $longdescription;
1953         last;
1954       }
1955     }
1956   }
1957
1958   my @header_sort = qw(name longdescription);
1959   my %header_title = ( "name" => $locale->text("Name"),
1960                        "longdescription" => $locale->text("Long Description"),
1961                        );
1962
1963   my @header =
1964     map(+{ "column_title" => $header_title{$_},
1965            "column" => $_,
1966            "callback" => $callback,
1967          },
1968         @header_sort);
1969
1970   $form->{"title"} = $locale->text("Language Values");
1971   $form->header();
1972   print $form->parse_html_template("ic/parts_language_selection", { "HEADER"    => \@header,
1973                                                                     "LANGUAGES" => $languages,
1974                                                                     "onload"    => $onload });
1975
1976   $lxdebug->leave_sub();
1977 }
1978
1979 sub continue { call_sub($form->{"nextsub"}); }