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