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