Bei Einkaufs- und Verkaufsmasken Felder für Angebots- und Auftragsdatum hinzugefügt.
[kivitendo-erp.git] / SL / IR.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 received module
32 #
33 #======================================================================
34
35 package IR;
36
37 use SL::AM;
38 use SL::DBUtils;
39
40 sub post_invoice {
41   $main::lxdebug->enter_sub();
42
43   my ($self, $myconfig, $form) = @_;
44
45   # connect to database, turn off autocommit
46   my $dbh = $form->dbconnect_noauto($myconfig);
47
48   my ($query, $sth, $null, $project_id);
49   my $exchangerate = 0;
50   my $allocated;
51   my $taxrate;
52   my $taxamount;
53   my $taxdiff;
54   my $item;
55
56   my $service_units = AM->retrieve_units($myconfig,$form,"service");
57   my $part_units = AM->retrieve_units($myconfig,$form,"dimension");
58
59   if ($form->{id}) {
60
61     &reverse_invoice($dbh, $form);
62
63   } else {
64     my $uid = rand() . time;
65
66     $uid .= $form->{login};
67
68     $uid = substr($uid, 2, 75);
69
70     $query = qq|INSERT INTO ap (invnumber, employee_id)
71                 VALUES ('$uid', (SELECT e.id FROM employee e
72                                  WHERE e.login = '$form->{login}'))|;
73     $dbh->do($query) || $form->dberror($query);
74
75     $query = qq|SELECT a.id FROM ap a
76                 WHERE a.invnumber = '$uid'|;
77     $sth = $dbh->prepare($query);
78     $sth->execute || $form->dberror($query);
79
80     ($form->{id}) = $sth->fetchrow_array;
81     $sth->finish;
82   }
83
84   ($null, $form->{contact_id}) = split /--/, $form->{contact};
85   $form->{contact_id} *= 1;
86
87   map { $form->{$_} =~ s/\'/\'\'/g } qw(invnumber ordnumber quonumber);
88
89   my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
90   my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
91
92   if ($form->{currency} eq $form->{defaultcurrency}) {
93     $form->{exchangerate} = 1;
94   } else {
95     $exchangerate =
96       $form->check_exchangerate($myconfig, $form->{currency},
97                                 $form->{transdate}, 'sell');
98   }
99
100   $form->{exchangerate} =
101     ($exchangerate)
102     ? $exchangerate
103     : $form->parse_amount($myconfig, $form->{exchangerate});
104
105   for my $i (1 .. $form->{rowcount}) {
106     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
107     
108     if ($form->{storno}) {
109       $form->{"qty_$i"} *= -1;
110     }
111
112     if ($main::eur) {
113       $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"};
114     }
115     
116     if ($form->{"id_$i"}) {
117
118       # get item baseunit
119       $query = qq|SELECT p.unit
120                   FROM parts p
121                   WHERE p.id = $form->{"id_$i"}|;
122       $sth = $dbh->prepare($query);
123       $sth->execute || $form->dberror($query);
124
125       my ($item_unit) = $sth->fetchrow_array();
126       $sth->finish;
127
128       if ($form->{"inventory_accno_$i"}) {
129         if (defined($part_units->{$item_unit}->{factor}) && $part_units->{$item_unit}->{factor} ne '' && $part_units->{$item_unit}->{factor} ne '0') {
130           $basefactor = $part_units->{$form->{"unit_$i"}}->{factor} / $part_units->{$item_unit}->{factor};
131         } else {
132           $basefactor = 1;
133         }
134         $baseqty = $form->{"qty_$i"} * $basefactor;
135       } else {
136         if (defined($service_units->{$item_unit}->{factor}) && $service_units->{$item_unit}->{factor} ne '' && $service_units->{$item_unit}->{factor} ne '0') {
137           $basefactor = $service_units->{$form->{"unit_$i"}}->{factor} / $service_units->{$item_unit}->{factor};
138         } else {
139           $basefactor = 1;
140         }
141         $baseqty = $form->{"qty_$i"} * $basefactor;
142       }
143
144       map { $form->{"${_}_$i"} =~ s/\'/\'\'/g }
145         qw(partnumber description unit);
146
147       @taxaccounts = split / /, $form->{"taxaccounts_$i"};
148       $taxdiff     = 0;
149       $allocated   = 0;
150       $taxrate     = 0;
151
152       $form->{"sellprice_$i"} =
153         $form->parse_amount($myconfig, $form->{"sellprice_$i"});
154       my $fxsellprice = $form->{"sellprice_$i"};
155
156       my ($dec) = ($fxsellprice =~ /\.(\d+)/);
157       $dec = length $dec;
158       my $decimalplaces = ($dec > 2) ? $dec : 2;
159
160       map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
161
162       if ($form->{"inventory_accno_$i"}) {
163
164         $linetotal =
165           $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
166
167         if ($form->{taxincluded}) {
168           $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
169           $form->{"sellprice_$i"} =
170             $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
171         } else {
172           $taxamount = $linetotal * $taxrate;
173         }
174
175         $netamount += $linetotal;
176
177         if ($form->round_amount($taxrate, 7) == 0) {
178           if ($form->{taxincluded}) {
179             foreach $item (@taxaccounts) {
180               $taxamount =
181                 $form->round_amount($linetotal * $form->{"${item}_rate"} /
182                                       (1 + abs($form->{"${item}_rate"})),
183                                     2);
184               $taxdiff += $taxamount;
185               $form->{amount}{ $form->{id} }{$item} -= $taxamount;
186             }
187             $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
188           } else {
189             map {
190               $form->{amount}{ $form->{id} }{$_} -=
191                 $linetotal * $form->{"${_}_rate"}
192             } @taxaccounts;
193           }
194         } else {
195           map {
196             $form->{amount}{ $form->{id} }{$_} -=
197               $taxamount * $form->{"${_}_rate"} / $taxrate
198           } @taxaccounts;
199         }
200
201         # add purchase to inventory, this one is without the tax!
202         $amount =
203           $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate};
204         $linetotal =
205           $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2) *
206           $form->{exchangerate};
207         $linetotal = $form->round_amount($linetotal, 2);
208
209         # this is the difference for the inventory
210         $invoicediff += ($amount - $linetotal);
211
212         $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -=
213           $linetotal;
214
215         # adjust and round sellprice
216         $form->{"sellprice_$i"} =
217           $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate},
218                               $decimalplaces);
219
220         # update parts table
221         $query = qq|UPDATE parts SET
222                     lastcost = $form->{"sellprice_$i"}
223                     WHERE id = $form->{"id_$i"}|;
224
225         $dbh->do($query) || $form->dberror($query);
226
227         $form->update_balance($dbh, "parts", "onhand",
228                               qq|id = $form->{"id_$i"}|,
229                               $baseqty)
230           unless $form->{shipped};
231
232         # check if we sold the item already and
233         # make an entry for the expense and inventory
234         $query = qq|SELECT i.id, i.qty, i.allocated, i.trans_id,
235                     p.inventory_accno_id, p.expense_accno_id, a.transdate
236                     FROM invoice i, ar a, parts p
237                     WHERE i.parts_id = p.id
238                     AND i.parts_id = $form->{"id_$i"}
239                     AND (i.base_qty + i.allocated) > 0
240                     AND i.trans_id = a.id
241                     ORDER BY transdate|;
242         $sth = $dbh->prepare($query);
243         $sth->execute || $form->dberror($query);
244
245         my $totalqty = $base_qty;
246
247         while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
248
249           my $qty = $ref->{base_qty} + $ref->{allocated};
250
251           if (($qty - $totalqty) > 0) {
252             $qty = $totalqty;
253           }
254
255           $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
256
257           if ($ref->{allocated} < 0) {
258
259             # we have an entry for it already, adjust amount
260             $form->update_balance(
261               $dbh,
262               "acc_trans",
263               "amount",
264               qq|trans_id = $ref->{trans_id} AND chart_id = $ref->{inventory_accno_id} AND transdate = '$ref->{transdate}'|,
265               $linetotal);
266
267             $form->update_balance(
268               $dbh,
269               "acc_trans",
270               "amount",
271               qq|trans_id = $ref->{trans_id} AND chart_id = $ref->{expense_accno_id} AND transdate = '$ref->{transdate}'|,
272               $linetotal * -1);
273
274           } else {
275
276             # add entry for inventory, this one is for the sold item
277             if ($linetotal != 0) {
278               $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
279                           transdate)
280                           VALUES ($ref->{trans_id}, $ref->{inventory_accno_id},
281                           $linetotal, '$ref->{transdate}')|;
282               $dbh->do($query) || $form->dberror($query);
283
284               # add expense
285               $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
286                           transdate, taxkey)
287                           VALUES ($ref->{trans_id}, $ref->{expense_accno_id},
288                           | . ($linetotal * -1) . qq|, '$ref->{transdate}',
289                           (SELECT taxkey from tax WHERE chart_id = $ref->{expense_accno_id}))|;
290               $dbh->do($query) || $form->dberror($query);
291             }
292           }
293
294           # update allocated for sold item
295           $form->update_balance($dbh, "invoice", "allocated",
296                                 qq|id = $ref->{id}|,
297                                 $qty * -1);
298
299           $allocated += $qty;
300
301           last if (($totalqty -= $qty) <= 0);
302         }
303
304         $sth->finish;
305
306         $lastinventoryaccno = $form->{"inventory_accno_$i"};
307
308       } else {
309
310         $linetotal =
311           $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
312
313         if ($form->{taxincluded}) {
314           $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
315
316           $form->{"sellprice_$i"} =
317             $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
318         } else {
319           $taxamount = $linetotal * $taxrate;
320         }
321
322         $netamount += $linetotal;
323
324         if ($form->round_amount($taxrate, 7) == 0) {
325           if ($form->{taxincluded}) {
326             foreach $item (@taxaccounts) {
327               $taxamount =
328                 $linetotal * $form->{"${item}_rate"} /
329                 (1 + abs($form->{"${item}_rate"}));
330               $totaltax += $taxamount;
331               $form->{amount}{ $form->{id} }{$item} -= $taxamount;
332             }
333           } else {
334             map {
335               $form->{amount}{ $form->{id} }{$_} -=
336                 $linetotal * $form->{"${_}_rate"}
337             } @taxaccounts;
338           }
339         } else {
340           map {
341             $form->{amount}{ $form->{id} }{$_} -=
342               $taxamount * $form->{"${_}_rate"} / $taxrate
343           } @taxaccounts;
344         }
345
346         $amount =
347           $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate};
348         $linetotal =
349           $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2) *
350           $form->{exchangerate};
351         $linetotal = $form->round_amount($linetotal, 2);
352
353         # this is the difference for expense
354         $expensediff += ($amount - $linetotal);
355
356         # add amount to expense
357         $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -=
358           $linetotal;
359
360         $lastexpenseaccno = $form->{"expense_accno_$i"};
361
362         # adjust and round sellprice
363         $form->{"sellprice_$i"} =
364           $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate},
365                               $decimalplaces);
366
367         # update lastcost
368         $query = qq|UPDATE parts SET
369                     lastcost = $form->{"sellprice_$i"}
370                     WHERE id = $form->{"id_$i"}|;
371
372         $dbh->do($query) || $form->dberror($query);
373
374       }
375
376       $project_id = 'NULL';
377       if ($form->{"projectnumber_$i"}) {
378         $project_id = $form->{"projectnumber_$i"};
379       }
380       $deliverydate =
381         ($form->{"deliverydate_$i"})
382         ? qq|'$form->{"deliverydate_$i"}'|
383         : "NULL";
384
385       # save detail record in invoice table
386       $query = qq|INSERT INTO invoice (trans_id, parts_id, description, qty, base_qty,
387                   sellprice, fxsellprice, allocated, unit, deliverydate,
388                   project_id, serialnumber)
389                   VALUES ($form->{id}, $form->{"id_$i"},
390                   '$form->{"description_$i"}', | . ($form->{"qty_$i"} * -1) . qq|,  | . ($baseqty * -1) . qq|,
391                   $form->{"sellprice_$i"}, $fxsellprice, $allocated,
392                   '$form->{"unit_$i"}', $deliverydate, (SELECT id FROM project WHERE projectnumber = '$project_id'),
393                   '$form->{"serialnumber_$i"}')|;
394       $dbh->do($query) || $form->dberror($query);
395     }
396   }
397
398   $form->{datepaid} = $form->{invdate};
399
400   # all amounts are in natural state, netamount includes the taxes
401   # if tax is included, netamount is rounded to 2 decimal places,
402   # taxes are not
403
404   # total payments
405   for my $i (1 .. $form->{paidaccounts}) {
406     $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
407     $form->{paid} += $form->{"paid_$i"};
408     $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"datepaid_$i"});
409   }
410
411   my ($tax, $paiddiff) = (0, 0);
412
413   $netamount = $form->round_amount($netamount, 2);
414
415   # figure out rounding errors for amount paid and total amount
416   if ($form->{taxincluded}) {
417
418     $amount    = $form->round_amount($netamount * $form->{exchangerate}, 2);
419     $paiddiff  = $amount - $netamount * $form->{exchangerate};
420     $netamount = $amount;
421
422     foreach $item (split / /, $form->{taxaccounts}) {
423       $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
424       $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
425       $amount = $form->{amount}{ $form->{id} }{$item} * -1;
426       $tax += $amount;
427       $netamount -= $amount;
428     }
429
430     $invoicediff += $paiddiff;
431     $expensediff += $paiddiff;
432
433     ######## this only applies to tax included
434     if ($lastinventoryaccno) {
435       $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff;
436     }
437     if ($lastexpenseaccno) {
438       $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff;
439     }
440
441   } else {
442     $amount    = $form->round_amount($netamount * $form->{exchangerate}, 2);
443     $paiddiff  = $amount - $netamount * $form->{exchangerate};
444     $netamount = $amount;
445     foreach my $item (split / /, $form->{taxaccounts}) {
446       $form->{amount}{ $form->{id} }{$item} =
447         $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
448       $amount =
449         $form->round_amount(
450             $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1,
451             2);
452       $paiddiff +=
453         $amount - $form->{amount}{ $form->{id} }{$item} *
454         $form->{exchangerate} * -1;
455       $form->{amount}{ $form->{id} }{$item} =
456         $form->round_amount($amount * -1, 2);
457       $amount = $form->{amount}{ $form->{id} }{$item} * -1;
458       $tax += $amount;
459     }
460   }
461
462   $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
463
464   if ($form->{paid} != 0) {
465     $form->{paid} =
466       $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff,
467                           2);
468   }
469
470   # update exchangerate
471   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
472     $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0,
473                                $form->{exchangerate});
474   }
475
476   # record acc_trans transactions
477   foreach my $trans_id (keys %{ $form->{amount} }) {
478     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
479       if (
480           ($form->{amount}{$trans_id}{$accno} =
481            $form->round_amount($form->{amount}{$trans_id}{$accno}, 2)
482           ) != 0
483         ) {
484         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
485                     transdate, taxkey)
486                     VALUES ($trans_id, (SELECT c.id FROM chart c
487                                          WHERE c.accno = '$accno'),
488                     $form->{amount}{$trans_id}{$accno}, '$form->{invdate}',
489                     (SELECT taxkey_id  FROM chart WHERE accno = '$accno'))|;
490         $dbh->do($query) || $form->dberror($query);
491       }
492     }
493   }
494
495   # deduct payment differences from paiddiff
496   for my $i (1 .. $form->{paidaccounts}) {
497     if ($form->{"paid_$i"} != 0) {
498       $amount =
499         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
500       $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
501     }
502   }
503
504   # force AP entry if 0
505   $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid}
506     if ($form->{amount}{ $form->{id} }{ $form->{AP} } == 0);
507
508   # record payments and offsetting AP
509   for my $i (1 .. $form->{paidaccounts}) {
510
511     if ($form->{"paid_$i"} != 0) {
512       my ($accno) = split /--/, $form->{"AP_paid_$i"};
513       $form->{"datepaid_$i"} = $form->{invdate}
514         unless ($form->{"datepaid_$i"});
515       $form->{datepaid} = $form->{"datepaid_$i"};
516
517       $amount = (
518                  $form->round_amount(
519                       $form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2
520                  )
521       ) * -1;
522
523       # record AP
524
525       if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
526         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
527                     transdate)
528                     VALUES ($form->{id}, (SELECT c.id FROM chart c
529                                         WHERE c.accno = '$form->{AP}'),
530                     $amount, '$form->{"datepaid_$i"}')|;
531         $dbh->do($query) || $form->dberror($query);
532       }
533
534       # record payment
535
536       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
537                   source, memo)
538                   VALUES ($form->{id}, (SELECT c.id FROM chart c
539                                       WHERE c.accno = '$accno'),
540                   $form->{"paid_$i"}, '$form->{"datepaid_$i"}',
541                   '$form->{"source_$i"}', '$form->{"memo_$i"}')|;
542       $dbh->do($query) || $form->dberror($query);
543
544       $exchangerate = 0;
545
546       if ($form->{currency} eq $form->{defaultcurrency}) {
547         $form->{"exchangerate_$i"} = 1;
548       } else {
549         $exchangerate =
550           $form->check_exchangerate($myconfig, $form->{currency},
551                                     $form->{"datepaid_$i"}, 'sell');
552
553         $form->{"exchangerate_$i"} =
554           ($exchangerate)
555           ? $exchangerate
556           : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
557       }
558
559       # exchangerate difference
560       $form->{fx}{$accno}{ $form->{"datepaid_$i"} } +=
561         $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
562
563       # gain/loss
564       $amount =
565         ($form->{"paid_$i"} * $form->{exchangerate}) -
566         ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
567       if ($amount > 0) {
568         $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } +=
569           $amount;
570       } else {
571         $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } +=
572           $amount;
573       }
574
575       $paiddiff = 0;
576
577       # update exchange rate
578       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
579         $form->update_exchangerate($dbh, $form->{currency},
580                                    $form->{"datepaid_$i"},
581                                    0, $form->{"exchangerate_$i"});
582       }
583     }
584   }
585
586   # record exchange rate differences and gains/losses
587   foreach my $accno (keys %{ $form->{fx} }) {
588     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
589       if (
590           ($form->{fx}{$accno}{$transdate} =
591            $form->round_amount($form->{fx}{$accno}{$transdate}, 2)
592           ) != 0
593         ) {
594
595         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
596                     transdate, cleared, fx_transaction)
597                     VALUES ($form->{id}, (SELECT c.id FROM chart c
598                                         WHERE c.accno = '$accno'),
599                     $form->{fx}{$accno}{$transdate}, '$transdate', '0', '1')|;
600         $dbh->do($query) || $form->dberror($query);
601       }
602     }
603   }
604
605   $amount = $netamount + $tax;
606
607   # set values which could be empty
608   $form->{taxincluded} *= 1;
609   my $datepaid = ($form->{paid})    ? qq|'$form->{datepaid}'| : "NULL";
610   my $duedate  = ($form->{duedate}) ? qq|'$form->{duedate}'|  : "NULL";
611
612   ($null, $form->{department_id}) = split(/--/, $form->{department});
613   $form->{department_id} *= 1;
614   $form->{payment_id} *= 1;
615   $form->{language_id} *= 1;
616   $form->{taxzone_id} *= 1;
617   $form->{storno} *= 1;
618
619
620   $form->{invnumber} = $form->{id} unless $form->{invnumber};
621
622   # save AP record
623   $query = qq|UPDATE ap set
624               invnumber = '$form->{invnumber}',
625               ordnumber = '$form->{ordnumber}',
626               quonumber = '$form->{quonumber}',
627               transdate = '$form->{invdate}',
628               orddate = | . conv_dateq($form->{"orddate"}) . qq|,
629               quodate = | . conv_dateq($form->{"quodate"}) . qq|,
630               vendor_id = $form->{vendor_id},
631               amount = $amount,
632               netamount = $netamount,
633               paid = $form->{paid},
634               datepaid = $datepaid,
635               duedate = $duedate,
636               invoice = '1',
637               taxzone_id = '$form->{taxzone_id}',
638               taxincluded = '$form->{taxincluded}',
639               notes = '$form->{notes}',
640               intnotes = '$form->{intnotes}',
641               curr = '$form->{currency}',
642               department_id = $form->{department_id},
643               storno = '$form->{storno}',
644               cp_id = $form->{contact_id}
645               WHERE id = $form->{id}|;
646   $dbh->do($query) || $form->dberror($query);
647
648   if ($form->{storno}) {
649     $query = qq| update ap set paid=paid+amount where id=$form->{storno_id}|;
650     $dbh->do($query) || $form->dberror($query);
651     $query = qq| update ap set storno='$form->{storno}' where id=$form->{storno_id}|;
652     $dbh->do($query) || $form->dberror($query);
653     $query = qq§ update ap set intnotes='Rechnung storniert am $form->{invdate} ' || intnotes where id=$form->{storno_id}§;
654     $dbh->do($query) || $form->dberror($query);
655
656     $query = qq| update ap set paid=amount where id=$form->{id}|;
657     $dbh->do($query) || $form->dberror($query);
658   }
659
660
661   # add shipto
662   $form->{name} = $form->{vendor};
663   $form->{name} =~ s/--$form->{vendor_id}//;
664   $form->add_shipto($dbh, $form->{id}, "AP");
665
666   # delete zero entries
667   $query = qq|DELETE FROM acc_trans
668               WHERE amount = 0|;
669   $dbh->do($query) || $form->dberror($query);
670
671   if ($form->{webdav}) {
672     &webdav_folder($myconfig, $form);
673   }
674
675   my $rc = $dbh->commit;
676   $dbh->disconnect;
677
678   $main::lxdebug->leave_sub();
679
680   return $rc;
681 }
682
683 sub reverse_invoice {
684   $main::lxdebug->enter_sub();
685
686   my ($dbh, $form) = @_;
687
688   # reverse inventory items
689   my $query = qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id,
690                  i.qty, i.allocated, i.sellprice
691                  FROM invoice i, parts p
692                  WHERE i.parts_id = p.id
693                  AND i.trans_id = $form->{id}|;
694   my $sth = $dbh->prepare($query);
695   $sth->execute || $form->dberror($query);
696
697   my $netamount = 0;
698
699   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
700     $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
701
702     if ($ref->{inventory_accno_id}) {
703
704       # update onhand
705       $form->update_balance($dbh, "parts", "onhand", qq|id = $ref->{parts_id}|,
706                             $ref->{qty});
707
708       # if $ref->{allocated} > 0 than we sold that many items
709       if ($ref->{allocated} > 0) {
710
711         # get references for sold items
712         $query = qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
713                     FROM invoice i, ar a
714                     WHERE i.parts_id = $ref->{parts_id}
715                     AND i.allocated < 0
716                     AND i.trans_id = a.id
717                     ORDER BY transdate DESC|;
718         my $sth = $dbh->prepare($query);
719         $sth->execute || $form->dberror($query);
720
721         while (my $pthref = $sth->fetchrow_hashref(NAME_lc)) {
722           my $qty = $ref->{allocated};
723           if (($ref->{allocated} + $pthref->{allocated}) > 0) {
724             $qty = $pthref->{allocated} * -1;
725           }
726
727           my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
728
729           #adjust allocated
730           $form->update_balance($dbh, "invoice", "allocated",
731                                 qq|id = $pthref->{id}|, $qty);
732
733           $form->update_balance(
734             $dbh,
735             "acc_trans",
736             "amount",
737             qq|trans_id = $pthref->{trans_id} AND chart_id = $ref->{expense_accno_id} AND transdate = '$pthref->{transdate}'|,
738             $amount);
739
740           $form->update_balance(
741             $dbh,
742             "acc_trans",
743             "amount",
744             qq|trans_id = $pthref->{trans_id} AND chart_id = $ref->{inventory_accno_id} AND transdate = '$pthref->{transdate}'|,
745             $amount * -1);
746
747           last if (($ref->{allocated} -= $qty) <= 0);
748         }
749         $sth->finish;
750       }
751     }
752   }
753   $sth->finish;
754
755   # delete acc_trans
756   $query = qq|DELETE FROM acc_trans
757               WHERE trans_id = $form->{id}|;
758   $dbh->do($query) || $form->dberror($query);
759
760   # delete invoice entries
761   $query = qq|DELETE FROM invoice
762               WHERE trans_id = $form->{id}|;
763   $dbh->do($query) || $form->dberror($query);
764
765   $query = qq|DELETE FROM shipto
766               WHERE trans_id = $form->{id} AND module = 'AP'|;
767   $dbh->do($query) || $form->dberror($query);
768
769   $main::lxdebug->leave_sub();
770 }
771
772 sub delete_invoice {
773   $main::lxdebug->enter_sub();
774
775   my ($self, $myconfig, $form) = @_;
776
777   # connect to database
778   my $dbh = $form->dbconnect_noauto($myconfig);
779
780   &reverse_invoice($dbh, $form);
781
782   # delete zero entries
783   my $query = qq|DELETE FROM acc_trans
784                  WHERE amount = 0|;
785   $dbh->do($query) || $form->dberror($query);
786
787   # delete AP record
788   my $query = qq|DELETE FROM ap
789                  WHERE id = $form->{id}|;
790   $dbh->do($query) || $form->dberror($query);
791
792   my $rc = $dbh->commit;
793   $dbh->disconnect;
794
795   $main::lxdebug->leave_sub();
796
797   return $rc;
798 }
799
800 sub retrieve_invoice {
801   $main::lxdebug->enter_sub();
802
803   my ($self, $myconfig, $form) = @_;
804
805   # connect to database
806   my $dbh = $form->dbconnect_noauto($myconfig);
807
808   my $query;
809
810   if ($form->{id}) {
811
812     # get default accounts and last invoice number
813     $query = qq|SELECT (SELECT c.accno FROM chart c
814                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
815                        (SELECT c.accno FROM chart c
816                         WHERE d.income_accno_id = c.id) AS income_accno,
817                        (SELECT c.accno FROM chart c
818                         WHERE d.expense_accno_id = c.id) AS expense_accno,
819                        (SELECT c.accno FROM chart c
820                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
821                        (SELECT c.accno FROM chart c
822                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
823                 d.curr AS currencies
824                 FROM defaults d|;
825   } else {
826     $query = qq|SELECT (SELECT c.accno FROM chart c
827                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
828                        (SELECT c.accno FROM chart c
829                         WHERE d.income_accno_id = c.id) AS income_accno,
830                        (SELECT c.accno FROM chart c
831                         WHERE d.expense_accno_id = c.id) AS expense_accno,
832                        (SELECT c.accno FROM chart c
833                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
834                        (SELECT c.accno FROM chart c
835                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
836                 d.curr AS currencies,
837                 current_date AS invdate
838                 FROM defaults d|;
839   }
840   my $sth = $dbh->prepare($query);
841   $sth->execute || $form->dberror($query);
842
843   my $ref = $sth->fetchrow_hashref(NAME_lc);
844   map { $form->{$_} = $ref->{$_} } keys %$ref;
845   $sth->finish;
846
847   if ($form->{id}) {
848
849     # retrieve invoice
850     $query = qq|SELECT a.cp_id, a.invnumber, a.transdate AS invdate, a.duedate,
851                 a.orddate, a.quodate,
852                 a.ordnumber, a.quonumber, a.paid, a.taxincluded, a.notes, a.taxzone_id, a.storno, a.gldate,
853                 a.intnotes, a.curr AS currency
854                 FROM ap a
855                 WHERE a.id = $form->{id}|;
856     $sth = $dbh->prepare($query);
857     $sth->execute || $form->dberror($query);
858
859     $ref = $sth->fetchrow_hashref(NAME_lc);
860     map { $form->{$_} = $ref->{$_} } keys %$ref;
861     $sth->finish;
862
863     $form->{exchangerate} =
864       $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate},
865                               "sell");
866
867     # get shipto
868     $query = qq|SELECT s.* FROM shipto s
869                 WHERE s.trans_id = $form->{id} AND s.module = 'AP'|;
870     $sth = $dbh->prepare($query);
871     $sth->execute || $form->dberror($query);
872
873     $ref = $sth->fetchrow_hashref(NAME_lc);
874     delete($ref->{id});
875     map { $form->{$_} = $ref->{$_} } keys %$ref;
876     $sth->finish;
877
878     my $transdate =
879       $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
880
881     if(!$form->{taxzone_id}) {
882       $form->{taxzone_id} = 0;
883     }
884     # retrieve individual items
885     $query = qq|SELECT c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
886                 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
887                 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
888                 p.partnumber, i.description, i.qty, i.fxsellprice AS sellprice, p.inventory_accno_id AS part_inventory_accno_id,
889                 i.parts_id AS id, i.unit, p.bin, i.deliverydate,
890                 pr.projectnumber,
891                 i.project_id, i.serialnumber,
892                 pg.partsgroup
893                 FROM invoice i
894                 JOIN parts p ON (i.parts_id = p.id)
895                 LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
896                 LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
897                 LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
898                 LEFT JOIN project pr ON (i.project_id = pr.id)
899                 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
900                 WHERE i.trans_id = $form->{id}
901                 ORDER BY i.id|;
902     $sth = $dbh->prepare($query);
903     $sth->execute || $form->dberror($query);
904
905     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
906       if (!$ref->{"part_inventory_accno_id"}) {
907         map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid));
908       }
909       delete($ref->{"part_inventory_accno_id"});
910
911       while ($ref->{inventory_new_chart} && ($ref->{inventory_valid} >=0)) {
912         my $query = qq| SELECT accno AS inventory_accno, new_chart_id AS inventory_new_chart, date($transdate) - valid_from AS inventory_valid FROM chart WHERE id = $ref->{inventory_new_chart}|;
913         my $stw = $dbh->prepare($query);
914         $stw->execute || $form->dberror($query);
915         ($ref->{inventory_accno}, $ref->{inventory_new_chart}, $ref->{inventory_valid}) = $stw->fetchrow_array;
916         $stw->finish;
917       }
918   
919       while ($ref->{income_new_chart} && ($ref->{income_valid} >=0)) {
920         my $query = qq| SELECT accno AS income_accno, new_chart_id AS income_new_chart, date($transdate) - valid_from AS income_valid FROM chart WHERE id = $ref->{income_new_chart}|;
921         my $stw = $dbh->prepare($query);
922         $stw->execute || $form->dberror($query);
923         ($ref->{income_accno}, $ref->{income_new_chart}, $ref->{income_valid}) = $stw->fetchrow_array;
924         $stw->finish;
925       }
926   
927       while ($ref->{expense_new_chart} && ($ref->{expense_valid} >=0)) {
928         my $query = qq| SELECT accno AS expense_accno, new_chart_id AS expense_new_chart, date($transdate) - valid_from AS expense_valid FROM chart WHERE id = $ref->{expense_new_chart}|;
929         my $stw = $dbh->prepare($query);
930         $stw->execute || $form->dberror($query);
931         ($ref->{expense_accno}, $ref->{expense_new_chart}, $ref->{expense_valid}) = $stw->fetchrow_array;
932         $stw->finish;
933       }
934
935       # get tax rates and description
936       $accno_id =
937         ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
938     $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
939               FROM tax t LEFT JOIN chart c on (c.id=t.chart_id)
940               WHERE t.id in (SELECT tk.tax_id from taxkeys tk where tk.chart_id = (SELECT id from chart WHERE accno='$accno_id') AND startdate<=$transdate ORDER BY startdate desc LIMIT 1)
941               ORDER BY c.accno|;
942       $stw = $dbh->prepare($query);
943       $stw->execute || $form->dberror($query);
944       $ref->{taxaccounts} = "";
945       my $i = 0;
946       while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
947
948         #    if ($customertax{$ref->{accno}}) {
949         if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
950           $i++;
951           $ptr->{accno} = $i;
952         }
953         $ref->{taxaccounts} .= "$ptr->{accno} ";
954         if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
955           $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
956           $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
957           $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
958           $form->{taxaccounts} .= "$ptr->{accno} ";
959         }
960
961       }
962
963       chop $ref->{taxaccounts};
964       push @{ $form->{invoice_details} }, $ref;
965       $stw->finish;
966     }
967     $sth->finish;
968
969     if ($form->{webdav}) {
970       &webdav_folder($myconfig, $form);
971     }
972
973   }
974
975   my $rc = $dbh->commit;
976   $dbh->disconnect;
977
978   $main::lxdebug->leave_sub();
979
980   return $rc;
981 }
982
983 sub get_vendor {
984   $main::lxdebug->enter_sub();
985
986   my ($self, $myconfig, $form) = @_;
987
988   # connect to database
989   my $dbh = $form->dbconnect($myconfig);
990
991   my $dateformat = $myconfig->{dateformat};
992   $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
993
994   my $duedate =
995     ($form->{invdate})
996     ? "to_date('$form->{invdate}', '$dateformat')"
997     : "current_date";
998
999   $form->{vendor_id} *= 1;
1000
1001   # get vendor
1002   my $query = qq|SELECT v.name AS vendor, v.creditlimit, v.terms,
1003                  v.email, v.cc, v.bcc, v.language_id, v.payment_id,
1004                  v.street, v.zipcode, v.city, v.country, v.taxzone_id,
1005                  $duedate + v.terms AS duedate
1006                  FROM vendor v
1007                  WHERE v.id = $form->{vendor_id}|;
1008   my $sth = $dbh->prepare($query);
1009   $sth->execute || $form->dberror($query);
1010
1011   $ref = $sth->fetchrow_hashref(NAME_lc);
1012   map { $form->{$_} = $ref->{$_} } keys %$ref;
1013   $sth->finish;
1014
1015   $form->{creditremaining} = $form->{creditlimit};
1016   $query = qq|SELECT SUM(a.amount - a.paid)
1017               FROM ap a
1018               WHERE a.vendor_id = $form->{vendor_id}|;
1019   $sth = $dbh->prepare($query);
1020   $sth->execute || $form->dberror($query);
1021
1022   ($form->{creditremaining}) -= $sth->fetchrow_array;
1023
1024   $sth->finish;
1025
1026   $query = qq|SELECT o.amount,
1027                 (SELECT e.sell FROM exchangerate e
1028                  WHERE e.curr = o.curr
1029                  AND e.transdate = o.transdate)
1030               FROM oe o
1031               WHERE o.vendor_id = $form->{vendor_id}
1032               AND o.quotation = '0'
1033               AND o.closed = '0'|;
1034   $sth = $dbh->prepare($query);
1035   $sth->execute || $form->dberror($query);
1036
1037   while (my ($amount, $exch) = $sth->fetchrow_array) {
1038     $exch = 1 unless $exch;
1039     $form->{creditremaining} -= $amount * $exch;
1040   }
1041   $sth->finish;
1042
1043   $form->get_contacts($dbh, $form->{vendor_id});
1044
1045   ($null, $form->{cp_id}) = split /--/, $form->{contact};
1046
1047   # get contact if selected
1048   if ($form->{contact} ne "--" && $form->{contact} ne "") {
1049     $form->get_contact($dbh, $form->{cp_id});
1050   }
1051
1052   # get shipto if we do not convert an order or invoice
1053   if (!$form->{shipto}) {
1054     map { delete $form->{$_} }
1055       qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail);
1056
1057     $query = qq|SELECT s.* FROM shipto s
1058                 WHERE s.trans_id = $form->{vendor_id} AND s.module= 'CT'|;
1059     $sth = $dbh->prepare($query);
1060     $sth->execute || $form->dberror($query);
1061
1062     $ref = $sth->fetchrow_hashref(NAME_lc);
1063     map { $form->{$_} = $ref->{$_} } keys %$ref;
1064     $sth->finish;
1065   }
1066
1067   # get taxes for vendor
1068   $query = qq|SELECT c.accno
1069               FROM chart c
1070               JOIN vendortax v ON (v.chart_id = c.id)
1071               WHERE v.vendor_id = $form->{vendor_id}|;
1072   $sth = $dbh->prepare($query);
1073   $sth->execute || $form->dberror($query);
1074
1075   my $vendortax = ();
1076   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1077     $vendortax{ $ref->{accno} } = 1;
1078   }
1079   $sth->finish;
1080
1081   if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
1082
1083     # setup last accounts used
1084     $query = qq|SELECT c.accno, c.description, c.link, c.category
1085                 FROM chart c
1086                 JOIN acc_trans ac ON (ac.chart_id = c.id)
1087                 JOIN ap a ON (a.id = ac.trans_id)
1088                 WHERE a.vendor_id = $form->{vendor_id}
1089                 AND NOT (c.link LIKE '%_tax%' OR c.link LIKE '%_paid%')
1090                 AND a.id IN (SELECT max(a2.id) FROM ap a2
1091                              WHERE a2.vendor_id = $form->{vendor_id})|;
1092     $sth = $dbh->prepare($query);
1093     $sth->execute || $form->dberror($query);
1094
1095     my $i = 0;
1096     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1097       if ($ref->{category} eq 'E') {
1098         $i++;
1099         $form->{"AP_amount_$i"} = "$ref->{accno}--$ref->{description}";
1100       }
1101       if ($ref->{category} eq 'L') {
1102         $form->{APselected} = $form->{AP_1} =
1103           "$ref->{accno}--$ref->{description}";
1104       }
1105     }
1106     $sth->finish;
1107     $form->{rowcount} = $i if ($i && !$form->{type});
1108   }
1109
1110   $dbh->disconnect;
1111
1112   $main::lxdebug->leave_sub();
1113 }
1114
1115 sub retrieve_item {
1116   $main::lxdebug->enter_sub();
1117
1118   my ($self, $myconfig, $form) = @_;
1119
1120   # connect to database
1121   my $dbh = $form->dbconnect($myconfig);
1122
1123   my $i = $form->{rowcount};
1124
1125   # don't include assemblies or obsolete parts
1126   my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
1127
1128   if ($form->{"partnumber_$i"}) {
1129     my $partnumber = $form->like(lc $form->{"partnumber_$i"});
1130     $where .= " AND lower(p.partnumber) LIKE '$partnumber'";
1131   }
1132
1133   if ($form->{"description_$i"}) {
1134     my $description = $form->like(lc $form->{"description_$i"});
1135     $where .= " AND lower(p.description) LIKE '$description'";
1136   }
1137
1138   if ($form->{"partsgroup_$i"}) {
1139     my $partsgroup = $form->like(lc $form->{"partsgroup_$i"});
1140     $where .= " AND lower(pg.partsgroup) LIKE '$partsgroup'";
1141   }
1142
1143   if ($form->{"description_$i"}) {
1144     $where .= " ORDER BY p.description";
1145   } else {
1146     $where .= " ORDER BY p.partnumber";
1147   }
1148
1149   my $transdate = "";
1150   if ($form->{type} eq "invoice") {
1151     $transdate =
1152       $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1153   } else {
1154     $transdate =
1155       $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1156   }
1157
1158   my $query = qq|SELECT p.id, p.partnumber, p.description, p.lastcost AS sellprice,
1159                         p.listprice, p.inventory_accno_id,
1160                         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
1161                         c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
1162                         c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
1163                  p.unit, p.assembly, p.bin, p.onhand, p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1164                  pg.partsgroup, p.formel
1165                  FROM parts p
1166                  LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
1167                  LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
1168                  LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
1169                  LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1170                  WHERE $where|;
1171   my $sth = $dbh->prepare($query);
1172   $sth->execute || $form->dberror($query);
1173
1174   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1175
1176     # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1177     # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1178     # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1179     if (!$ref->{inventory_accno_id}) {
1180       map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1181     }
1182     delete($ref->{inventory_accno_id});
1183
1184     # get tax rates and description
1185     $accno_id =
1186       ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1187     $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1188               FROM tax t LEFT JOIN chart c on (c.id=t.chart_id)
1189               WHERE t.id in (SELECT tk.tax_id from taxkeys tk where tk.chart_id = (SELECT id from chart WHERE accno='$accno_id') AND startdate<=$transdate ORDER BY startdate desc LIMIT 1)
1190               ORDER BY c.accno|;
1191     $stw = $dbh->prepare($query);
1192     $stw->execute || $form->dberror($query);
1193
1194     $ref->{taxaccounts} = "";
1195     my $i = 0;
1196     while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1197
1198       #    if ($customertax{$ref->{accno}}) {
1199       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1200         $i++;
1201         $ptr->{accno} = $i;
1202       }
1203       $ref->{taxaccounts} .= "$ptr->{accno} ";
1204       if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
1205         $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
1206         $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1207         $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
1208         $form->{taxaccounts} .= "$ptr->{accno} ";
1209       }
1210
1211     }
1212
1213     $stw->finish;
1214     chop $ref->{taxaccounts};
1215
1216     push @{ $form->{item_list} }, $ref;
1217
1218   }
1219
1220   $sth->finish;
1221   $dbh->disconnect;
1222
1223   $main::lxdebug->leave_sub();
1224 }
1225
1226 sub vendor_details {
1227   $main::lxdebug->enter_sub();
1228
1229   my ($self, $myconfig, $form, @wanted_vars) = @_;
1230
1231   # connect to database
1232   my $dbh = $form->dbconnect($myconfig);
1233
1234   # get contact id, set it if nessessary
1235   ($null, $form->{cp_id}) = split /--/, $form->{contact};
1236
1237   $contact = "";
1238   if ($form->{cp_id}) {
1239     $contact = "and cp.cp_id = $form->{cp_id}";
1240   }
1241
1242   # get rest for the vendor
1243   # fax and phone and email as vendor*
1244   my $query =
1245     qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail
1246                  FROM vendor ct
1247                  LEFT JOIN contacts cp on ct.id = cp.cp_cv_id
1248                  WHERE ct.id = $form->{vendor_id}  $contact order by cp.cp_id limit 1|;
1249   my $sth = $dbh->prepare($query);
1250   $sth->execute || $form->dberror($query);
1251
1252   $ref = $sth->fetchrow_hashref(NAME_lc);
1253
1254   # remove id and taxincluded before copy back
1255   delete @$ref{qw(id taxincluded)};
1256
1257   @wanted_vars = grep({ $_ } @wanted_vars);
1258   if (scalar(@wanted_vars) > 0) {
1259     my %h_wanted_vars;
1260     map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1261     map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1262   }
1263
1264   map { $form->{$_} = $ref->{$_} } keys %$ref;
1265
1266   $sth->finish;
1267   $dbh->disconnect;
1268
1269   $main::lxdebug->leave_sub();
1270 }
1271
1272 sub item_links {
1273   $main::lxdebug->enter_sub();
1274
1275   my ($self, $myconfig, $form) = @_;
1276
1277   # connect to database
1278   my $dbh = $form->dbconnect($myconfig);
1279
1280   my $query = qq|SELECT c.accno, c.description, c.link
1281                  FROM chart c
1282                  WHERE c.link LIKE '%IC%'
1283                  ORDER BY c.accno|;
1284   my $sth = $dbh->prepare($query);
1285   $sth->execute || $form->dberror($query);
1286
1287   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1288     foreach my $key (split(/:/, $ref->{link})) {
1289       if ($key =~ /IC/) {
1290         push @{ $form->{IC_links}{$key} },
1291           { accno       => $ref->{accno},
1292             description => $ref->{description} };
1293       }
1294     }
1295   }
1296
1297   $sth->finish;
1298   $main::lxdebug->leave_sub();
1299 }
1300
1301 sub webdav_folder {
1302   $main::lxdebug->enter_sub();
1303
1304   my ($myconfig, $form) = @_;
1305
1306 SWITCH: {
1307     $path = "webdav/rechnungen/" . $form->{invnumber}, last SWITCH
1308       if ($form->{vc} eq "customer");
1309     $path = "webdav/einkaufsrechnungen/" . $form->{invnumber}, last SWITCH
1310       if ($form->{vc} eq "vendor");
1311   }
1312
1313   if (!-d $path) {
1314     mkdir($path, 0770) or die "can't make directory $!\n";
1315   } else {
1316     if ($form->{id}) {
1317       @files = <$path/*>;
1318       foreach $file (@files) {
1319
1320         $file =~ /\/([^\/]*)$/;
1321         $fname = $1;
1322         $ENV{'SCRIPT_NAME'} =~ /\/([^\/]*)\//;
1323         $lxerp = $1;
1324         $link  = "http://" . $ENV{'SERVER_NAME'} . "/" . $lxerp . "/" . $file;
1325         $form->{WEBDAV}{$fname} = $link;
1326       }
1327     }
1328   }
1329
1330   $main::lxdebug->leave_sub();
1331 }
1332
1333 sub post_payment {
1334   $main::lxdebug->enter_sub();
1335
1336   my ($self, $myconfig, $form, $locale) = @_;
1337
1338   # connect to database, turn off autocommit
1339   my $dbh = $form->dbconnect_noauto($myconfig);
1340
1341   $form->{datepaid} = $form->{invdate};
1342
1343   # total payments, don't move we need it here
1344   for my $i (1 .. $form->{paidaccounts}) {
1345     $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
1346     $form->{paid} += $form->{"paid_$i"};
1347     $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"datepaid_$i"});
1348   }
1349
1350   $form->{exchangerate} =
1351       $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate},
1352                               "buy");
1353
1354   # record payments and offsetting AP
1355   for my $i (1 .. $form->{paidaccounts}) {
1356
1357     if ($form->{"paid_$i"} != 0) {
1358       my ($accno) = split /--/, $form->{"AP_paid_$i"};
1359       $form->{"datepaid_$i"} = $form->{invdate}
1360         unless ($form->{"datepaid_$i"});
1361       $form->{datepaid} = $form->{"datepaid_$i"};
1362
1363       $exchangerate = 0;
1364       if (($form->{currency} eq $form->{defaultcurrency}) || ($form->{defaultcurrency} eq "")) {
1365         $form->{"exchangerate_$i"} = 1;
1366       } else {
1367         $exchangerate =
1368           $form->check_exchangerate($myconfig, $form->{currency},
1369                                     $form->{"datepaid_$i"}, 'buy');
1370
1371         $form->{"exchangerate_$i"} =
1372           ($exchangerate)
1373           ? $exchangerate
1374           : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
1375       }
1376
1377       # record AP
1378       $amount =
1379         $form->round_amount($form->{"paid_$i"} * $form->{"exchangerate"},
1380                             2) * -1;
1381
1382
1383       $query = qq|DELETE FROM acc_trans WHERE trans_id=$form->{id} AND chart_id=(SELECT c.id FROM chart c
1384                                       WHERE c.accno = '$form->{AP}') AND amount=$amount AND transdate='$form->{"datepaid_$i"}'|;
1385       $dbh->do($query) || $form->dberror($query);
1386
1387       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
1388                   transdate)
1389                   VALUES ($form->{id}, (SELECT c.id FROM chart c
1390                                       WHERE c.accno = '$form->{AP}'),
1391                   $amount, '$form->{"datepaid_$i"}')|;
1392       $dbh->do($query) || $form->dberror($query);
1393
1394
1395
1396       $query = qq|DELETE FROM acc_trans WHERE trans_id=$form->{id} AND chart_id=(SELECT c.id FROM chart c
1397                                       WHERE c.accno = '$accno') AND amount=$form->{"paid_$i"} AND transdate='$form->{"datepaid_$i"}' AND source='$form->{"source_$i"}' AND memo='$form->{"memo_$i"}'|;
1398       $dbh->do($query) || $form->dberror($query);
1399
1400       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
1401                   source, memo)
1402                   VALUES ($form->{id}, (SELECT c.id FROM chart c
1403                                       WHERE c.accno = '$accno'),
1404                   $form->{"paid_$i"}, '$form->{"datepaid_$i"}',
1405                   '$form->{"source_$i"}', '$form->{"memo_$i"}')|;
1406       $dbh->do($query) || $form->dberror($query);
1407
1408
1409       # gain/loss
1410       $amount =
1411         $form->{"paid_$i"} * $form->{exchangerate} - $form->{"paid_$i"} *
1412         $form->{"exchangerate_$i"};
1413       if ($amount > 0) {
1414         $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } +=
1415           $amount;
1416       } else {
1417         $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } +=
1418           $amount;
1419       }
1420
1421       $diff = 0;
1422
1423       # update exchange rate
1424       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
1425         $form->update_exchangerate($dbh, $form->{currency},
1426                                    $form->{"datepaid_$i"},
1427                                    $form->{"exchangerate_$i"}, 0);
1428       }
1429     }
1430   }
1431
1432   # record exchange rate differences and gains/losses
1433   foreach my $accno (keys %{ $form->{fx} }) {
1434     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
1435       if (
1436           ($form->{fx}{$accno}{$transdate} =
1437            $form->round_amount($form->{fx}{$accno}{$transdate}, 2)
1438           ) != 0
1439         ) {
1440         $query = qq|DELETE FROM acc_trans WHERE trans_id=$form->{id} AND chart_id=(SELECT c.id FROM chart c
1441                                         WHERE c.accno = '$accno') AND amount=$form->{fx}{$accno}{$transdate} AND transdate='$transdate' AND cleared='0' AND fx_transaction='1'|;
1442         $dbh->do($query) || $form->dberror($query);
1443         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
1444                     transdate, cleared, fx_transaction)
1445                     VALUES ($form->{id},
1446                            (SELECT c.id FROM chart c
1447                             WHERE c.accno = '$accno'),
1448                     $form->{fx}{$accno}{$transdate}, '$transdate', '0', '1')|;
1449         $dbh->do($query) || $form->dberror($query);
1450       }
1451     }
1452   }
1453   my $datepaid = ($form->{paid})    ? qq|'$form->{datepaid}'| : "NULL";
1454
1455   # save AP record
1456   my $query = qq|UPDATE ap set
1457               paid = $form->{paid},
1458               datepaid = $datepaid
1459               WHERE id=$form->{id}|;
1460
1461   $dbh->do($query) || $form->dberror($query);
1462
1463   my $rc = $dbh->commit;
1464   $dbh->disconnect;
1465
1466   $main::lxdebug->leave_sub();
1467
1468   return $rc;
1469 }
1470
1471 1;