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