Die Variable taxzone_id muss immer gesetzt sein. Wenn sie aber nicht definiert ist...
[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 use Data::Dumper;
37
38 sub get_part {
39   $main::lxdebug->enter_sub();
40
41   my ($self, $myconfig, $form) = @_;
42
43   # connect to db
44   my $dbh = $form->dbconnect($myconfig);
45
46   my $query = qq|SELECT p.*,
47                  c1.accno AS inventory_accno,
48                  c2.accno AS income_accno,
49                  c3.accno AS expense_accno,
50                  pg.partsgroup
51                  FROM parts p
52                  LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
53                  LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
54                  LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
55                  LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
56                  WHERE p.id = $form->{id}|;
57   my $sth = $dbh->prepare($query);
58   $sth->execute || $form->dberror($query);
59   my $ref = $sth->fetchrow_hashref(NAME_lc);
60
61   # copy to $form variables
62   map { $form->{$_} = $ref->{$_} } (keys %{$ref});
63
64   $sth->finish;
65
66   my %oid = ('Pg'     => 'a.oid',
67              'Oracle' => 'a.rowid');
68
69   # part or service item
70   $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
71   if ($form->{assembly}) {
72     $form->{item} = 'assembly';
73
74     # retrieve assembly items
75     $query = qq|SELECT p.id, p.partnumber, p.description,
76                 p.sellprice, p.weight, a.qty, a.bom, p.unit,
77                 pg.partsgroup
78                 FROM parts p
79                 JOIN assembly a ON (a.parts_id = p.id)
80                 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
81                 WHERE a.id = $form->{id}
82                 ORDER BY $oid{$myconfig->{dbdriver}}|;
83
84     $sth = $dbh->prepare($query);
85     $sth->execute || $form->dberror($query);
86
87     $form->{assembly_rows} = 0;
88     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
89       $form->{assembly_rows}++;
90       foreach my $key (keys %{$ref}) {
91         $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
92       }
93     }
94     $sth->finish;
95
96   }
97
98   # setup accno hash for <option checked> {amount} is used in create_links
99   $form->{amount}{IC}         = $form->{inventory_accno};
100   $form->{amount}{IC_income}  = $form->{income_accno};
101   $form->{amount}{IC_sale}    = $form->{income_accno};
102   $form->{amount}{IC_expense} = $form->{expense_accno};
103   $form->{amount}{IC_cogs}    = $form->{expense_accno};
104
105   # get prices
106   $query =
107     qq|SELECT p.parts_id, p.pricegroup_id, p.price, (SELECT pg.pricegroup FROM pricegroup pg WHERE pg.id=p.pricegroup_id) AS pricegroup FROM prices p
108               WHERE parts_id = $form->{id}
109               ORDER by pricegroup|;
110
111   $sth = $dbh->prepare($query);
112   $sth->execute || $form->dberror($query);
113
114   @pricegroups          = ();
115   @pricegroups_not_used = ();
116
117   #for pricegroups
118   my $i = 1;
119   while (
120          ($form->{"klass_$i"}, $form->{"pricegroup_id_$i"},
121           $form->{"price_$i"}, $form->{"pricegroup_$i"})
122          = $sth->fetchrow_array
123     ) {
124     $form->{"price_$i"} = $form->round_amount($form->{"price_$i"}, 5);
125     $form->{"price_$i"} =
126       $form->format_amount($myconfig, $form->{"price_$i"}, 5);
127     push @pricegroups, $form->{"pricegroup_id_$i"};
128     $i++;
129   }
130
131   $sth->finish;
132
133   # get pricegroups
134   $query = qq|SELECT p.id, p.pricegroup FROM pricegroup p|;
135
136   $pkq = $dbh->prepare($query);
137   $pkq->execute || $form->dberror($query);
138   while ($pkr = $pkq->fetchrow_hashref(NAME_lc)) {
139     push @{ $form->{PRICEGROUPS} }, $pkr;
140   }
141   $pkq->finish;
142
143   #find not used pricegroups
144   while ($tmp = pop @{ $form->{PRICEGROUPS} }) {
145     my $insert = 0;
146     foreach $item (@pricegroups) {
147       if ($item eq $tmp->{id}) {
148
149         #drop
150         $insert = 1;
151       }
152     }
153     if ($insert == 0) {
154       push @pricegroups_not_used, $tmp;
155     }
156   }
157
158   # if not used pricegroups are avaible
159   if (@pricegroups_not_used) {
160
161     foreach $name (@pricegroups_not_used) {
162       $form->{"klass_$i"} = "$name->{id}";
163       $form->{"price_$i"} = $form->round_amount($form->{sellprice}, 5);
164       $form->{"price_$i"} =
165         $form->format_amount($myconfig, $form->{"price_$i"}, 5);
166       $form->{"pricegroup_id_$i"} = "$name->{id}";
167       $form->{"pricegroup_$i"}    = "$name->{pricegroup}";
168       $i++;
169     }
170   }
171
172   #correct rows
173   $form->{price_rows} = $i - 1;
174
175   unless ($form->{item} eq 'service') {
176
177     # get makes
178     if ($form->{makemodel}) {
179       $query = qq|SELECT m.make, m.model FROM makemodel m
180                   WHERE m.parts_id = $form->{id}|;
181
182       $sth = $dbh->prepare($query);
183       $sth->execute || $form->dberror($query);
184
185       my $i = 1;
186       while (($form->{"make_$i"}, $form->{"model_$i"}) = $sth->fetchrow_array)
187       {
188         $i++;
189       }
190       $sth->finish;
191       $form->{makemodel_rows} = $i - 1;
192
193     }
194   }
195
196   # get translations
197   $form->{language_values} = "";
198   $query = qq|SELECT language_id, translation FROM translation WHERE parts_id = $form->{id}|;
199   $trq = $dbh->prepare($query);
200   $trq->execute || $form->dberror($query);
201   while ($tr = $trq->fetchrow_hashref(NAME_lc)) {
202     $form->{language_values} .= "---+++---".$tr->{language_id}."--++--".$tr->{translation};
203   }
204   $trq->finish;
205
206   # now get accno for taxes
207   $query = qq|SELECT c.accno
208               FROM chart c, partstax pt
209               WHERE pt.chart_id = c.id
210               AND pt.parts_id = $form->{id}|;
211
212   $sth = $dbh->prepare($query);
213   $sth->execute || $form->dberror($query);
214
215   while (($key) = $sth->fetchrow_array) {
216     $form->{amount}{$key} = $key;
217   }
218
219   $sth->finish;
220
221   # is it an orphan
222   $query = qq|SELECT i.parts_id
223               FROM invoice i
224               WHERE i.parts_id = $form->{id}
225             UNION
226               SELECT o.parts_id
227               FROM orderitems o
228               WHERE o.parts_id = $form->{id}
229             UNION
230               SELECT a.parts_id
231               FROM assembly a
232               WHERE a.parts_id = $form->{id}|;
233   $sth = $dbh->prepare($query);
234   $sth->execute || $form->dberror($query);
235
236   ($form->{orphaned}) = $sth->fetchrow_array;
237   $form->{orphaned} = !$form->{orphaned};
238   $sth->finish;
239
240   $form->{"unit_changeable"} = 1;
241   foreach my $table (qw(invoice assembly orderitems inventory license)) {
242     $query = "SELECT COUNT(*) FROM $table WHERE parts_id = ?";
243     my ($count) = $dbh->selectrow_array($query, undef, $form->{"id"});
244     $form->dberror($query . " (" . $form->{"id"} . ")") if ($dbh->err);
245
246     if ($count) {
247       $form->{"unit_changeable"} = 0;
248       last;
249     }
250   }
251
252   $dbh->disconnect;
253
254   $main::lxdebug->leave_sub();
255 }
256
257 sub get_pricegroups {
258   $main::lxdebug->enter_sub();
259
260   my ($self, $myconfig, $form) = @_;
261   my $dbh                  = $form->dbconnect($myconfig);
262   my $i                    = 1;
263   my @pricegroups_not_used = ();
264
265   # get pricegroups
266   my $query = qq|SELECT p.id, p.pricegroup FROM pricegroup p|;
267
268   my $pkq = $dbh->prepare($query);
269   $pkq->execute || $form->dberror($query);
270   while ($pkr = $pkq->fetchrow_hashref(NAME_lc)) {
271     push @{ $form->{PRICEGROUPS} }, $pkr;
272   }
273   $pkq->finish;
274
275   #find not used pricegroups
276   while ($tmp = pop @{ $form->{PRICEGROUPS} }) {
277     push @pricegroups_not_used, $tmp;
278   }
279
280   # if not used pricegroups are avaible
281   if (@pricegroups_not_used) {
282
283     foreach $name (@pricegroups_not_used) {
284       $form->{"klass_$i"} = "$name->{id}";
285       $form->{"price_$i"} = $form->round_amount($form->{sellprice}, 5);
286       $form->{"price_$i"} =
287         $form->format_amount($myconfig, $form->{"price_$i"}, 5);
288       $form->{"pricegroup_id_$i"} = "$name->{id}";
289       $form->{"pricegroup_$i"}    = "$name->{pricegroup}";
290       $i++;
291     }
292   }
293
294   #correct rows
295   $form->{price_rows} = $i - 1;
296
297   $dbh->disconnect;
298
299   $main::lxdebug->leave_sub();
300 }
301
302 sub retrieve_buchungsgruppen {
303   $main::lxdebug->enter_sub();
304
305   my ($self, $myconfig, $form) = @_;
306
307   my ($query, $sth);
308
309   my $dbh = $form->dbconnect($myconfig);
310
311   # get buchungsgruppen
312   $query = qq|SELECT id, description
313               FROM buchungsgruppen|;
314   $sth = $dbh->prepare($query);
315   $sth->execute || $form->dberror($query);
316
317   $form->{BUCHUNGSGRUPPEN} = [];
318   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
319     push(@{ $form->{BUCHUNGSGRUPPEN} }, $ref);
320   }
321   $sth->finish;
322
323   $main::lxdebug->leave_sub();
324 }
325
326 sub save {
327   $main::lxdebug->enter_sub();
328
329   my ($self, $myconfig, $form) = @_;
330   $form->{IC_expense} = "1000";
331   $form->{IC_income} = "2000";
332
333   if ($form->{item} ne 'service') {
334     $form->{IC} = $form->{IC_expense};
335   }
336
337   ($form->{inventory_accno}) = split(/--/, $form->{IC});
338   ($form->{expense_accno})   = split(/--/, $form->{IC_expense});
339   ($form->{income_accno})    = split(/--/, $form->{IC_income});
340
341   # connect to database, turn off AutoCommit
342   my $dbh = $form->dbconnect_noauto($myconfig);
343
344   # save the part
345   # make up a unique handle and store in partnumber field
346   # then retrieve the record based on the unique handle to get the id
347   # replace the partnumber field with the actual variable
348   # add records for makemodel
349
350   # if there is a $form->{id} then replace the old entry
351   # delete all makemodel entries and add the new ones
352
353   # escape '
354   map { $form->{$_} =~ s/\'/\'\'/g } qw(partnumber description notes unit);
355
356   # undo amount formatting
357   map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
358     qw(rop weight listprice sellprice gv lastcost stock);
359
360   # set date to NULL if nothing entered
361   $form->{priceupdate} =
362     ($form->{priceupdate}) ? qq|'$form->{priceupdate}'| : "NULL";
363
364   $form->{makemodel} = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
365
366   $form->{alternate} = 0;
367   $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
368   $form->{obsolete} *= 1;
369   $form->{shop}     *= 1;
370   $form->{onhand}   *= 1;
371   $form->{ve}       *= 1;
372   $form->{ge}       *= 1;
373   $form->{buchungsgruppen_id}       *= 1;
374   $form->{not_discountable}       *= 1;
375   $form->{payment_id}       *= 1;
376
377   my ($query, $sth);
378
379   if ($form->{id}) {
380
381     # get old price
382     $query = qq|SELECT p.sellprice, p.weight
383                 FROM parts p
384                 WHERE p.id = $form->{id}|;
385     $sth = $dbh->prepare($query);
386     $sth->execute || $form->dberror($query);
387     my ($sellprice, $weight) = $sth->fetchrow_array;
388     $sth->finish;
389
390     # if item is part of an assembly adjust all assemblies
391     $query = qq|SELECT a.id, a.qty
392                 FROM assembly a
393                 WHERE a.parts_id = $form->{id}|;
394     $sth = $dbh->prepare($query);
395     $sth->execute || $form->dberror($query);
396     while (my ($id, $qty) = $sth->fetchrow_array) {
397       &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
398     }
399     $sth->finish;
400
401     if ($form->{item} ne 'service') {
402
403       # delete makemodel records
404       $query = qq|DELETE FROM makemodel
405                   WHERE parts_id = $form->{id}|;
406       $dbh->do($query) || $form->dberror($query);
407     }
408
409     if ($form->{item} eq 'assembly') {
410       if ($form->{onhand} != 0) {
411         &adjust_inventory($dbh, $form, $form->{id}, $form->{onhand} * -1);
412       }
413
414       # delete assembly records
415       $query = qq|DELETE FROM assembly
416                   WHERE id = $form->{id}|;
417       $dbh->do($query) || $form->dberror($query);
418
419       $form->{onhand} += $form->{stock};
420     }
421
422     # delete tax records
423     $query = qq|DELETE FROM partstax
424                 WHERE parts_id = $form->{id}|;
425     $dbh->do($query) || $form->dberror($query);
426
427     # delete translations
428     $query = qq|DELETE FROM translation
429                 WHERE parts_id = $form->{id}|;
430     $dbh->do($query) || $form->dberror($query);
431
432   } else {
433     my $uid = rand() . time;
434     $uid .= $form->{login};
435
436     $query = qq|SELECT p.id FROM parts p
437                 WHERE p.partnumber = '$form->{partnumber}'|;
438     $sth = $dbh->prepare($query);
439     $sth->execute || $form->dberror($query);
440     ($form->{id}) = $sth->fetchrow_array;
441     $sth->finish;
442
443     if ($form->{id} ne "") {
444       $main::lxdebug->leave_sub();
445       return 3;
446     }
447     $query = qq|INSERT INTO parts (partnumber, description)
448                 VALUES ('$uid', 'dummy')|;
449     $dbh->do($query) || $form->dberror($query);
450
451     $query = qq|SELECT p.id FROM parts p
452                 WHERE p.partnumber = '$uid'|;
453     $sth = $dbh->prepare($query);
454     $sth->execute || $form->dberror($query);
455
456     ($form->{id}) = $sth->fetchrow_array;
457     $sth->finish;
458
459     $form->{orphaned} = 1;
460     $form->{onhand} = $form->{stock} if $form->{item} eq 'assembly';
461     if ($form->{partnumber} eq "" && $form->{inventory_accno} eq "") {
462       $form->{partnumber} = $form->update_defaults($myconfig, "servicenumber");
463     }
464     if ($form->{partnumber} eq "" && $form->{inventory_accno} ne "") {
465       $form->{partnumber} = $form->update_defaults($myconfig, "articlenumber");
466     }
467
468   }
469   my $partsgroup_id = 0;
470
471   if ($form->{partsgroup}) {
472     ($partsgroup, $partsgroup_id) = split /--/, $form->{partsgroup};
473   }
474
475   $query = qq|UPDATE parts SET
476               partnumber = '$form->{partnumber}',
477               description = '$form->{description}',
478               makemodel = '$form->{makemodel}',
479               alternate = '$form->{alternate}',
480               assembly = '$form->{assembly}',
481               listprice = $form->{listprice},
482               sellprice = $form->{sellprice},
483               lastcost = $form->{lastcost},
484               weight = $form->{weight},
485               priceupdate = $form->{priceupdate},
486               unit = '$form->{unit}',
487               notes = '$form->{notes}',
488               formel = '$form->{formel}',
489               rop = $form->{rop},
490               bin = '$form->{bin}',
491               buchungsgruppen_id = '$form->{buchungsgruppen_id}',
492               payment_id = '$form->{payment_id}',
493               inventory_accno_id = (SELECT c.id FROM chart c
494                                     WHERE c.accno = '$form->{inventory_accno}'),
495               income_accno_id = (SELECT c.id FROM chart c
496                                  WHERE c.accno = '$form->{income_accno}'),
497               expense_accno_id = (SELECT c.id FROM chart c
498                                   WHERE c.accno = '$form->{expense_accno}'),
499               obsolete = '$form->{obsolete}',
500               image = '$form->{image}',
501               drawing = '$form->{drawing}',
502               shop = '$form->{shop}',
503               ve = '$form->{ve}',
504               gv = '$form->{gv}',
505               ean = '$form->{ean}',
506               not_discountable = '$form->{not_discountable}',
507               microfiche = '$form->{microfiche}',
508               partsgroup_id = $partsgroup_id
509               WHERE id = $form->{id}|;
510   $dbh->do($query) || $form->dberror($query);
511
512   # delete translation records
513   $query = qq|DELETE FROM translation
514               WHERE parts_id = $form->{id}|;
515   $dbh->do($query) || $form->dberror($query);
516
517   if ($form->{language_values} ne "") {
518     split /---\+\+\+---/,$form->{language_values};
519     foreach $item (@_) {
520       my ($language_id, $translation, $longdescription) = split /--\+\+--/, $item;
521       if ($translation ne "") {
522         $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription) VALUES
523                     ($form->{id}, $language_id, | . $dbh->quote($translation) . qq|, | . $dbh->quote($longdescription) . qq| )|;
524         $dbh->do($query) || $form->dberror($query);
525       }
526     }
527   }
528   # delete price records
529   $query = qq|DELETE FROM prices
530               WHERE parts_id = $form->{id}|;
531   $dbh->do($query) || $form->dberror($query);
532   # insert price records only if different to sellprice
533   for my $i (1 .. $form->{price_rows}) {
534     if ($form->{"price_$i"} eq "0") {
535       $form->{"price_$i"} = $form->{sellprice};
536     }
537     if (
538         (   $form->{"price_$i"}
539          || $form->{"klass_$i"}
540          || $form->{"pricegroup_id_$i"})
541         and $form->{"price_$i"} != $form->{sellprice}
542       ) {
543       $klass = $form->parse_amount($myconfig, $form->{"klass_$i"});
544       $price = $form->parse_amount($myconfig, $form->{"price_$i"});
545       $pricegroup_id =
546         $form->parse_amount($myconfig, $form->{"pricegroup_id_$i"});
547       $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price)
548                   VALUES($form->{id},$pricegroup_id,$price)|;
549       $dbh->do($query) || $form->dberror($query);
550     }
551   }
552
553   # insert makemodel records
554   unless ($form->{item} eq 'service') {
555     for my $i (1 .. $form->{makemodel_rows}) {
556       if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
557         map { $form->{"${_}_$i"} =~ s/\'/\'\'/g } qw(make model);
558
559         $query = qq|INSERT INTO makemodel (parts_id, make, model)
560                     VALUES ($form->{id},
561                     '$form->{"make_$i"}', '$form->{"model_$i"}')|;
562         $dbh->do($query) || $form->dberror($query);
563       }
564     }
565   }
566
567   # insert taxes
568   foreach $item (split / /, $form->{taxaccounts}) {
569     if ($form->{"IC_tax_$item"}) {
570       $query = qq|INSERT INTO partstax (parts_id, chart_id)
571                   VALUES ($form->{id},
572                           (SELECT c.id
573                            FROM chart c
574                            WHERE c.accno = '$item'))|;
575       $dbh->do($query) || $form->dberror($query);
576     }
577   }
578
579   # add assembly records
580   if ($form->{item} eq 'assembly') {
581
582     for my $i (1 .. $form->{assembly_rows}) {
583       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
584
585       if ($form->{"qty_$i"} != 0) {
586         $form->{"bom_$i"} *= 1;
587         $query = qq|INSERT INTO assembly (id, parts_id, qty, bom)
588                     VALUES ($form->{id}, $form->{"id_$i"},
589                     $form->{"qty_$i"}, '$form->{"bom_$i"}')|;
590         $dbh->do($query) || $form->dberror($query);
591       }
592     }
593
594     # adjust onhand for the parts
595     if ($form->{onhand} != 0) {
596       &adjust_inventory($dbh, $form, $form->{id}, $form->{onhand});
597     }
598
599     @a = localtime;
600     $a[5] += 1900;
601     $a[4]++;
602     my $shippingdate = "$a[5]-$a[4]-$a[3]";
603
604     $form->get_employee($dbh);
605
606     # add inventory record
607     $query = qq|INSERT INTO inventory (warehouse_id, parts_id, qty,
608                 shippingdate, employee_id) VALUES (
609                 0, $form->{id}, $form->{stock}, '$shippingdate',
610                 $form->{employee_id})|;
611     $dbh->do($query) || $form->dberror($query);
612
613   }
614
615   #set expense_accno=inventory_accno if they are different => bilanz
616   $vendor_accno =
617     ($form->{expense_accno} != $form->{inventory_accno})
618     ? $form->{inventory_accno}
619     : $form->{expense_accno};
620
621   # get tax rates and description
622   $accno_id =
623     ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
624   $query = qq|SELECT c.accno, c.description, t.rate, t.taxnumber
625               FROM chart c, tax t
626               WHERE c.id=t.chart_id AND t.taxkey in (SELECT taxkey_id from chart where accno = '$accno_id')
627               ORDER BY c.accno|;
628   $stw = $dbh->prepare($query);
629
630   $stw->execute || $form->dberror($query);
631
632   $form->{taxaccount} = "";
633   while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
634
635     #    if ($customertax{$ref->{accno}}) {
636     $form->{taxaccount} .= "$ptr->{accno} ";
637     if (!($form->{taxaccount2} =~ /$ptr->{accno}/)) {
638       $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
639       $form->{"$ptr->{accno}_description"} = $ptr->{description};
640       $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
641       $form->{taxaccount2} .= " $ptr->{accno} ";
642     }
643
644   }
645
646   # commit
647   my $rc = $dbh->commit;
648   $dbh->disconnect;
649
650   $main::lxdebug->leave_sub();
651
652   return $rc;
653 }
654
655 sub update_assembly {
656   $main::lxdebug->enter_sub();
657
658   my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
659
660   my $query = qq|SELECT a.id, a.qty
661                  FROM assembly a
662                  WHERE a.parts_id = $id|;
663   my $sth = $dbh->prepare($query);
664   $sth->execute || $form->dberror($query);
665
666   while (my ($pid, $aqty) = $sth->fetchrow_array) {
667     &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
668   }
669   $sth->finish;
670
671   $query = qq|UPDATE parts
672               SET sellprice = sellprice +
673                   $qty * ($form->{sellprice} - $sellprice),
674                   weight = weight +
675                   $qty * ($form->{weight} - $weight)
676               WHERE id = $id|;
677   $dbh->do($query) || $form->dberror($query);
678
679   $main::lxdebug->leave_sub();
680 }
681
682 sub retrieve_assemblies {
683   $main::lxdebug->enter_sub();
684
685   my ($self, $myconfig, $form) = @_;
686
687   # connect to database
688   my $dbh = $form->dbconnect($myconfig);
689
690   my $where = '1 = 1';
691
692   if ($form->{partnumber}) {
693     my $partnumber = $form->like(lc $form->{partnumber});
694     $where .= " AND lower(p.partnumber) LIKE '$partnumber'";
695   }
696
697   if ($form->{description}) {
698     my $description = $form->like(lc $form->{description});
699     $where .= " AND lower(p.description) LIKE '$description'";
700   }
701   $where .= " AND NOT p.obsolete = '1'";
702
703   # retrieve assembly items
704   my $query = qq|SELECT p.id, p.partnumber, p.description,
705                  p.bin, p.onhand, p.rop,
706                    (SELECT sum(p2.inventory_accno_id)
707                     FROM parts p2, assembly a
708                     WHERE p2.id = a.parts_id
709                     AND a.id = p.id) AS inventory
710                  FROM parts p
711                  WHERE $where
712                  AND assembly = '1'|;
713
714   my $sth = $dbh->prepare($query);
715   $sth->execute || $form->dberror($query);
716
717   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
718     push @{ $form->{assembly_items} }, $ref if $ref->{inventory};
719   }
720   $sth->finish;
721
722   $dbh->disconnect;
723
724   $main::lxdebug->leave_sub();
725 }
726
727 sub restock_assemblies {
728   $main::lxdebug->enter_sub();
729
730   my ($self, $myconfig, $form) = @_;
731
732   # connect to database
733   my $dbh = $form->dbconnect_noauto($myconfig);
734
735   for my $i (1 .. $form->{rowcount}) {
736
737     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
738
739     if ($form->{"qty_$i"} != 0) {
740       &adjust_inventory($dbh, $form, $form->{"id_$i"}, $form->{"qty_$i"});
741     }
742
743   }
744
745   my $rc = $dbh->commit;
746   $dbh->disconnect;
747
748   $main::lxdebug->leave_sub();
749
750   return $rc;
751 }
752
753 sub adjust_inventory {
754   $main::lxdebug->enter_sub();
755
756   my ($dbh, $form, $id, $qty) = @_;
757
758   my $query = qq|SELECT p.id, p.inventory_accno_id, p.assembly, a.qty
759                  FROM parts p, assembly a
760                  WHERE a.parts_id = p.id
761                  AND a.id = $id|;
762   my $sth = $dbh->prepare($query);
763   $sth->execute || $form->dberror($query);
764
765   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
766
767     my $allocate = $qty * $ref->{qty};
768
769     # is it a service item, then loop
770     $ref->{inventory_accno_id} *= 1;
771     next if (($ref->{inventory_accno_id} == 0) && !$ref->{assembly});
772
773     # adjust parts onhand
774     $form->update_balance($dbh, "parts", "onhand",
775                           qq|id = $ref->{id}|,
776                           $allocate * -1);
777   }
778
779   $sth->finish;
780
781   # update assembly
782   my $rc = $form->update_balance($dbh, "parts", "onhand", qq|id = $id|, $qty);
783
784   $main::lxdebug->leave_sub();
785
786   return $rc;
787 }
788
789 sub delete {
790   $main::lxdebug->enter_sub();
791
792   my ($self, $myconfig, $form) = @_;
793
794   # connect to database, turn off AutoCommit
795   my $dbh = $form->dbconnect_noauto($myconfig);
796
797   # first delete prices of pricegroup 
798   my $query = qq|DELETE FROM prices
799            WHERE parts_id = $form->{id}|;
800   $dbh->do($query) || $form->dberror($query);
801
802   my $query = qq|DELETE FROM parts
803                  WHERE id = $form->{id}|;
804   $dbh->do($query) || $form->dberror($query);
805
806   $query = qq|DELETE FROM partstax
807               WHERE parts_id = $form->{id}|;
808   $dbh->do($query) || $form->dberror($query);
809
810   # check if it is a part, assembly or service
811   if ($form->{item} ne 'service') {
812     $query = qq|DELETE FROM makemodel
813                 WHERE parts_id = $form->{id}|;
814     $dbh->do($query) || $form->dberror($query);
815   }
816
817   if ($form->{item} eq 'assembly') {
818
819     # delete inventory
820     $query = qq|DELETE FROM inventory
821                 WHERE parts_id = $form->{id}|;
822     $dbh->do($query) || $form->dberror($query);
823
824     $query = qq|DELETE FROM assembly
825                 WHERE id = $form->{id}|;
826     $dbh->do($query) || $form->dberror($query);
827   }
828
829   if ($form->{item} eq 'alternate') {
830     $query = qq|DELETE FROM alternate
831                 WHERE id = $form->{id}|;
832     $dbh->do($query) || $form->dberror($query);
833   }
834
835   # commit
836   my $rc = $dbh->commit;
837   $dbh->disconnect;
838
839   $main::lxdebug->leave_sub();
840
841   return $rc;
842 }
843
844 sub assembly_item {
845   $main::lxdebug->enter_sub();
846
847   my ($self, $myconfig, $form) = @_;
848
849   my $i = $form->{assembly_rows};
850   my $var;
851   my $where = "1 = 1";
852
853   if ($form->{"partnumber_$i"}) {
854     $var = $form->like(lc $form->{"partnumber_$i"});
855     $where .= " AND lower(p.partnumber) LIKE '$var'";
856   }
857   if ($form->{"description_$i"}) {
858     $var = $form->like(lc $form->{"description_$i"});
859     $where .= " AND lower(p.description) LIKE '$var'";
860   }
861   if ($form->{"partsgroup_$i"}) {
862     $var = $form->like(lc $form->{"partsgroup_$i"});
863     $where .= " AND lower(pg.partsgroup) LIKE '$var'";
864   }
865
866   if ($form->{id}) {
867     $where .= " AND NOT p.id = $form->{id}";
868   }
869
870   if ($partnumber) {
871     $where .= " ORDER BY p.partnumber";
872   } else {
873     $where .= " ORDER BY p.description";
874   }
875
876   # connect to database
877   my $dbh = $form->dbconnect($myconfig);
878
879   my $query = qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
880                  p.weight, p.onhand, p.unit,
881                  pg.partsgroup
882                  FROM parts p
883                  LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
884                  WHERE $where|;
885   my $sth = $dbh->prepare($query);
886   $sth->execute || $form->dberror($query);
887
888   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
889     push @{ $form->{item_list} }, $ref;
890   }
891
892   $sth->finish;
893   $dbh->disconnect;
894
895   $main::lxdebug->leave_sub();
896 }
897
898 sub all_parts {
899   $main::lxdebug->enter_sub();
900
901   my ($self, $myconfig, $form) = @_;
902
903   my $where = '1 = 1';
904   my $var;
905
906   my $group;
907   my $limit;
908
909   foreach my $item (qw(partnumber drawing microfiche)) {
910     if ($form->{$item}) {
911       $var = $form->like(lc $form->{$item});
912       $where .= " AND lower(p.$item) LIKE '$var'";
913     }
914   }
915
916   # special case for description
917   if ($form->{description}) {
918     unless (   $form->{bought}
919             || $form->{sold}
920             || $form->{onorder}
921             || $form->{ordered}
922             || $form->{rfq}
923             || $form->{quoted}) {
924       $var = $form->like(lc $form->{description});
925       $where .= " AND lower(p.description) LIKE '$var'";
926     }
927   }
928
929   # special case for serialnumber
930   if ($form->{l_serialnumber}) {
931     if ($form->{serialnumber}) {
932       $var = $form->like(lc $form->{serialnumber});
933       $where .= " AND lower(serialnumber) LIKE '$var'";
934     }
935   }
936
937   if ($form->{ean}) {
938     $var = $form->like(lc $form->{ean});
939     $where .= " AND lower(ean) LIKE '$var'";
940   }
941   
942   if ($form->{searchitems} eq 'part') {
943     $where .= " AND p.inventory_accno_id > 0";
944   }
945   if ($form->{searchitems} eq 'assembly') {
946     $form->{bought} = "";
947     $where .= " AND p.assembly = '1'";
948   }
949   if ($form->{searchitems} eq 'service') {
950     $where .= " AND p.inventory_accno_id IS NULL AND NOT p.assembly = '1'";
951
952     # irrelevant for services
953     $form->{make} = $form->{model} = "";
954   }
955
956   # items which were never bought, sold or on an order
957   if ($form->{itemstatus} eq 'orphaned') {
958     $form->{onhand}  = $form->{short}   = 0;
959     $form->{bought}  = $form->{sold}    = 0;
960     $form->{onorder} = $form->{ordered} = 0;
961     $form->{rfq}     = $form->{quoted}  = 0;
962
963     $form->{transdatefrom} = $form->{transdateto} = "";
964
965     $where .= " AND p.onhand = 0
966                 AND p.id NOT IN (SELECT p.id FROM parts p, invoice i
967                                  WHERE p.id = i.parts_id)
968                 AND p.id NOT IN (SELECT p.id FROM parts p, assembly a
969                                  WHERE p.id = a.parts_id)
970                 AND p.id NOT IN (SELECT p.id FROM parts p, orderitems o
971                                  WHERE p.id = o.parts_id)";
972   }
973
974   if ($form->{itemstatus} eq 'active') {
975     $where .= " AND p.obsolete = '0'";
976   }
977   if ($form->{itemstatus} eq 'obsolete') {
978     $where .= " AND p.obsolete = '1'";
979     $form->{onhand} = $form->{short} = 0;
980   }
981   if ($form->{itemstatus} eq 'onhand') {
982     $where .= " AND p.onhand > 0";
983   }
984   if ($form->{itemstatus} eq 'short') {
985     $where .= " AND p.onhand < p.rop";
986   }
987   if ($form->{make}) {
988     $var = $form->like(lc $form->{make});
989     $where .= " AND p.id IN (SELECT DISTINCT ON (m.parts_id) m.parts_id
990                            FROM makemodel m WHERE lower(m.make) LIKE '$var')";
991   }
992   if ($form->{model}) {
993     $var = $form->like(lc $form->{model});
994     $where .= " AND p.id IN (SELECT DISTINCT ON (m.parts_id) m.parts_id
995                            FROM makemodel m WHERE lower(m.model) LIKE '$var')";
996   }
997   if ($form->{partsgroup}) {
998     $var = $form->like(lc $form->{partsgroup});
999     $where .= " AND lower(pg.partsgroup) LIKE '$var'";
1000   }
1001   if ($form->{l_soldtotal}) {
1002     $where .= " AND p.id=i.parts_id AND  i.qty >= 0";
1003     $group =
1004       " GROUP BY  p.id,p.partnumber,p.description,p.onhand,p.unit,p.bin, p.sellprice,p.listprice,p.lastcost,p.priceupdate,pg.partsgroup";
1005   }
1006   if ($form->{top100}) {
1007     $limit = " LIMIT 100";
1008   }
1009
1010   # tables revers?
1011   if ($form->{revers} == 1) {
1012     $form->{desc} = " DESC";
1013   } else {
1014     $form->{desc} = "";
1015   }
1016
1017   # connect to database
1018   my $dbh = $form->dbconnect($myconfig);
1019
1020   my $sortorder = $form->{sort};
1021   $sortorder .= $form->{desc};
1022   $sortorder = $form->{sort} if $form->{sort};
1023
1024   my $query = "";
1025
1026   if ($form->{l_soldtotal}) {
1027     $form->{soldtotal} = 'soldtotal';
1028     $query =
1029       qq|SELECT p.id,p.partnumber,p.description,p.onhand,p.unit,p.bin,p.sellprice,p.listprice,
1030                 p.lastcost,p.priceupdate,pg.partsgroup,sum(i.qty) as soldtotal FROM parts
1031                 p LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id), invoice i
1032                 WHERE $where
1033                 $group
1034                 ORDER BY $sortorder
1035                 $limit|;
1036   } else {
1037     $query = qq|SELECT p.id, p.partnumber, p.description, p.onhand, p.unit,
1038                  p.bin, p.sellprice, p.listprice, p.lastcost, p.rop, p.weight,
1039                  p.priceupdate, p.image, p.drawing, p.microfiche,
1040                  pg.partsgroup
1041                  FROM parts p
1042                  LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1043                  WHERE $where
1044                  $group
1045                  ORDER BY $sortorder|;
1046   }
1047
1048   # rebuild query for bought and sold items
1049   if (   $form->{bought}
1050       || $form->{sold}
1051       || $form->{onorder}
1052       || $form->{ordered}
1053       || $form->{rfq}
1054       || $form->{quoted}) {
1055
1056     my @a = qw(partnumber description bin priceupdate name);
1057
1058     push @a, qw(invnumber serialnumber) if ($form->{bought} || $form->{sold});
1059     push @a, "ordnumber" if ($form->{onorder} || $form->{ordered});
1060     push @a, "quonumber" if ($form->{rfq}     || $form->{quoted});
1061
1062     my $union = "";
1063     $query = "";
1064
1065     if ($form->{bought} || $form->{sold}) {
1066
1067       my $invwhere = "$where";
1068       $invwhere .= " AND i.assemblyitem = '0'";
1069       $invwhere .= " AND a.transdate >= '$form->{transdatefrom}'"
1070         if $form->{transdatefrom};
1071       $invwhere .= " AND a.transdate <= '$form->{transdateto}'"
1072         if $form->{transdateto};
1073
1074       if ($form->{description}) {
1075         $var = $form->like(lc $form->{description});
1076         $invwhere .= " AND lower(i.description) LIKE '$var'";
1077       }
1078
1079       my $flds = qq|p.id, p.partnumber, i.description, i.serialnumber,
1080                     i.qty AS onhand, i.unit, p.bin, i.sellprice,
1081                     p.listprice, p.lastcost, p.rop, p.weight,
1082                     p.priceupdate, p.image, p.drawing, p.microfiche,
1083                     pg.partsgroup,
1084                     a.invnumber, a.ordnumber, a.quonumber, i.trans_id,
1085                     ct.name, i.deliverydate|;
1086
1087       if ($form->{bought}) {
1088         $query = qq|
1089                     SELECT $flds, 'ir' AS module, '' AS type,
1090                     1 AS exchangerate
1091                     FROM invoice i
1092                     JOIN parts p ON (p.id = i.parts_id)
1093                     JOIN ap a ON (a.id = i.trans_id)
1094                     JOIN vendor ct ON (a.vendor_id = ct.id)
1095                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1096                     WHERE $invwhere|;
1097         $union = "
1098                   UNION";
1099       }
1100
1101       if ($form->{sold}) {
1102         $query .= qq|$union
1103                      SELECT $flds, 'is' AS module, '' AS type,
1104                      1 As exchangerate
1105                      FROM invoice i
1106                      JOIN parts p ON (p.id = i.parts_id)
1107                      JOIN ar a ON (a.id = i.trans_id)
1108                      JOIN customer ct ON (a.customer_id = ct.id)
1109                      LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1110                      WHERE $invwhere|;
1111         $union = "
1112                   UNION";
1113       }
1114     }
1115
1116     if ($form->{onorder} || $form->{ordered}) {
1117       my $ordwhere = "$where
1118                      AND o.quotation = '0'";
1119       $ordwhere .= " AND o.transdate >= '$form->{transdatefrom}'"
1120         if $form->{transdatefrom};
1121       $ordwhere .= " AND o.transdate <= '$form->{transdateto}'"
1122         if $form->{transdateto};
1123
1124       if ($form->{description}) {
1125         $var = $form->like(lc $form->{description});
1126         $ordwhere .= " AND lower(oi.description) LIKE '$var'";
1127       }
1128
1129       $flds =
1130         qq|p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
1131                  oi.qty AS onhand, oi.unit, p.bin, oi.sellprice,
1132                  p.listprice, p.lastcost, p.rop, p.weight,
1133                  p.priceupdate, p.image, p.drawing, p.microfiche,
1134                  pg.partsgroup,
1135                  '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
1136                  ct.name|;
1137
1138       if ($form->{ordered}) {
1139         $query .= qq|$union
1140                      SELECT $flds, 'oe' AS module, 'sales_order' AS type,
1141                     (SELECT buy FROM exchangerate ex
1142                      WHERE ex.curr = o.curr
1143                      AND ex.transdate = o.transdate) AS exchangerate
1144                      FROM orderitems oi
1145                      JOIN parts p ON (oi.parts_id = p.id)
1146                      JOIN oe o ON (oi.trans_id = o.id)
1147                      JOIN customer ct ON (o.customer_id = ct.id)
1148                      LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1149                      WHERE $ordwhere
1150                      AND o.customer_id > 0|;
1151         $union = "
1152                   UNION";
1153       }
1154
1155       if ($form->{onorder}) {
1156         $flds =
1157           qq|p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
1158                    oi.qty * -1 AS onhand, oi.unit, p.bin, oi.sellprice,
1159                    p.listprice, p.lastcost, p.rop, p.weight,
1160                    p.priceupdate, p.image, p.drawing, p.microfiche,
1161                    pg.partsgroup,
1162                    '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
1163                    ct.name|;
1164
1165         $query .= qq|$union
1166                     SELECT $flds, 'oe' AS module, 'purchase_order' AS type,
1167                     (SELECT sell FROM exchangerate ex
1168                      WHERE ex.curr = o.curr
1169                      AND ex.transdate = o.transdate) AS exchangerate
1170                     FROM orderitems oi
1171                     JOIN parts p ON (oi.parts_id = p.id)
1172                     JOIN oe o ON (oi.trans_id = o.id)
1173                     JOIN vendor ct ON (o.vendor_id = ct.id)
1174                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1175                     WHERE $ordwhere
1176                     AND o.vendor_id > 0|;
1177       }
1178
1179     }
1180
1181     if ($form->{rfq} || $form->{quoted}) {
1182       my $quowhere = "$where
1183                      AND o.quotation = '1'";
1184       $quowhere .= " AND o.transdate >= '$form->{transdatefrom}'"
1185         if $form->{transdatefrom};
1186       $quowhere .= " AND o.transdate <= '$form->{transdateto}'"
1187         if $form->{transdateto};
1188
1189       if ($form->{description}) {
1190         $var = $form->like(lc $form->{description});
1191         $quowhere .= " AND lower(oi.description) LIKE '$var'";
1192       }
1193
1194       $flds =
1195         qq|p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
1196                  oi.qty AS onhand, oi.unit, p.bin, oi.sellprice,
1197                  p.listprice, p.lastcost, p.rop, p.weight,
1198                  p.priceupdate, p.image, p.drawing, p.microfiche,
1199                  pg.partsgroup,
1200                  '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
1201                  ct.name|;
1202
1203       if ($form->{quoted}) {
1204         $query .= qq|$union
1205                      SELECT $flds, 'oe' AS module, 'sales_quotation' AS type,
1206                     (SELECT buy FROM exchangerate ex
1207                      WHERE ex.curr = o.curr
1208                      AND ex.transdate = o.transdate) AS exchangerate
1209                      FROM orderitems oi
1210                      JOIN parts p ON (oi.parts_id = p.id)
1211                      JOIN oe o ON (oi.trans_id = o.id)
1212                      JOIN customer ct ON (o.customer_id = ct.id)
1213                      LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1214                      WHERE $quowhere
1215                      AND o.customer_id > 0|;
1216         $union = "
1217                   UNION";
1218       }
1219
1220       if ($form->{rfq}) {
1221         $flds =
1222           qq|p.id, p.partnumber, oi.description, oi.serialnumber AS serialnumber,
1223                    oi.qty * -1 AS onhand, oi.unit, p.bin, oi.sellprice,
1224                    p.listprice, p.lastcost, p.rop, p.weight,
1225                    p.priceupdate, p.image, p.drawing, p.microfiche,
1226                    pg.partsgroup,
1227                    '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
1228                    ct.name|;
1229
1230         $query .= qq|$union
1231                     SELECT $flds, 'oe' AS module, 'request_quotation' AS type,
1232                     (SELECT sell FROM exchangerate ex
1233                      WHERE ex.curr = o.curr
1234                      AND ex.transdate = o.transdate) AS exchangerate
1235                     FROM orderitems oi
1236                     JOIN parts p ON (oi.parts_id = p.id)
1237                     JOIN oe o ON (oi.trans_id = o.id)
1238                     JOIN vendor ct ON (o.vendor_id = ct.id)
1239                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1240                     WHERE $quowhere
1241                     AND o.vendor_id > 0|;
1242       }
1243
1244     }
1245     $query .= qq|
1246                  ORDER BY $sortorder|;
1247
1248   }
1249   my $sth = $dbh->prepare($query);
1250   $sth->execute || $form->dberror($query);
1251
1252   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1253     push @{ $form->{parts} }, $ref;
1254   }
1255
1256   $sth->finish;
1257
1258   # include individual items for assemblies
1259   if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1260     foreach $item (@{ $form->{parts} }) {
1261       push @assemblies, $item;
1262       $query = qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1263                   p.unit, p.bin,
1264                   p.sellprice, p.listprice, p.lastcost,
1265                   p.rop, p.weight, p.priceupdate,
1266                   p.image, p.drawing, p.microfiche
1267                   FROM parts p, assembly a
1268                   WHERE p.id = a.parts_id
1269                   AND a.id = $item->{id}|;
1270
1271       $sth = $dbh->prepare($query);
1272       $sth->execute || $form->dberror($query);
1273
1274       while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1275         $ref->{assemblyitem} = 1;
1276         push @assemblies, $ref;
1277       }
1278       $sth->finish;
1279
1280       push @assemblies, { id => $item->{id} };
1281
1282     }
1283
1284     # copy assemblies to $form->{parts}
1285     @{ $form->{parts} } = @assemblies;
1286   }
1287
1288   $dbh->disconnect;
1289   $main::lxdebug->leave_sub();
1290 }
1291
1292 sub update_prices {
1293   $main::lxdebug->enter_sub();
1294
1295   my ($self, $myconfig, $form) = @_;
1296
1297   my $where = '1 = 1';
1298   my $var;
1299
1300   my $group;
1301   my $limit;
1302
1303   foreach my $item (qw(partnumber drawing microfiche make model)) {
1304     if ($form->{$item}) {
1305       $var = $form->like(lc $form->{$item});
1306
1307       # make will build later Bugfix 145
1308       if ($item ne 'make') {
1309         $where .= " AND lower(p.$item) LIKE '$var'";
1310       }
1311     }
1312   }
1313
1314   # special case for description
1315   if ($form->{description}) {
1316     unless (   $form->{bought}
1317             || $form->{sold}
1318             || $form->{onorder}
1319             || $form->{ordered}
1320             || $form->{rfq}
1321             || $form->{quoted}) {
1322       $var = $form->like(lc $form->{description});
1323       $where .= " AND lower(p.description) LIKE '$var'";
1324     }
1325   }
1326
1327   # special case for serialnumber
1328   if ($form->{l_serialnumber}) {
1329     if ($form->{serialnumber}) {
1330       $var = $form->like(lc $form->{serialnumber});
1331       $where .= " AND lower(serialnumber) LIKE '$var'";
1332     }
1333   }
1334
1335
1336   # items which were never bought, sold or on an order
1337   if ($form->{itemstatus} eq 'orphaned') {
1338     $form->{onhand}  = $form->{short}   = 0;
1339     $form->{bought}  = $form->{sold}    = 0;
1340     $form->{onorder} = $form->{ordered} = 0;
1341     $form->{rfq}     = $form->{quoted}  = 0;
1342
1343     $form->{transdatefrom} = $form->{transdateto} = "";
1344
1345     $where .= " AND p.onhand = 0
1346                 AND p.id NOT IN (SELECT p.id FROM parts p, invoice i
1347                                  WHERE p.id = i.parts_id)
1348                 AND p.id NOT IN (SELECT p.id FROM parts p, assembly a
1349                                  WHERE p.id = a.parts_id)
1350                 AND p.id NOT IN (SELECT p.id FROM parts p, orderitems o
1351                                  WHERE p.id = o.parts_id)";
1352   }
1353
1354   if ($form->{itemstatus} eq 'active') {
1355     $where .= " AND p.obsolete = '0'";
1356   }
1357   if ($form->{itemstatus} eq 'obsolete') {
1358     $where .= " AND p.obsolete = '1'";
1359     $form->{onhand} = $form->{short} = 0;
1360   }
1361   if ($form->{itemstatus} eq 'onhand') {
1362     $where .= " AND p.onhand > 0";
1363   }
1364   if ($form->{itemstatus} eq 'short') {
1365     $where .= " AND p.onhand < p.rop";
1366   }
1367   if ($form->{make}) {
1368     $var = $form->like(lc $form->{make});
1369     $where .= " AND p.id IN (SELECT DISTINCT ON (m.parts_id) m.parts_id
1370                            FROM makemodel m WHERE lower(m.make) LIKE '$var')";
1371   }
1372   if ($form->{model}) {
1373     $var = $form->like(lc $form->{model});
1374     $where .= " AND p.id IN (SELECT DISTINCT ON (m.parts_id) m.parts_id
1375                            FROM makemodel m WHERE lower(m.model) LIKE '$var')";
1376   }
1377   if ($form->{partsgroup}) {
1378     $var = $form->like(lc $form->{partsgroup});
1379     $where .= " AND lower(pg.partsgroup) LIKE '$var'";
1380   }
1381
1382
1383   # connect to database
1384   my $dbh = $form->dbconnect_noauto($myconfig);
1385
1386   if ($form->{"sellprice"} ne "") {
1387     my $update = "";
1388     my $faktor = $form->parse_amount($myconfig,$form->{"sellprice"});
1389     if ($form->{"sellprice_type"} eq "percent") {
1390       my $faktor = $form->parse_amount($myconfig,$form->{"sellprice"})/100 +1;
1391       $update = "sellprice* $faktor";
1392     } else {
1393       $update = "sellprice+$faktor";
1394     }
1395   
1396     $query = qq|UPDATE parts set sellprice=$update WHERE id IN (SELECT p.id
1397                   FROM parts p
1398                   LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1399                   WHERE $where)|;
1400     $dbh->do($query);
1401   }
1402
1403   if ($form->{"listprice"} ne "") {
1404     my $update = "";
1405     my $faktor = $form->parse_amount($myconfig,$form->{"listprice"});
1406     if ($form->{"listprice_type"} eq "percent") {
1407       my $faktor = $form->parse_amount($myconfig,$form->{"sellprice"})/100 +1;
1408       $update = "listprice* $faktor";
1409     } else {
1410       $update = "listprice+$faktor";
1411     }
1412   
1413     $query = qq|UPDATE parts set listprice=$update WHERE id IN (SELECT p.id
1414                   FROM parts p
1415                   LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1416                   WHERE $where)|;
1417   
1418     $dbh->do($query);
1419   }
1420
1421
1422
1423
1424   for my $i (1 .. $form->{price_rows}) {
1425
1426     my $query = "";
1427     
1428   
1429     if ($form->{"price_$i"} ne "") {
1430       my $update = "";
1431       my $faktor = $form->parse_amount($myconfig,$form->{"price_$i"});
1432       if ($form->{"pricegroup_type_$i"} eq "percent") {
1433         my $faktor = $form->parse_amount($myconfig,$form->{"sellprice"})/100 +1;
1434         $update = "price* $faktor";
1435       } else {
1436         $update = "price+$faktor";
1437       }
1438     
1439       $query = qq|UPDATE prices set price=$update WHERE parts_id IN (SELECT p.id
1440                     FROM parts p
1441                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1442                     WHERE $where) AND pricegroup_id=$form->{"pricegroup_id_$i"}|;
1443     
1444       $dbh->do($query);
1445     }
1446   }
1447
1448
1449
1450   my $rc= $dbh->commit;
1451   $dbh->disconnect;
1452   $main::lxdebug->leave_sub();
1453
1454   return $rc;
1455 }
1456
1457 sub create_links {
1458   $main::lxdebug->enter_sub();
1459
1460   my ($self, $module, $myconfig, $form) = @_;
1461
1462   # connect to database
1463   my $dbh = $form->dbconnect($myconfig);
1464
1465   if ($form->{id}) {
1466     $query = qq|SELECT c.accno, c.description, c.link, c.id,
1467                         p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1468                         FROM chart c, parts p
1469                         WHERE c.link LIKE '%$module%'
1470                         AND p.id = $form->{id}
1471                         ORDER BY c.accno|;
1472   } else {
1473     $query = qq|SELECT c.accno, c.description, c.link, c.id,
1474                 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1475                 FROM chart c, defaults d
1476                 WHERE c.link LIKE '%$module%'
1477                 ORDER BY c.accno|;
1478   }
1479
1480   my $sth = $dbh->prepare($query);
1481   $sth->execute || $form->dberror($query);
1482   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1483     foreach my $key (split /:/, $ref->{link}) {
1484       if ($key =~ /$module/) {
1485         if (   ($ref->{id} eq $ref->{inventory_accno_id})
1486             || ($ref->{id} eq $ref->{income_accno_id})
1487             || ($ref->{id} eq $ref->{expense_accno_id})) {
1488           push @{ $form->{"${module}_links"}{$key} },
1489             { accno       => $ref->{accno},
1490               description => $ref->{description},
1491               selected    => "selected" };
1492           $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1493             } else {
1494           push @{ $form->{"${module}_links"}{$key} },
1495             { accno       => $ref->{accno},
1496               description => $ref->{description},
1497               selected    => "" };
1498         }
1499       }
1500     }
1501   }
1502   $sth->finish;
1503
1504   # get buchungsgruppen
1505   $query = qq|SELECT id, description
1506               FROM buchungsgruppen|;
1507   $sth = $dbh->prepare($query);
1508   $sth->execute || $form->dberror($query);
1509
1510   $form->{BUCHUNGSGRUPPEN} = [];
1511   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1512     push @{ $form->{BUCHUNGSGRUPPEN} }, $ref;
1513   }
1514   $sth->finish;
1515
1516   # get payment terms
1517   $query = qq|SELECT id, description
1518               FROM payment_terms
1519               ORDER BY 1|;
1520   $sth = $dbh->prepare($query);
1521   $sth->execute || $form->dberror($query);
1522
1523   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1524     push @{ $self->{payment_terms} }, $ref;
1525   }
1526   $sth->finish;
1527
1528   if (!$form->{id}) {
1529     $query = qq|SELECT current_date FROM defaults|;
1530     $sth = $dbh->prepare($query);
1531     $sth->execute || $form->dberror($query);
1532
1533     ($form->{priceupdate}) = $sth->fetchrow_array;
1534     $sth->finish;
1535   }
1536
1537   $dbh->disconnect;
1538   $main::lxdebug->leave_sub();
1539 }
1540
1541 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1542 sub get_parts {
1543   $main::lxdebug->enter_sub();
1544
1545   my ($self, $myconfig, $form, $sortorder) = @_;
1546   my $dbh   = $form->dbconnect($myconfig);
1547   my $order = " p.partnumber";
1548   my $where = "1 = 1";
1549
1550   if ($sortorder eq "all") {
1551     $where .= " AND p.partnumber LIKE '%$form->{partnumber}%'";
1552     $where .= " AND p.description LIKE '%$form->{description}%'";
1553   } else {
1554     if ($sortorder eq "partnumber") {
1555       $where .= " AND p.partnumber LIKE '%$form->{partnumber}%'";
1556       $order = qq|p.$sortorder|;
1557     }
1558     if ($sortorder eq "description") {
1559       $where .= " AND p.description LIKE '%$form->{description}%'";
1560     }
1561   }
1562
1563   my $query =
1564     qq|SELECT p.id, p.partnumber, p.description, p.unit, p.sellprice FROM parts p WHERE $where ORDER BY $order|;
1565   my $sth = $dbh->prepare($query);
1566   $sth->execute || $self->dberror($query);
1567   my $j = 0;
1568   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1569     if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1570     } else {
1571       $j++;
1572       $form->{"id_$j"}          = $ref->{id};
1573       $form->{"partnumber_$j"}  = $ref->{partnumber};
1574       $form->{"description_$j"} = $ref->{description};
1575       $form->{"unit_$j"}        = $ref->{unit};
1576       $form->{"sellprice_$j"}   = $ref->{sellprice};
1577       $form->{"soldtotal_$j"}   = get_soldtotal($dbh, $ref->{id});
1578     }    #fi
1579   }    #while
1580   $form->{rows} = $j;
1581   $sth->finish;
1582   $dbh->disconnect;
1583
1584   $main::lxdebug->leave_sub();
1585
1586   return $self;
1587 }    #end get_parts()
1588
1589 # gets sum of sold part with part_id
1590 sub get_soldtotal {
1591   $main::lxdebug->enter_sub();
1592
1593   my ($dbh, $id) = @_;
1594
1595   my $query =
1596     qq|SELECT sum(i.qty) as totalsold FROM invoice i WHERE i.parts_id = $id|;
1597
1598   my $sth = $dbh->prepare($query);
1599   $sth->execute || $form->dberror($query);
1600
1601   my $sum = 0;
1602   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1603
1604     $sum = $ref->{totalsold};
1605   }    #while
1606   $sth->finish;
1607
1608   if ($sum eq undef) {
1609     $sum = 0;
1610   }    #fi
1611
1612   $main::lxdebug->leave_sub();
1613
1614   return $sum;
1615 }    #end get_soldtotal
1616
1617 sub retrieve_item {
1618   $main::lxdebug->enter_sub();
1619
1620   my ($self, $myconfig, $form) = @_;
1621   my $i     = $form->{rowcount};
1622   my $where = "NOT p.obsolete = '1'";
1623
1624   if ($form->{"partnumber_$i"}) {
1625     my $partnumber = $form->like(lc $form->{"partnumber_$i"});
1626     $where .= " AND lower(p.partnumber) LIKE '$partnumber'";
1627   }
1628   if ($form->{"description_$i"}) {
1629     my $description = $form->like(lc $form->{"description_$i"});
1630     $where .= " AND lower(p.description) LIKE '$description'";
1631   }
1632
1633   if ($form->{"partsgroup_$i"}) {
1634     my $partsgroup = $form->like(lc $form->{"partsgroup_$i"});
1635     $where .= " AND lower(pg.partsgroup) LIKE '$partsgroup'";
1636   }
1637
1638   if ($form->{"description_$i"}) {
1639     $where .= " ORDER BY description";
1640   } else {
1641     $where .= " ORDER BY partnumber";
1642   }
1643
1644   # connect to database
1645   my $dbh = $form->dbconnect($myconfig);
1646
1647   my $query = qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
1648                         p.listprice,
1649                         c1.accno AS inventory_accno,
1650                         c2.accno AS income_accno,
1651                         c3.accno AS expense_accno,
1652                  p.unit, p.assembly, p.bin, p.onhand, p.notes AS partnotes,
1653                  pg.partsgroup
1654                  FROM parts p
1655                  LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
1656                  LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
1657                  LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
1658                  LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1659                  WHERE $where|;
1660   my $sth = $dbh->prepare($query);
1661   $sth->execute || $form->dberror($query);
1662
1663   #while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1664
1665   # get tax rates and description
1666   #$accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{inventory_accno};
1667   #$query = qq|SELECT c.accno, c.description, t.rate, t.taxnumber
1668   #           FROM chart c, tax t
1669   #           WHERE c.id=t.chart_id AND t.taxkey in (SELECT taxkey_id from chart where accno = '$accno_id')
1670   #           ORDER BY accno|;
1671   # $stw = $dbh->prepare($query);
1672   #$stw->execute || $form->dberror($query);
1673
1674   #$ref->{taxaccounts} = "";
1675   #while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1676
1677   #   $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1678   #  $form->{"$ptr->{accno}_description"} = $ptr->{description};
1679   #   $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1680   #   $form->{taxaccounts} .= "$ptr->{accno} ";
1681   #   $ref->{taxaccounts} .= "$ptr->{accno} ";
1682
1683   #}
1684
1685   #$stw->finish;
1686   #chop $ref->{taxaccounts};
1687
1688   push @{ $form->{item_list} }, $ref;
1689
1690   #}
1691   $sth->finish;
1692   $dbh->disconnect;
1693
1694   $main::lxdebug->leave_sub();
1695 }
1696
1697 sub retrieve_languages {
1698   $main::lxdebug->enter_sub();
1699
1700   my ($self, $myconfig, $form) = @_;
1701
1702   # connect to database
1703   my $dbh = $form->dbconnect($myconfig);
1704
1705   if ($form->{id}) {
1706     $where .= "tr.parts_id=$form->{id}";
1707   }
1708
1709
1710   if ($form->{language_values} ne "") {
1711   $query = qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1712                  FROM language l LEFT OUTER JOIN translation tr ON (tr.language_id=l.id AND $where)|;
1713   } else {
1714   $query = qq|SELECT l.id, l.description
1715                  FROM language l|;
1716   }
1717   my $sth = $dbh->prepare($query);
1718   $sth->execute || $form->dberror($query);
1719
1720   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1721     push(@{$languages}, $ref);
1722   }
1723   $sth->finish;
1724
1725   $dbh->disconnect;
1726
1727   $main::lxdebug->leave_sub();
1728   return $languages;
1729
1730 }
1731
1732 sub follow_account_chain {
1733   $main::lxdebug->enter_sub();
1734
1735   my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1736
1737   my @visited_accno_ids = ($accno_id);
1738
1739   my ($query, $sth);
1740
1741   $query =
1742     "SELECT c.new_chart_id, date($transdate) >= c.valid_from AS is_valid, " .
1743     "  cnew.accno " .
1744     "FROM chart c " .
1745     "LEFT JOIN chart cnew ON c.new_chart_id = cnew.id " .
1746     "WHERE (c.id = ?) AND NOT c.new_chart_id ISNULL AND (c.new_chart_id > 0)";
1747   $sth = $dbh->prepare($query);
1748
1749   while (1) {
1750     $sth->execute($accno_id) || $form->dberror($query . " ($accno_id)");
1751     $ref = $sth->fetchrow_hashref();
1752     last unless ($ref && $ref->{"is_valid"} &&
1753                  !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1754     $accno_id = $ref->{"new_chart_id"};
1755     $accno = $ref->{"accno"};
1756     push(@visited_accno_ids, $accno_id);
1757   }
1758
1759   $main::lxdebug->leave_sub();
1760
1761   return ($accno_id, $accno);
1762 }
1763
1764 sub retrieve_accounts {
1765   $main::lxdebug->enter_sub();
1766
1767   my ($self, $myconfig, $form, $parts_id, $index, $copy_accnos) = @_;
1768
1769   my ($query, $sth, $dbh);
1770
1771   $form->{"taxzone_id"} *= 1;
1772
1773   $dbh = $form->dbconnect($myconfig);
1774
1775   my $transdate = "";
1776   if ($form->{type} eq "invoice") {
1777     if (($form->{vc} eq "vendor") || !$form->{deliverydate}) {
1778       $transdate = $form->{invdate};
1779     } else {
1780       $transdate = $form->{deliverydate};
1781     }
1782   } elsif ($form->{type} eq "credit_note") {
1783     $transdate = $form->{invdate};
1784   } else {
1785     $transdate = $form->{transdate};
1786   }
1787
1788   if ($transdate eq "") {
1789     $transdate = "current_date";
1790   } else {
1791     $transdate = $dbh->quote($transdate);
1792   }
1793
1794   $query =
1795     "SELECT " .
1796     "  p.inventory_accno_id AS is_part, " .
1797     "  bg.inventory_accno_id, " .
1798     "  bg.income_accno_id_$form->{taxzone_id} AS income_accno_id, " .
1799     "  bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id, " .
1800     "  c1.accno AS inventory_accno, " .
1801     "  c2.accno AS income_accno, " .
1802     "  c3.accno AS expense_accno " .
1803     "FROM parts p " .
1804     "LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id " .
1805     "LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id " .
1806     "LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id " .
1807     "LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id " .
1808     "WHERE p.id = ?";
1809   $sth = $dbh->prepare($query);
1810   $sth->execute($parts_id) || $form->dberror($query . " ($parts_id)");
1811   my $ref = $sth->fetchrow_hashref();
1812   $sth->finish();
1813
1814 #   $main::lxdebug->message(0, "q $query");
1815
1816   if (!$ref) {
1817     $dbh->disconnect();
1818     return $main::lxdebug->leave_sub();
1819   }
1820
1821   $ref->{"inventory_accno_id"} = undef unless ($ref->{"is_part"});
1822
1823   my %accounts;
1824   foreach my $type (qw(inventory income expense)) {
1825     next unless ($ref->{"${type}_accno_id"});
1826     ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1827       $self->follow_account_chain($form, $dbh, $transdate,
1828                                   $ref->{"${type}_accno_id"},
1829                                   $ref->{"${type}_accno"});
1830   }
1831
1832   map({ $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} }
1833       qw(inventory income expense));
1834
1835   my $inc_exp = $form->{"vc"} eq "customer" ? "income" : "expense";
1836   my $accno_id = $accounts{"${inc_exp}_accno_id"};
1837
1838   $query =
1839     "SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber " .
1840     "FROM tax t " .
1841     "LEFT JOIN chart c ON c.id = t.chart_id " .
1842     "WHERE t.id IN " .
1843     "  (SELECT tk.tax_id " .
1844     "   FROM taxkeys tk " .
1845     "   WHERE tk.chart_id = $accno_id AND startdate <= $transdate " .
1846     "   ORDER BY startdate DESC LIMIT 1) ";
1847   $sth = $dbh->prepare($query);
1848   $sth->execute() || $form->dberror($query);
1849   $ref = $sth->fetchrow_hashref();
1850   $sth->finish();
1851   $dbh->disconnect();
1852
1853   unless ($ref) {
1854     $main::lxdebug->leave_sub();
1855     return;
1856   }
1857
1858   $form->{"taxaccounts_$index"} = $ref->{"accno"};
1859   if ($form->{"taxaccounts"} !~ /$ref->{accno}/) {
1860     $form->{"taxaccounts"} .= "$ref->{accno} ";
1861   }
1862   map({ $form->{"$ref->{accno}_${_}"} = $ref->{$_}; }
1863       qw(rate description taxnumber));
1864
1865 #   $main::lxdebug->message(0, "formvars: rate " . $form->{"$ref->{accno}_rate"} .
1866 #                           " description " . $form->{"$ref->{accno}_description"} .
1867 #                           " taxnumber " . $form->{"$ref->{accno}_taxnumber"} .
1868 #                           " || taxaccounts_$index " . $form->{"taxaccounts_$index"} .
1869 #                           " || taxaccounts " . $form->{"taxaccounts"});
1870
1871   $main::lxdebug->leave_sub();
1872 }
1873 1;