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