ffc734bd819b13411157a0aa93161fc23328f571
[kivitendo-erp.git] / SL / IC.pm
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 #  Contributors:
16 #
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
21 #
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
30 #
31 # Inventory Control backend
32 #
33 #======================================================================
34
35 package IC;
36
37 use Data::Dumper;
38 use List::MoreUtils qw(all any);
39 use YAML;
40
41 use SL::CVar;
42 use SL::DBUtils;
43
44 sub get_part {
45   $main::lxdebug->enter_sub();
46
47   my ($self, $myconfig, $form) = @_;
48
49   # connect to db
50   my $dbh = $form->dbconnect($myconfig);
51
52   my $sth;
53
54   my $query =
55     qq|SELECT p.*,
56          c1.accno AS inventory_accno,
57          c2.accno AS income_accno,
58          c3.accno AS expense_accno,
59          pg.partsgroup
60        FROM parts p
61        LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
62        LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
63        LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
64        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
65        WHERE p.id = ? |;
66   my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
67
68   # copy to $form variables
69   map { $form->{$_} = $ref->{$_} } (keys %{$ref});
70
71   $form->{onhand} *= 1;
72
73   # part or service item
74   $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
75   if ($form->{assembly}) {
76     $form->{item} = 'assembly';
77
78     # retrieve assembly items
79     $query =
80       qq|SELECT p.id, p.partnumber, p.description,
81            p.sellprice, p.lastcost, p.weight, a.qty, a.bom, p.unit,
82            pg.partsgroup, p.price_factor_id, pfac.factor AS price_factor
83          FROM parts p
84          JOIN assembly a ON (a.parts_id = p.id)
85          LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
86          LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
87          WHERE (a.id = ?)
88          ORDER BY a.oid|;
89     $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
90
91     $form->{assembly_rows} = 0;
92     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
93       $form->{assembly_rows}++;
94       foreach my $key (keys %{$ref}) {
95         $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
96       }
97     }
98     $sth->finish;
99
100   }
101
102   # setup accno hash for <option checked> {amount} is used in create_links
103   $form->{amount}{IC}         = $form->{inventory_accno};
104   $form->{amount}{IC_income}  = $form->{income_accno};
105   $form->{amount}{IC_sale}    = $form->{income_accno};
106   $form->{amount}{IC_expense} = $form->{expense_accno};
107   $form->{amount}{IC_cogs}    = $form->{expense_accno};
108
109   my @pricegroups          = ();
110   my @pricegroups_not_used = ();
111
112   # get prices
113   $query =
114     qq|SELECT p.parts_id, p.pricegroup_id, p.price,
115          (SELECT pg.pricegroup
116           FROM pricegroup pg
117           WHERE pg.id = p.pricegroup_id) AS pricegroup
118        FROM prices p
119        WHERE (parts_id = ?)
120        ORDER BY pricegroup|;
121   $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
122
123   #for pricegroups
124   my $i = 1;
125   while (($form->{"klass_$i"}, $form->{"pricegroup_id_$i"},
126           $form->{"price_$i"}, $form->{"pricegroup_$i"})
127          = $sth->fetchrow_array()) {
128     push @pricegroups, $form->{"pricegroup_id_$i"};
129     $i++;
130   }
131
132   $sth->finish;
133
134   # get pricegroups
135   $query = qq|SELECT id, pricegroup FROM pricegroup|;
136   $form->{PRICEGROUPS} = selectall_hashref_query($form, $dbh, $query);
137
138   #find not used pricegroups
139   while (my $tmp = pop(@{ $form->{PRICEGROUPS} })) {
140     my $in_use = 0;
141     foreach my $item (@pricegroups) {
142       if ($item eq $tmp->{id}) {
143         $in_use = 1;
144         last;
145       }
146     }
147     push(@pricegroups_not_used, $tmp) unless ($in_use);
148   }
149
150   # if not used pricegroups are avaible
151   if (@pricegroups_not_used) {
152
153     foreach my $name (@pricegroups_not_used) {
154       $form->{"klass_$i"} = "$name->{id}";
155       $form->{"pricegroup_id_$i"} = "$name->{id}";
156       $form->{"pricegroup_$i"}    = "$name->{pricegroup}";
157       $i++;
158     }
159   }
160
161   #correct rows
162   $form->{price_rows} = $i - 1;
163
164   unless ($form->{item} eq 'service') {
165
166     # get makes
167     if ($form->{makemodel}) {
168       $query = qq|SELECT m.make, m.model FROM makemodel m | .
169                qq|WHERE m.parts_id = ?|;
170       my @values = ($form->{id});
171       $sth = $dbh->prepare($query);
172       $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
173
174       my $i = 1;
175       while (($form->{"make_$i"}, $form->{"model_$i"}) = $sth->fetchrow_array)
176       {
177         $i++;
178       }
179       $sth->finish;
180       $form->{makemodel_rows} = $i - 1;
181
182     }
183   }
184
185   # get translations
186   $form->{language_values} = "";
187   $query = qq|SELECT language_id, translation, longdescription
188               FROM translation
189               WHERE parts_id = ?|;
190   my $trq = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
191   while (my $tr = $trq->fetchrow_hashref("NAME_lc")) {
192     $form->{language_values} .= "---+++---" . join('--++--', @{$tr}{qw(language_id translation longdescription)});
193   }
194   $trq->finish;
195
196   # now get accno for taxes
197   $query =
198     qq|SELECT c.accno
199        FROM chart c, partstax pt
200        WHERE (pt.chart_id = c.id) AND (pt.parts_id = ?)|;
201   $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
202   while (my ($key) = $sth->fetchrow_array) {
203     $form->{amount}{$key} = $key;
204   }
205
206   $sth->finish;
207
208   # is it an orphan
209   my @referencing_tables = qw(invoice orderitems inventory rmaitems);
210   my %column_map         = ( );
211   my $parts_id           = conv_i($form->{id});
212
213   $form->{orphaned}      = 1;
214
215   foreach my $table (@referencing_tables) {
216     my $column  = $column_map{$table} || 'parts_id';
217     $query      = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
218     my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
219
220     if ($found) {
221       $form->{orphaned} = 0;
222       last;
223     }
224   }
225
226   $form->{"unit_changeable"} = $form->{orphaned};
227
228   $dbh->disconnect;
229
230   $main::lxdebug->leave_sub();
231 }
232
233 sub get_pricegroups {
234   $main::lxdebug->enter_sub();
235
236   my ($self, $myconfig, $form) = @_;
237
238   my $dbh = $form->dbconnect($myconfig);
239
240   # get pricegroups
241   my $query = qq|SELECT id, pricegroup FROM pricegroup|;
242   my $pricegroups = selectall_hashref_query($form, $dbh, $query);
243
244   my $i = 1;
245   foreach my $pg (@{ $pricegroups }) {
246     $form->{"klass_$i"} = "$pg->{id}";
247     $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
248     $form->{"pricegroup_id_$i"} = "$pg->{id}";
249     $form->{"pricegroup_$i"}    = "$pg->{pricegroup}";
250     $i++;
251   }
252
253   #correct rows
254   $form->{price_rows} = $i - 1;
255
256   $dbh->disconnect;
257
258   $main::lxdebug->leave_sub();
259
260   return $pricegroups;
261 }
262
263 sub retrieve_buchungsgruppen {
264   $main::lxdebug->enter_sub();
265
266   my ($self, $myconfig, $form) = @_;
267
268   my ($query, $sth);
269
270   my $dbh = $form->dbconnect($myconfig);
271
272   # get buchungsgruppen
273   $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
274   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
275
276   $main::lxdebug->leave_sub();
277 }
278
279 sub save {
280   $main::lxdebug->enter_sub();
281
282   my ($self, $myconfig, $form) = @_;
283   my @values;
284   # connect to database, turn off AutoCommit
285   my $dbh = $form->dbconnect_noauto($myconfig);
286
287   # save the part
288   # make up a unique handle and store in partnumber field
289   # then retrieve the record based on the unique handle to get the id
290   # replace the partnumber field with the actual variable
291   # add records for makemodel
292
293   # if there is a $form->{id} then replace the old entry
294   # delete all makemodel entries and add the new ones
295
296   # undo amount formatting
297   map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
298     qw(rop weight listprice sellprice gv lastcost);
299
300   my $makemodel = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
301
302   $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
303
304   my ($query, $sth);
305
306   my $priceupdate = ', priceupdate = current_date';
307
308   if ($form->{id}) {
309
310     # get old price
311     $query = qq|SELECT sellprice, weight FROM parts WHERE id = ?|;
312     my ($sellprice, $weight) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
313
314     # if item is part of an assembly adjust all assemblies
315     $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
316     $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
317     while (my ($id, $qty) = $sth->fetchrow_array) {
318       &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
319     }
320     $sth->finish;
321
322     if ($form->{item} ne 'service') {
323       # delete makemodel records
324       do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
325     }
326
327     if ($form->{item} eq 'assembly') {
328       # delete assembly records
329       do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
330     }
331
332     # delete tax records
333     do_query($form, $dbh, qq|DELETE FROM partstax WHERE parts_id = ?|, conv_i($form->{id}));
334
335     # delete translations
336     do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
337
338     # Check whether or not the prices have changed. If they haven't
339     # then 'priceupdate' should not be updated.
340     my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
341     $priceupdate        = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
342
343   } else {
344     my ($count) = selectrow_query($form, $dbh, qq|SELECT COUNT(*) FROM parts WHERE partnumber = ?|, $form->{partnumber});
345     if ($count) {
346       $main::lxdebug->leave_sub();
347       return 3;
348     }
349
350     ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
351     do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber) VALUES (?, '')|, $form->{id});
352
353     $form->{orphaned} = 1;
354     if ($form->{partnumber} eq "" && $form->{"item"} eq "service") {
355       $form->{partnumber} = $form->update_defaults($myconfig, "servicenumber");
356     }
357     if ($form->{partnumber} eq "" && $form->{"item"} ne "service") {
358       $form->{partnumber} = $form->update_defaults($myconfig, "articlenumber");
359     }
360
361   }
362   my $partsgroup_id = 0;
363
364   if ($form->{partsgroup}) {
365     (my $partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
366   }
367
368   my ($subq_inventory, $subq_expense, $subq_income);
369   if ($form->{"item"} eq "part") {
370     $subq_inventory =
371       qq|(SELECT bg.inventory_accno_id
372           FROM buchungsgruppen bg
373           WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
374   } else {
375     $subq_inventory = "NULL";
376   }
377
378   if ($form->{"item"} ne "assembly") {
379     $subq_expense =
380       qq|(SELECT bg.expense_accno_id_0
381           FROM buchungsgruppen bg
382           WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
383   } else {
384     $subq_expense = "NULL";
385   }
386
387   $query =
388     qq|UPDATE parts SET
389          partnumber = ?,
390          description = ?,
391          makemodel = ?,
392          alternate = 'f',
393          assembly = ?,
394          listprice = ?,
395          sellprice = ?,
396          lastcost = ?,
397          weight = ?,
398          unit = ?,
399          notes = ?,
400          formel = ?,
401          rop = ?,
402          bin = ?,
403          buchungsgruppen_id = ?,
404          payment_id = ?,
405          inventory_accno_id = $subq_inventory,
406          income_accno_id = (SELECT bg.income_accno_id_0 FROM buchungsgruppen bg WHERE bg.id = ?),
407          expense_accno_id = $subq_expense,
408          obsolete = ?,
409          image = ?,
410          drawing = ?,
411          shop = ?,
412          ve = ?,
413          gv = ?,
414          ean = ?,
415          has_sernumber = ?,
416          not_discountable = ?,
417          microfiche = ?,
418          partsgroup_id = ?,
419          price_factor_id = ?
420          $priceupdate
421        WHERE id = ?|;
422   @values = ($form->{partnumber},
423              $form->{description},
424              $makemodel ? 't' : 'f',
425              $form->{assembly} ? 't' : 'f',
426              $form->{listprice},
427              $form->{sellprice},
428              $form->{lastcost},
429              $form->{weight},
430              $form->{unit},
431              $form->{notes},
432              $form->{formel},
433              $form->{rop},
434              $form->{bin},
435              conv_i($form->{buchungsgruppen_id}),
436              conv_i($form->{payment_id}),
437              conv_i($form->{buchungsgruppen_id}),
438              $form->{obsolete} ? 't' : 'f',
439              $form->{image},
440              $form->{drawing},
441              $form->{shop} ? 't' : 'f',
442              conv_i($form->{ve}),
443              conv_i($form->{gv}),
444              $form->{ean},
445              $form->{has_sernumber} ? 't' : 'f',
446              $form->{not_discountable} ? 't' : 'f',
447              $form->{microfiche},
448              conv_i($partsgroup_id),
449              conv_i($form->{price_factor_id}),
450              conv_i($form->{id})
451   );
452   do_query($form, $dbh, $query, @values);
453
454   # delete translation records
455   do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
456
457   if ($form->{language_values} ne "") {
458     foreach my $item (split(/---\+\+\+---/, $form->{language_values})) {
459       my ($language_id, $translation, $longdescription) = split(/--\+\+--/, $item);
460       if ($translation ne "") {
461         $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
462                     VALUES ( ?, ?, ?, ? )|;
463         @values = (conv_i($form->{id}), conv_i($language_id), $translation, $longdescription);
464         do_query($form, $dbh, $query, @values);
465       }
466     }
467   }
468
469   # delete price records
470   do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
471
472   # insert price records only if different to sellprice
473   for my $i (1 .. $form->{price_rows}) {
474     my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
475     if ($price == 0) {
476       $form->{"price_$i"} = $form->{sellprice};
477     }
478     if (
479         (   $price
480          || $form->{"klass_$i"}
481          || $form->{"pricegroup_id_$i"})
482         and $price != $form->{sellprice}
483       ) {
484       #$klass = $form->parse_amount($myconfig, $form->{"klass_$i"});
485       $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) | .
486                qq|VALUES(?, ?, ?)|;
487       @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
488       do_query($form, $dbh, $query, @values);
489     }
490   }
491
492   # insert makemodel records
493   unless ($form->{item} eq 'service') {
494     for my $i (1 .. $form->{makemodel_rows}) {
495       if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
496
497         $query = qq|INSERT INTO makemodel (parts_id, make, model) | .
498                              qq|VALUES (?, ?, ?)|;
499                     @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"});
500
501         do_query($form, $dbh, $query, @values);
502       }
503     }
504   }
505
506   # insert taxes
507   foreach my $item (split(/ /, $form->{taxaccounts})) {
508     if ($form->{"IC_tax_$item"}) {
509       $query =
510         qq|INSERT INTO partstax (parts_id, chart_id)
511            VALUES (?, (SELECT id FROM chart WHERE accno = ?))|;
512                         @values = (conv_i($form->{id}), $item);
513       do_query($form, $dbh, $query, @values);
514     }
515   }
516
517   # add assembly records
518   if ($form->{item} eq 'assembly') {
519
520     for my $i (1 .. $form->{assembly_rows}) {
521       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
522
523       if ($form->{"qty_$i"} != 0) {
524         $form->{"bom_$i"} *= 1;
525         $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
526                              qq|VALUES (?, ?, ?, ?)|;
527                     @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
528         do_query($form, $dbh, $query, @values);
529       }
530     }
531
532     my @a = localtime;
533     $a[5] += 1900;
534     $a[4]++;
535     my $shippingdate = "$a[5]-$a[4]-$a[3]";
536
537     $form->get_employee($dbh);
538
539   }
540
541   #set expense_accno=inventory_accno if they are different => bilanz
542   my $vendor_accno =
543     ($form->{expense_accno} != $form->{inventory_accno})
544     ? $form->{inventory_accno}
545     : $form->{expense_accno};
546
547   # get tax rates and description
548   my $accno_id =
549     ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
550   $query =
551     qq|SELECT c.accno, c.description, t.rate, t.taxnumber
552        FROM chart c, tax t
553        WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
554        ORDER BY c.accno|;
555   my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
556
557   $form->{taxaccount} = "";
558   while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
559     $form->{taxaccount} .= "$ptr->{accno} ";
560     if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
561       $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
562       $form->{"$ptr->{accno}_description"} = $ptr->{description};
563       $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
564       $form->{taxaccount2} .= " $ptr->{accno} ";
565     }
566   }
567
568   CVar->save_custom_variables('dbh'       => $dbh,
569                               'module'    => 'IC',
570                               'trans_id'  => $form->{id},
571                               'variables' => $form);
572
573   # commit
574   my $rc = $dbh->commit;
575   $dbh->disconnect;
576
577   $main::lxdebug->leave_sub();
578
579   return $rc;
580 }
581
582 sub update_assembly {
583   $main::lxdebug->enter_sub();
584
585   my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
586
587   my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
588   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
589
590   while (my ($pid, $aqty) = $sth->fetchrow_array) {
591     &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
592   }
593   $sth->finish;
594
595   $query =
596     qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
597        WHERE id = ?|;
598   my @values = ($qty * ($form->{sellprice} - $sellprice),
599              $qty * ($form->{weight} - $weight), conv_i($id));
600   do_query($form, $dbh, $query, @values);
601
602   $main::lxdebug->leave_sub();
603 }
604
605 sub retrieve_assemblies {
606   $main::lxdebug->enter_sub();
607
608   my ($self, $myconfig, $form) = @_;
609
610   # connect to database
611   my $dbh = $form->dbconnect($myconfig);
612
613   my $where = qq|NOT p.obsolete|;
614   my @values;
615
616   if ($form->{partnumber}) {
617     $where .= qq| AND (p.partnumber ILIKE ?)|;
618     push(@values, '%' . $form->{partnumber} . '%');
619   }
620
621   if ($form->{description}) {
622     $where .= qq| AND (p.description ILIKE ?)|;
623     push(@values, '%' . $form->{description} . '%');
624   }
625
626   # retrieve assembly items
627   my $query =
628     qq|SELECT p.id, p.partnumber, p.description,
629          p.bin, p.onhand, p.rop,
630          (SELECT sum(p2.inventory_accno_id)
631           FROM parts p2, assembly a
632           WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
633        FROM parts p
634        WHERE NOT p.obsolete AND p.assembly $where|;
635
636   $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
637
638   $dbh->disconnect;
639
640   $main::lxdebug->leave_sub();
641 }
642
643 sub delete {
644   $main::lxdebug->enter_sub();
645
646   my ($self, $myconfig, $form) = @_;
647   my @values = (conv_i($form->{id}));
648   # connect to database, turn off AutoCommit
649   my $dbh = $form->dbconnect_noauto($myconfig);
650
651   my %columns = ( "assembly" => "id", "parts" => "id" );
652
653   for my $table (qw(prices partstax makemodel inventory assembly license translation parts)) {
654     my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
655     do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
656   }
657
658   # commit
659   my $rc = $dbh->commit;
660   $dbh->disconnect;
661
662   $main::lxdebug->leave_sub();
663
664   return $rc;
665 }
666
667 sub assembly_item {
668   $main::lxdebug->enter_sub();
669
670   my ($self, $myconfig, $form) = @_;
671
672   my $i = $form->{assembly_rows};
673   my $var;
674   my $where = qq|1 = 1|;
675   my @values;
676
677   my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
678
679   while (my ($column, $table) = each(%columns)) {
680     next unless ($form->{"${column}_$i"});
681     $where .= qq| AND ${table}.${column} ILIKE ?|;
682     push(@values, '%' . $form->{"${column}_$i"} . '%');
683   }
684
685   if ($form->{id}) {
686     $where .= qq| AND NOT (p.id = ?)|;
687     push(@values, conv_i($form->{id}));
688   }
689
690   if ($form->{partnumber}) {
691     $where .= qq| ORDER BY p.partnumber|;
692   } else {
693     $where .= qq| ORDER BY p.description|;
694   }
695
696   # connect to database
697   my $dbh = $form->dbconnect($myconfig);
698
699   my $query =
700     qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
701        p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
702        p.price_factor_id, pfac.factor AS price_factor
703        FROM parts p
704        LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
705        LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
706        WHERE $where|;
707   $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
708
709   $dbh->disconnect;
710
711   $main::lxdebug->leave_sub();
712 }
713
714 #
715 # Report for Wares.
716 # Warning, deep magic ahead.
717 # This function gets all parts from the database according to the filters specified
718 #
719 # specials:
720 #   sort revers  - sorting field + direction
721 #   top100
722 #
723 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
724 #   partnumber ean description partsgroup microfiche drawing
725 #
726 # column flags:
727 #   l_partnumber l_description l_listprice l_sellprice l_lastcost l_priceupdate l_weight l_unit l_bin l_rop l_image l_drawing l_microfiche l_partsgroup
728 #
729 # exclusives:
730 #   itemstatus  = active | onhand | short | obsolete | orphaned
731 #   searchitems = part | assembly | service
732 #
733 # joining filters:
734 #   make model                               - makemodel
735 #   serialnumber transdatefrom transdateto   - invoice/orderitems
736 #
737 # binary flags:
738 #   bought sold onorder ordered rfq quoted   - aggreg joins with invoices/orders
739 #   l_linetotal l_subtotal                   - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
740 #   l_soldtotal                              - aggreg join to display total of sold quantity
741 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
742 #   short                                    - NOT IMPLEMENTED as form filter, only as itemstatus option
743 #   l_serialnumber                           - belonges to serialnumber filter
744 #   l_deliverydate                           - displays deliverydate is sold etc. flags are active
745 #   l_soldtotal                              - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
746 #
747 # not working:
748 #   onhand                                   - as above, but masking the simple itemstatus results (doh!)
749 #   warehouse onhand
750 #   search by overrides of description
751 #
752 # disabled sanity checks and changes:
753 #  - searchitems = assembly will no longer disable bought
754 #  - searchitems = service  will no longer disable make and model, although services don't have make/model, it doesn't break the query
755 #  - itemstatus  = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
756 #  - itemstatus  = obsolete will no longer disable onhand, short
757 #  - allow sorting by ean
758 #  - serialnumber filter also works if l_serialnumber isn't ticked
759 #  - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
760 #
761 sub all_parts {
762   $main::lxdebug->enter_sub();
763
764   my ($self, $myconfig, $form) = @_;
765   my $dbh = $form->get_standard_dbh($myconfig);
766
767   $form->{parts}     = +{ };
768   $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
769
770   my @simple_filters       = qw(partnumber ean description partsgroup microfiche drawing onhand);
771   my @makemodel_filters    = qw(make model);
772   my @invoice_oi_filters   = qw(serialnumber soldtotal);
773   my @apoe_filters         = qw(transdate);
774   my @like_filters         = (@simple_filters, @makemodel_filters, @invoice_oi_filters);
775   my @all_columns          = (@simple_filters, @makemodel_filters, @apoe_filters, qw(serialnumber));
776   my @simple_l_switches    = (@all_columns, qw(listprice sellprice lastcost priceupdate weight unit bin rop image));
777   my @oe_flags             = qw(bought sold onorder ordered rfq quoted);
778   my @qsooqr_flags         = qw(invnumber ordnumber quonumber trans_id name module qty);
779   my @deliverydate_flags   = qw(deliverydate);
780 #  my @other_flags          = qw(onhand); # ToDO: implement these
781 #  my @inactive_flags       = qw(l_subtotal short l_linetotal);
782
783   my @select_tokens = qw(id factor);
784   my @where_tokens  = qw(1=1);
785   my @group_tokens  = ();
786   my @bind_vars     = ();
787   my %joins_needed  = ();
788
789   my %joins = (
790     partsgroup => 'LEFT JOIN partsgroup pg      ON (pg.id       = p.partsgroup_id)',
791     makemodel  => 'LEFT JOIN makemodel mm       ON (mm.parts_id = p.id)',
792     pfac       => 'LEFT JOIN price_factors pfac ON (pfac.id     = p.price_factor_id)',
793     invoice_oi =>
794       q|LEFT JOIN (
795          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty,          assemblyitem,         deliverydate, 'invoice'    AS ioi, id FROM invoice UNION
796          SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, id FROM orderitems
797        ) AS ioi ON ioi.parts_id = p.id|,
798     apoe       =>
799       q|LEFT JOIN (
800          SELECT id, transdate, 'ir' AS module, ordnumber, quonumber,         invnumber, FALSE AS quotation, NULL AS customer_id,         vendor_id, NULL AS deliverydate, 'invoice'    AS ioi FROM ap UNION
801          SELECT id, transdate, 'is' AS module, ordnumber, quonumber,         invnumber, FALSE AS quotation,         customer_id, NULL AS vendor_id,         deliverydate, 'invoice'    AS ioi FROM ar UNION
802          SELECT id, transdate, 'oe' AS module, ordnumber, quonumber, NULL AS invnumber,          quotation,         customer_id,         vendor_id, NULL AS deliverydate, 'orderitems' AS ioi FROM oe
803        ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
804     cv         =>
805       q|LEFT JOIN (
806            SELECT id, name, 'customer' AS cv FROM customer UNION
807            SELECT id, name, 'vendor'   AS cv FROM vendor
808          ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
809   );
810   my @join_order = qw(partsgroup makemodel invoice_oi apoe cv pfac);
811
812   my %table_prefix = (
813      deliverydate => 'apoe.', serialnumber => 'ioi.',
814      transdate    => 'apoe.', trans_id     => 'ioi.',
815      module       => 'apoe.', name         => 'cv.',
816      ordnumber    => 'apoe.', make         => 'mm.',
817      quonumber    => 'apoe.', model        => 'mm.',
818      invnumber    => 'apoe.', partsgroup   => 'pg.',
819      lastcost     => ' ',
820      factor       => 'pfac.',
821      'SUM(ioi.qty)' => ' ',
822      description  => 'p.',
823      qty          => 'ioi.',
824      serialnumber => 'ioi.',
825      quotation    => 'apoe.',
826      cv           => 'cv.',
827      "ioi.id"     => ' ',
828      "ioi.ioi"    => ' ',
829   );
830
831   # if the join condition in these blocks are met, the column
832   # of the scecified table will gently override (coalesce actually) the original value
833   # use it to conditionally coalesce values from subtables
834   my @column_override = (
835     #  column name,   prefix,  joins_needed
836     [ 'description',  'ioi.',  'invoice_oi'  ],
837     [ 'deliverydate', 'ioi.',  'invoice_oi'  ],
838     [ 'transdate',    'apoe.', 'apoe'        ],
839     [ 'unit',         'ioi.',  'invoice_oi'  ],
840     [ 'sellprice',    'ioi.',  'invoice_oi'  ],
841   );
842
843   # careful with renames. these are HARD, and any filters done on the original column will break
844   my %renamed_columns = (
845     'factor'       => 'price_factor',
846     'SUM(ioi.qty)' => 'soldtotal',
847     'ioi.id'       => 'ioi_id',
848     'ioi.ioi'      => 'ioi',
849   );
850
851   if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
852     @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
853   }
854
855   my $make_token_builder = sub {
856     my $joins_needed = shift;
857     sub {
858       my ($col, $alias) = @_;
859       my @coalesce_tokens =
860         map  { ($_->[1] || 'p.') . $_->[0] }
861         grep { !$_->[2] || $joins_needed->{$_->[2]} }
862         grep {  $_->[0] eq $col }
863         @column_override, [ $col, $table_prefix{$col} ];
864
865       my $coalesce = scalar @coalesce_tokens > 1;
866       return ($coalesce
867         ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
868         : shift                              @coalesce_tokens)
869         . ($alias && ($coalesce || $renamed_columns{$col})
870         ?  " AS " . ($renamed_columns{$col} || $col)
871         : '');
872     }
873   };
874
875   #===== switches and simple filters ========#
876
877   # special case transdate
878   if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
879     $form->{"l_transdate"} = 1;
880     push @select_tokens, 'transdate';
881     for (qw(transdatefrom transdateto)) {
882       next unless $form->{$_};
883       push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
884       push @bind_vars,    $form->{$_};
885     }
886   }
887
888   foreach (@like_filters) {
889     next unless $form->{$_};
890     $form->{"l_$_"} = '1'; # show the column
891     push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
892     push @bind_vars,    "%$form->{$_}%";
893   }
894
895   foreach (@simple_l_switches) {
896     next unless $form->{"l_$_"};
897     push @select_tokens, $_;
898   }
899
900   for ($form->{searchitems}) {
901     push @where_tokens, 'p.inventory_accno_id > 0'     if /part/;
902     push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
903     push @where_tokens, 'NOT p.assembly'               if /service/;
904     push @where_tokens, '    p.assembly'               if /assembly/;
905   }
906
907   for ($form->{itemstatus}) {
908     push @where_tokens, 'p.id NOT IN
909         (SELECT DISTINCT parts_id FROM invoice UNION
910          SELECT DISTINCT parts_id FROM assembly UNION
911          SELECT DISTINCT parts_id FROM orderitems)'    if /orphaned/;
912     push @where_tokens, 'p.onhand = 0'                 if /orphaned/;
913     push @where_tokens, 'NOT p.obsolete'               if /active/;
914     push @where_tokens, '    p.obsolete',              if /obsolete/;
915     push @where_tokens, 'p.onhand > 0',                if /onhand/;
916     push @where_tokens, 'p.onhand < p.rop',            if /short/;
917   }
918
919   my $q_assembly_lastcost =
920     qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
921         FROM assembly a_lc
922         LEFT JOIN parts p_lc            ON (a_lc.parts_id        = p_lc.id)
923         LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
924         WHERE (a_lc.id = p.id)) AS lastcost|;
925   $table_prefix{$q_assembly_lastcost} = ' ';
926
927   # special case: sorting by partnumber
928   # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
929   # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
930   # ToDO: implement proper functional sorting
931   # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
932   # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
933   #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
934   #  if $form->{sort} eq 'partnumber';
935
936   #my $order_clause = " ORDER BY $form->{sort} $sort_order";
937
938   my $limit_clause = " LIMIT 100" if $form->{top100};
939
940   #=== joins and complicated filters ========#
941
942   my $bsooqr        = any { $form->{$_} } @oe_flags;
943   my @bsooqr_tokens = ();
944
945   push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi'  if $bsooqr;
946   push @select_tokens, @deliverydate_flags                                    if $bsooqr && $form->{l_deliverydate};
947   push @select_tokens, $q_assembly_lastcost                                   if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
948   push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem|              if $form->{bought};
949   push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem|              if $form->{sold};
950   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
951   push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'|   if $form->{onorder};
952   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'customer'| if $form->{quoted};
953   push @bsooqr_tokens, q|module = 'oe' AND     quotation AND cv = 'vendor'|   if $form->{rfq};
954   push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens              if $bsooqr;
955
956   $joins_needed{partsgroup}  = 1;
957   $joins_needed{pfac}        = 1;
958   $joins_needed{makemodel}   = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
959   $joins_needed{cv}          = 1 if $bsooqr;
960   $joins_needed{apoe}        = 1 if $joins_needed{cv}   || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
961   $joins_needed{invoice_oi}  = 1 if $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
962
963   # in bsoorq, use qtys instead of onhand
964   if ($joins_needed{invoice_oi}) {
965     $renamed_columns{onhand} = 'onhand_before_bsooqr';
966     $renamed_columns{qty}    = 'onhand';
967   }
968
969   # special case for description search.
970   # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
971   # now we'd like to search also for the masked description entered in orderitems and invoice, so...
972   # find the old entries in of @where_tokens and @bind_vars, and adjust them
973   if ($joins_needed{invoice_oi}) {
974     for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
975       next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
976       splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
977       splice @bind_vars,    $bi, 0, $bind_vars[$bi];
978       last;
979     }
980   }
981
982   # now the master trick: soldtotal.
983   if ($form->{l_soldtotal}) {
984     push @where_tokens, 'ioi.qty >= 0';
985     push @group_tokens, @select_tokens;
986      map { s/.*\sAS\s+//si } @group_tokens;
987     push @select_tokens, 'SUM(ioi.qty)';
988   }
989
990   #============= build query ================#
991
992   my $token_builder = $make_token_builder->(\%joins_needed);
993
994   my @sort_cols    = (@simple_filters, qw(id bin priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
995      $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
996   my $sort_order   = ($form->{revers} ? ' DESC' : ' ASC');
997   my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
998
999   my $select_clause = join ', ',    map { $token_builder->($_, 1) } @select_tokens;
1000   my $join_clause   = join ' ',     @joins{ grep $joins_needed{$_}, @join_order };
1001   my $where_clause  = join ' AND ', map { "($_)" } @where_tokens;
1002   my $group_clause  = ' GROUP BY ' . join ', ',    map { $token_builder->($_) } @group_tokens if scalar @group_tokens;
1003
1004   my ($cvar_where, @cvar_values) = CVar->build_filter_query('module'         => 'IC',
1005                                                             'trans_id_field' => 'p.id',
1006                                                             'filter'         => $form);
1007
1008   if ($cvar_where) {
1009     $where_clause .= qq| AND ($cvar_where)|;
1010     push @bind_vars, @cvar_values;
1011   }
1012
1013   my $query = <<"  SQL";
1014     SELECT DISTINCT $select_clause
1015     FROM parts p
1016     $join_clause
1017     WHERE $where_clause
1018     $group_clause
1019     $order_clause
1020     $limit_clause
1021   SQL
1022
1023   $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1024
1025   map { $_->{onhand} *= 1 } @{ $form->{parts} };
1026
1027   # post processing for assembly parts lists (bom)
1028   # for each part get the assembly parts and add them into the partlist.
1029   my @assemblies;
1030   if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1031     $query =
1032       qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1033            p.unit, p.bin,
1034            p.sellprice, p.listprice, p.lastcost,
1035            p.rop, p.weight, p.priceupdate,
1036            p.image, p.drawing, p.microfiche,
1037            pfac.factor
1038          FROM parts p
1039          INNER JOIN assembly a ON (p.id = a.parts_id)
1040          $joins{pfac}
1041          WHERE a.id = ?|;
1042     my $sth = prepare_query($form, $dbh, $query);
1043
1044     foreach my $item (@{ $form->{parts} }) {
1045       push(@assemblies, $item);
1046       do_statement($form, $sth, $query, conv_i($item->{id}));
1047
1048       while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1049         $ref->{assemblyitem} = 1;
1050         map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1051         push(@assemblies, $ref);
1052       }
1053       $sth->finish;
1054     }
1055
1056     # copy assemblies to $form->{parts}
1057     $form->{parts} = \@assemblies;
1058   }
1059
1060   $main::lxdebug->leave_sub();
1061 }
1062
1063 sub _create_filter_for_priceupdate {
1064   $main::lxdebug->enter_sub();
1065
1066   my $self     = shift;
1067   my $myconfig = \%main::myconfig;
1068   my $form     = $main::form;
1069
1070   my @where_values;
1071   my $where = '1 = 1';
1072
1073   foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1074     my $column = $item;
1075     $column =~ s/.*\.//;
1076     next unless ($form->{$column});
1077
1078     $where .= qq| AND $item ILIKE ?|;
1079     push(@where_values, '%' . $form->{$column} . '%');
1080   }
1081
1082   foreach my $item (qw(description serialnumber)) {
1083     next unless ($form->{$item});
1084
1085     $where .= qq| AND (${item} ILIKE ?)|;
1086     push(@where_values, '%' . $form->{$item} . '%');
1087   }
1088
1089
1090   # items which were never bought, sold or on an order
1091   if ($form->{itemstatus} eq 'orphaned') {
1092     $where .=
1093       qq| AND (p.onhand = 0)
1094           AND p.id NOT IN
1095             (
1096               SELECT DISTINCT parts_id FROM invoice
1097               UNION
1098               SELECT DISTINCT parts_id FROM assembly
1099               UNION
1100               SELECT DISTINCT parts_id FROM orderitems
1101             )|;
1102
1103   } elsif ($form->{itemstatus} eq 'active') {
1104     $where .= qq| AND p.obsolete = '0'|;
1105
1106   } elsif ($form->{itemstatus} eq 'obsolete') {
1107     $where .= qq| AND p.obsolete = '1'|;
1108
1109   } elsif ($form->{itemstatus} eq 'onhand') {
1110     $where .= qq| AND p.onhand > 0|;
1111
1112   } elsif ($form->{itemstatus} eq 'short') {
1113     $where .= qq| AND p.onhand < p.rop|;
1114
1115   }
1116
1117   foreach my $column (qw(make model)) {
1118     next unless ($form->{$column});
1119     $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1120     push(@where_values, '%' . $form->{$column} . '%');
1121   }
1122
1123   $main::lxdebug->leave_sub();
1124
1125   return ($where, @where_values);
1126 }
1127
1128 sub get_num_matches_for_priceupdate {
1129   $main::lxdebug->enter_sub();
1130
1131   my $self     = shift;
1132
1133   my $myconfig = \%main::myconfig;
1134   my $form     = $main::form;
1135
1136   my $dbh      = $form->get_standard_dbh($myconfig);
1137
1138   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1139
1140   my $num_updated = 0;
1141   my $query;
1142
1143   for my $column (qw(sellprice listprice)) {
1144     next if ($form->{$column} eq "");
1145
1146     $query =
1147       qq|SELECT COUNT(*)
1148          FROM parts
1149          WHERE id IN
1150            (SELECT p.id
1151             FROM parts p
1152             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1153             WHERE $where)|;
1154     my ($result)  = selectfirst_array_query($form, $dbh, $query, @where_values);
1155     $num_updated += $result if (0 <= $result);
1156   }
1157
1158   $query =
1159     qq|SELECT COUNT(*)
1160        FROM prices
1161        WHERE parts_id IN
1162          (SELECT p.id
1163           FROM parts p
1164           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1165           WHERE $where) AND (pricegroup_id = ?)|;
1166   my $sth = prepare_query($form, $dbh, $query);
1167
1168   for my $i (1 .. $form->{price_rows}) {
1169     next if ($form->{"price_$i"} eq "");
1170
1171     my ($result)  = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1172     $num_updated += $result if (0 <= $result);
1173   }
1174   $sth->finish();
1175
1176   $main::lxdebug->leave_sub();
1177
1178   return $num_updated;
1179 }
1180
1181 sub update_prices {
1182   $main::lxdebug->enter_sub();
1183
1184   my ($self, $myconfig, $form) = @_;
1185
1186   my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1187   my $num_updated = 0;
1188
1189   # connect to database
1190   my $dbh = $form->dbconnect_noauto($myconfig);
1191
1192   for my $column (qw(sellprice listprice)) {
1193     next if ($form->{$column} eq "");
1194
1195     my $value = $form->parse_amount($myconfig, $form->{$column});
1196     my $operator = '+';
1197
1198     if ($form->{"${column}_type"} eq "percent") {
1199       $value = ($value / 100) + 1;
1200       $operator = '*';
1201     }
1202
1203     my $query =
1204       qq|UPDATE parts SET $column = $column $operator ?
1205          WHERE id IN
1206            (SELECT p.id
1207             FROM parts p
1208             LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1209             WHERE $where)|;
1210     my $result    = do_query($form, $dbh, $query, $value, @where_values);
1211     $num_updated += $result if (0 <= $result);
1212   }
1213
1214   my $q_add =
1215     qq|UPDATE prices SET price = price + ?
1216        WHERE parts_id IN
1217          (SELECT p.id
1218           FROM parts p
1219           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1220           WHERE $where) AND (pricegroup_id = ?)|;
1221   my $sth_add = prepare_query($form, $dbh, $q_add);
1222
1223   my $q_multiply =
1224     qq|UPDATE prices SET price = price * ?
1225        WHERE parts_id IN
1226          (SELECT p.id
1227           FROM parts p
1228           LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1229           WHERE $where) AND (pricegroup_id = ?)|;
1230   my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1231
1232   for my $i (1 .. $form->{price_rows}) {
1233     next if ($form->{"price_$i"} eq "");
1234
1235     my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1236     my $result;
1237
1238     if ($form->{"pricegroup_type_$i"} eq "percent") {
1239       $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1240     } else {
1241       $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1242     }
1243
1244     $num_updated += $result if (0 <= $result);
1245   }
1246
1247   $sth_add->finish();
1248   $sth_multiply->finish();
1249
1250   my $rc= $dbh->commit;
1251   $dbh->disconnect;
1252
1253   $main::lxdebug->leave_sub();
1254
1255   return $num_updated;
1256 }
1257
1258 sub create_links {
1259   $main::lxdebug->enter_sub();
1260
1261   my ($self, $module, $myconfig, $form) = @_;
1262
1263   # connect to database
1264   my $dbh = $form->dbconnect($myconfig);
1265
1266   my @values = ('%' . $module . '%');
1267   my $query;
1268
1269   if ($form->{id}) {
1270     $query =
1271       qq|SELECT c.accno, c.description, c.link, c.id,
1272            p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1273          FROM chart c, parts p
1274          WHERE (c.link LIKE ?) AND (p.id = ?)
1275          ORDER BY c.accno|;
1276     push(@values, conv_i($form->{id}));
1277
1278   } else {
1279     $query =
1280       qq|SELECT c.accno, c.description, c.link, c.id,
1281            d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1282          FROM chart c, defaults d
1283          WHERE c.link LIKE ?
1284          ORDER BY c.accno|;
1285   }
1286
1287   my $sth = prepare_execute_query($form, $dbh, $query, @values);
1288   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1289     foreach my $key (split(/:/, $ref->{link})) {
1290       if ($key =~ /\Q$module\E/) {
1291         if (   ($ref->{id} eq $ref->{inventory_accno_id})
1292             || ($ref->{id} eq $ref->{income_accno_id})
1293             || ($ref->{id} eq $ref->{expense_accno_id})) {
1294           push @{ $form->{"${module}_links"}{$key} },
1295             { accno       => $ref->{accno},
1296               description => $ref->{description},
1297               selected    => "selected" };
1298           $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1299             } else {
1300           push @{ $form->{"${module}_links"}{$key} },
1301             { accno       => $ref->{accno},
1302               description => $ref->{description},
1303               selected    => "" };
1304         }
1305       }
1306     }
1307   }
1308   $sth->finish;
1309
1310   # get buchungsgruppen
1311   $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1312
1313   # get payment terms
1314   $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1315
1316   if (!$form->{id}) {
1317     ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1318   }
1319
1320   $dbh->disconnect;
1321   $main::lxdebug->leave_sub();
1322 }
1323
1324 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1325 sub get_parts {
1326   $main::lxdebug->enter_sub();
1327
1328   my ($self, $myconfig, $form, $sortorder) = @_;
1329   my $dbh   = $form->dbconnect($myconfig);
1330   my $order = qq| p.partnumber|;
1331   my $where = qq|1 = 1|;
1332   my @values;
1333
1334   if ($sortorder eq "all") {
1335     $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1336     push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1337
1338   } elsif ($sortorder eq "partnumber") {
1339     $where .= qq| AND (partnumber ILIKE ?)|;
1340     push(@values, '%' . $form->{partnumber} . '%');
1341
1342   } elsif ($sortorder eq "description") {
1343     $where .= qq| AND (description ILIKE ?)|;
1344     push(@values, '%' . $form->{description} . '%');
1345     $order = "description";
1346
1347   }
1348
1349   my $query =
1350     qq|SELECT id, partnumber, description, unit, sellprice
1351        FROM parts
1352        WHERE $where ORDER BY $order|;
1353
1354   my $sth = prepare_execute_query($form, $dbh, $query, @values);
1355
1356   my $j = 0;
1357   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1358     if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1359       next;
1360     }
1361
1362     $j++;
1363     $form->{"id_$j"}          = $ref->{id};
1364     $form->{"partnumber_$j"}  = $ref->{partnumber};
1365     $form->{"description_$j"} = $ref->{description};
1366     $form->{"unit_$j"}        = $ref->{unit};
1367     $form->{"sellprice_$j"}   = $ref->{sellprice};
1368     $form->{"soldtotal_$j"}   = get_soldtotal($dbh, $ref->{id});
1369   }    #while
1370   $form->{rows} = $j;
1371   $sth->finish;
1372   $dbh->disconnect;
1373
1374   $main::lxdebug->leave_sub();
1375
1376   return $self;
1377 }    #end get_parts()
1378
1379 # gets sum of sold part with part_id
1380 sub get_soldtotal {
1381   $main::lxdebug->enter_sub();
1382
1383   my ($dbh, $id) = @_;
1384
1385   my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1386   my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1387   $sum ||= 0;
1388
1389   $main::lxdebug->leave_sub();
1390
1391   return $sum;
1392 }    #end get_soldtotal
1393
1394 sub retrieve_languages {
1395   $main::lxdebug->enter_sub();
1396
1397   my ($self, $myconfig, $form) = @_;
1398
1399   # connect to database
1400   my $dbh = $form->dbconnect($myconfig);
1401
1402   my @values;
1403   my $where;
1404   my $query;
1405
1406   if ($form->{language_values} ne "") {
1407     $query =
1408       qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1409          FROM language l
1410          LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1411          ORDER BY lower(l.description)|;
1412     @values = (conv_i($form->{id}));
1413
1414   } else {
1415     $query = qq|SELECT id, description
1416                 FROM language
1417                 ORDER BY lower(description)|;
1418   }
1419
1420   my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1421
1422   $dbh->disconnect;
1423
1424   $main::lxdebug->leave_sub();
1425
1426   return $languages;
1427 }
1428
1429 sub follow_account_chain {
1430   $main::lxdebug->enter_sub(2);
1431
1432   my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1433
1434   my @visited_accno_ids = ($accno_id);
1435
1436   my ($query, $sth);
1437
1438   $query =
1439     qq|SELECT c.new_chart_id, date($transdate) >= c.valid_from AS is_valid, | .
1440     qq|  cnew.accno | .
1441     qq|FROM chart c | .
1442     qq|LEFT JOIN chart cnew ON c.new_chart_id = cnew.id | .
1443     qq|WHERE (c.id = ?) AND NOT c.new_chart_id ISNULL AND (c.new_chart_id > 0)|;
1444   $sth = prepare_query($form, $dbh, $query);
1445
1446   while (1) {
1447     do_statement($form, $sth, $query, $accno_id);
1448     my $ref = $sth->fetchrow_hashref();
1449     last unless ($ref && $ref->{"is_valid"} &&
1450                  !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1451     $accno_id = $ref->{"new_chart_id"};
1452     $accno = $ref->{"accno"};
1453     push(@visited_accno_ids, $accno_id);
1454   }
1455
1456   $main::lxdebug->leave_sub(2);
1457
1458   return ($accno_id, $accno);
1459 }
1460
1461 sub retrieve_accounts {
1462   $main::lxdebug->enter_sub(2);
1463
1464   my ($self, $myconfig, $form, $parts_id, $index) = @_;
1465
1466   my ($query, $sth, $dbh);
1467
1468   $form->{"taxzone_id"} *= 1;
1469
1470   $dbh = $form->get_standard_dbh($myconfig);
1471
1472   my $transdate = "";
1473   if ($form->{type} eq "invoice") {
1474     if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
1475       $transdate = $form->{invdate};
1476     } else {
1477       $transdate = $form->{deliverydate};
1478     }
1479   } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1480     $transdate = $form->{invdate};
1481   } else {
1482     $transdate = $form->{transdate};
1483   }
1484
1485   if ($transdate eq "") {
1486     $transdate = "current_date";
1487   } else {
1488     $transdate = $dbh->quote($transdate);
1489   }
1490
1491   $query =
1492     qq|SELECT | .
1493     qq|  p.inventory_accno_id AS is_part, | .
1494     qq|  bg.inventory_accno_id, | .
1495     qq|  bg.income_accno_id_$form->{taxzone_id} AS income_accno_id, | .
1496     qq|  bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id, | .
1497     qq|  c1.accno AS inventory_accno, | .
1498     qq|  c2.accno AS income_accno, | .
1499     qq|  c3.accno AS expense_accno | .
1500     qq|FROM parts p | .
1501     qq|LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id | .
1502     qq|LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id | .
1503     qq|LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id | .
1504     qq|LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id | .
1505     qq|WHERE p.id = ?|;
1506   my $ref = selectfirst_hashref_query($form, $dbh, $query, $parts_id);
1507
1508   return $main::lxdebug->leave_sub(2) if (!$ref);
1509
1510   $ref->{"inventory_accno_id"} = undef unless ($ref->{"is_part"});
1511
1512   my %accounts;
1513   foreach my $type (qw(inventory income expense)) {
1514     next unless ($ref->{"${type}_accno_id"});
1515     ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1516       $self->follow_account_chain($form, $dbh, $transdate,
1517                                   $ref->{"${type}_accno_id"},
1518                                   $ref->{"${type}_accno"});
1519   }
1520
1521   map({ $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} }
1522       qw(inventory income expense));
1523
1524   my $inc_exp = $form->{"vc"} eq "customer" ? "income" : "expense";
1525   my $accno_id = $accounts{"${inc_exp}_accno_id"};
1526
1527   $query =
1528     qq|SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber | .
1529     qq|FROM tax t | .
1530     qq|LEFT JOIN chart c ON c.id = t.chart_id | .
1531     qq|WHERE t.id IN | .
1532     qq|  (SELECT tk.tax_id | .
1533     qq|   FROM taxkeys tk | .
1534     qq|   WHERE tk.chart_id = ? AND startdate <= | . quote_db_date($transdate) .
1535     qq|   ORDER BY startdate DESC LIMIT 1) |;
1536   $ref = selectfirst_hashref_query($form, $dbh, $query, $accno_id);
1537
1538   unless ($ref) {
1539     $main::lxdebug->leave_sub(2);
1540     return;
1541   }
1542
1543   $form->{"taxaccounts_$index"} = $ref->{"accno"};
1544   if ($form->{"taxaccounts"} !~ /$ref->{accno}/) {
1545     $form->{"taxaccounts"} .= "$ref->{accno} ";
1546   }
1547   map({ $form->{"$ref->{accno}_${_}"} = $ref->{$_}; }
1548       qw(rate description taxnumber));
1549
1550 #   $main::lxdebug->message(0, "formvars: rate " . $form->{"$ref->{accno}_rate"} .
1551 #                           " description " . $form->{"$ref->{accno}_description"} .
1552 #                           " taxnumber " . $form->{"$ref->{accno}_taxnumber"} .
1553 #                           " || taxaccounts_$index " . $form->{"taxaccounts_$index"} .
1554 #                           " || taxaccounts " . $form->{"taxaccounts"});
1555
1556   $main::lxdebug->leave_sub(2);
1557 }
1558
1559 sub get_basic_part_info {
1560   $main::lxdebug->enter_sub();
1561
1562   my $self     = shift;
1563   my %params   = @_;
1564
1565   Common::check_params(\%params, qw(id));
1566
1567   my @ids      = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1568
1569   if (!scalar @ids) {
1570     $main::lxdebug->leave_sub();
1571     return ();
1572   }
1573
1574   my $myconfig = \%main::myconfig;
1575   my $form     = $main::form;
1576
1577   my $dbh      = $form->get_standard_dbh($myconfig);
1578
1579   my $query    = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1580
1581   my $info     = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1582
1583   if ('' eq ref $params{id}) {
1584     $info = $info->[0] || { };
1585
1586     $main::lxdebug->leave_sub();
1587     return $info;
1588   }
1589
1590   my %info_map = map { $_->{id} => $_ } @{ $info };
1591
1592   $main::lxdebug->leave_sub();
1593
1594   return %info_map;
1595 }
1596
1597 sub prepare_parts_for_printing {
1598   $main::lxdebug->enter_sub();
1599
1600   my $self     = shift;
1601   my %params   = @_;
1602
1603   my $myconfig = \%main::myconfig;
1604   my $form     = $main::form;
1605
1606   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1607
1608   my $prefix   = $params{prefix} || 'id_';
1609   my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1610
1611   my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1612
1613   if (!@part_ids) {
1614     $main::lxdebug->leave_sub();
1615     return;
1616   }
1617
1618   my $placeholders = join ', ', ('?') x scalar(@part_ids);
1619   my $query        = qq|SELECT mm.parts_id, mm.model, v.name AS make
1620                         FROM makemodel mm
1621                         LEFT JOIN vendor v ON (mm.make = cast (v.id as text))
1622                         WHERE mm.parts_id IN ($placeholders)|;
1623
1624   my %makemodel    = ();
1625
1626   my $sth          = prepare_execute_query($form, $dbh, $query, @part_ids);
1627
1628   while (my $ref = $sth->fetchrow_hashref()) {
1629     $makemodel{$ref->{parts_id}} ||= [];
1630     push @{ $makemodel{$ref->{parts_id}} }, $ref;
1631   }
1632
1633   $sth->finish();
1634
1635   my @columns = qw(ean image microfiche drawing weight);
1636
1637   $query      = qq|SELECT id, | . join(', ', @columns) . qq|
1638                    FROM parts
1639                    WHERE id IN ($placeholders)|;
1640
1641   my %data    = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1642
1643   map { $form->{TEMPLATE_ARRAYS}{$_} = [] } (qw(make model), @columns);
1644
1645   foreach my $i (1 .. $rowcount) {
1646     my $id = $form->{"${prefix}${i}"};
1647
1648     next if (!$id);
1649
1650     foreach (@columns) {
1651       push @{ $form->{TEMPLATE_ARRAYS}{$_} }, $data{$id}->{$_};
1652     }
1653
1654     push @{ $form->{TEMPLATE_ARRAYS}{make} },  [];
1655     push @{ $form->{TEMPLATE_ARRAYS}{model} }, [];
1656
1657     next if (!$makemodel{$id});
1658
1659     foreach my $ref (@{ $makemodel{$id} }) {
1660       map { push @{ $form->{TEMPLATE_ARRAYS}{$_}->[-1] }, $ref->{$_} } qw(make model);
1661     }
1662   }
1663
1664   $main::lxdebug->leave_sub();
1665 }
1666
1667
1668 1;