Uebernahme der kompletten Version, so wie sie Philip als "Demo-Version" gezeigt hat...
[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,
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     my $transdate = "current_date";
870     if($form->{invdate}) {
871      $transdate = "'$form->{invdate}'";
872     }
873
874     if(!$form->{taxzone_id}) {
875       $form->{taxzone_id} = 0;
876     }
877     # retrieve individual items
878     $query = qq|SELECT c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
879                 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
880                 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
881                 p.partnumber, i.description, i.qty, i.fxsellprice AS sellprice, p.inventory_accno_id AS part_inventory_accno_id,
882                 i.parts_id AS id, i.unit, p.bin, i.deliverydate,
883                 pr.projectnumber,
884                 i.project_id, i.serialnumber,
885                 pg.partsgroup
886                 FROM invoice i
887                 JOIN parts p ON (i.parts_id = p.id)
888                 LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
889                 LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
890                 LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
891                 LEFT JOIN project pr ON (i.project_id = pr.id)
892                 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
893                 WHERE i.trans_id = $form->{id}
894                 ORDER BY i.id|;
895     $sth = $dbh->prepare($query);
896     $sth->execute || $form->dberror($query);
897
898     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
899       if (!$ref->{"part_inventory_accno_id"}) {
900         map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid));
901       }
902       delete($ref->{"part_inventory_accno_id"});
903
904       while ($ref->{inventory_new_chart} && ($ref->{inventory_valid} >=0)) {
905         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}|;
906         my $stw = $dbh->prepare($query);
907         $stw->execute || $form->dberror($query);
908         ($ref->{inventory_accno}, $ref->{inventory_new_chart}, $ref->{inventory_valid}) = $stw->fetchrow_array;
909         $stw->finish;
910       }
911   
912       while ($ref->{income_new_chart} && ($ref->{income_valid} >=0)) {
913         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}|;
914         my $stw = $dbh->prepare($query);
915         $stw->execute || $form->dberror($query);
916         ($ref->{income_accno}, $ref->{income_new_chart}, $ref->{income_valid}) = $stw->fetchrow_array;
917         $stw->finish;
918       }
919   
920       while ($ref->{expense_new_chart} && ($ref->{expense_valid} >=0)) {
921         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}|;
922         my $stw = $dbh->prepare($query);
923         $stw->execute || $form->dberror($query);
924         ($ref->{expense_accno}, $ref->{expense_new_chart}, $ref->{expense_valid}) = $stw->fetchrow_array;
925         $stw->finish;
926       }
927
928
929
930       #set expense_accno=inventory_accno if they are different => bilanz
931       $vendor_accno =
932         ($ref->{expense_accno} != $ref->{inventory_accno})
933         ? $ref->{inventory_accno}
934         : $ref->{expense_accno};
935       $vendor_accno =
936         ($ref->{inventory_accno})
937         ? $ref->{inventory_accno}
938         : $ref->{expense_accno};
939
940       # get tax rates and description
941       $accno_id =
942         ($form->{vc} eq "customer") ? $ref->{income_accno} : $vendor_accno;
943       $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
944                  FROM tax t LEFT join chart c ON (c.id=t.chart_id)
945                  WHERE t.taxkey in (SELECT taxkey_id from chart where accno = '$accno_id')
946                  ORDER BY accno|;
947       $stw = $dbh->prepare($query);
948       $stw->execute || $form->dberror($query);
949       $ref->{taxaccounts} = "";
950       my $i = 0;
951       while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
952
953         #    if ($customertax{$ref->{accno}}) {
954         if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
955           $i++;
956           $ptr->{accno} = $i;
957         }
958         $ref->{taxaccounts} .= "$ptr->{accno} ";
959         if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
960           $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
961           $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
962           $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
963           $form->{taxaccounts} .= "$ptr->{accno} ";
964         }
965
966       }
967
968       chop $ref->{taxaccounts};
969       push @{ $form->{invoice_details} }, $ref;
970       $stw->finish;
971     }
972     $sth->finish;
973
974     if ($form->{webdav}) {
975       &webdav_folder($myconfig, $form);
976     }
977
978   }
979
980   my $rc = $dbh->commit;
981   $dbh->disconnect;
982
983   $main::lxdebug->leave_sub();
984
985   return $rc;
986 }
987
988 sub get_vendor {
989   $main::lxdebug->enter_sub();
990
991   my ($self, $myconfig, $form) = @_;
992
993   # connect to database
994   my $dbh = $form->dbconnect($myconfig);
995
996   my $dateformat = $myconfig->{dateformat};
997   $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
998
999   my $duedate =
1000     ($form->{invdate})
1001     ? "to_date('$form->{invdate}', '$dateformat')"
1002     : "current_date";
1003
1004   $form->{vendor_id} *= 1;
1005
1006   # get vendor
1007   my $query = qq|SELECT v.name AS vendor, v.creditlimit, v.terms,
1008                  v.email, v.cc, v.bcc, v.language_id, v.payment_id,
1009                  v.street, v.zipcode, v.city, v.country, v.taxzone_id,
1010                  $duedate + v.terms AS duedate
1011                  FROM vendor v
1012                  WHERE v.id = $form->{vendor_id}|;
1013   my $sth = $dbh->prepare($query);
1014   $sth->execute || $form->dberror($query);
1015
1016   $ref = $sth->fetchrow_hashref(NAME_lc);
1017   map { $form->{$_} = $ref->{$_} } keys %$ref;
1018   $sth->finish;
1019
1020   $form->{creditremaining} = $form->{creditlimit};
1021   $query = qq|SELECT SUM(a.amount - a.paid)
1022               FROM ap a
1023               WHERE a.vendor_id = $form->{vendor_id}|;
1024   $sth = $dbh->prepare($query);
1025   $sth->execute || $form->dberror($query);
1026
1027   ($form->{creditremaining}) -= $sth->fetchrow_array;
1028
1029   $sth->finish;
1030
1031   $query = qq|SELECT o.amount,
1032                 (SELECT e.sell FROM exchangerate e
1033                  WHERE e.curr = o.curr
1034                  AND e.transdate = o.transdate)
1035               FROM oe o
1036               WHERE o.vendor_id = $form->{vendor_id}
1037               AND o.quotation = '0'
1038               AND o.closed = '0'|;
1039   $sth = $dbh->prepare($query);
1040   $sth->execute || $form->dberror($query);
1041
1042   while (my ($amount, $exch) = $sth->fetchrow_array) {
1043     $exch = 1 unless $exch;
1044     $form->{creditremaining} -= $amount * $exch;
1045   }
1046   $sth->finish;
1047
1048   $form->get_contacts($dbh, $form->{vendor_id});
1049
1050   ($null, $form->{cp_id}) = split /--/, $form->{contact};
1051
1052   # get contact if selected
1053   if ($form->{contact} ne "--" && $form->{contact} ne "") {
1054     $form->get_contact($dbh, $form->{cp_id});
1055   }
1056
1057   # get shipto if we do not convert an order or invoice
1058   if (!$form->{shipto}) {
1059     map { delete $form->{$_} }
1060       qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail);
1061
1062     $query = qq|SELECT s.* FROM shipto s
1063                 WHERE s.trans_id = $form->{vendor_id} AND s.module= 'CT'|;
1064     $sth = $dbh->prepare($query);
1065     $sth->execute || $form->dberror($query);
1066
1067     $ref = $sth->fetchrow_hashref(NAME_lc);
1068     map { $form->{$_} = $ref->{$_} } keys %$ref;
1069     $sth->finish;
1070   }
1071
1072   # get taxes for vendor
1073   $query = qq|SELECT c.accno
1074               FROM chart c
1075               JOIN vendortax v ON (v.chart_id = c.id)
1076               WHERE v.vendor_id = $form->{vendor_id}|;
1077   $sth = $dbh->prepare($query);
1078   $sth->execute || $form->dberror($query);
1079
1080   my $vendortax = ();
1081   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1082     $vendortax{ $ref->{accno} } = 1;
1083   }
1084   $sth->finish;
1085
1086   if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
1087
1088     # setup last accounts used
1089     $query = qq|SELECT c.accno, c.description, c.link, c.category
1090                 FROM chart c
1091                 JOIN acc_trans ac ON (ac.chart_id = c.id)
1092                 JOIN ap a ON (a.id = ac.trans_id)
1093                 WHERE a.vendor_id = $form->{vendor_id}
1094                 AND NOT (c.link LIKE '%_tax%' OR c.link LIKE '%_paid%')
1095                 AND a.id IN (SELECT max(a2.id) FROM ap a2
1096                              WHERE a2.vendor_id = $form->{vendor_id})|;
1097     $sth = $dbh->prepare($query);
1098     $sth->execute || $form->dberror($query);
1099
1100     my $i = 0;
1101     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1102       if ($ref->{category} eq 'E') {
1103         $i++;
1104         $form->{"AP_amount_$i"} = "$ref->{accno}--$ref->{description}";
1105       }
1106       if ($ref->{category} eq 'L') {
1107         $form->{APselected} = $form->{AP_1} =
1108           "$ref->{accno}--$ref->{description}";
1109       }
1110     }
1111     $sth->finish;
1112     $form->{rowcount} = $i if ($i && !$form->{type});
1113   }
1114
1115   $dbh->disconnect;
1116
1117   $main::lxdebug->leave_sub();
1118 }
1119
1120 sub retrieve_item {
1121   $main::lxdebug->enter_sub();
1122
1123   my ($self, $myconfig, $form) = @_;
1124
1125   my $i = $form->{rowcount};
1126
1127   # don't include assemblies or obsolete parts
1128   my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
1129
1130   if ($form->{"partnumber_$i"}) {
1131     my $partnumber = $form->like(lc $form->{"partnumber_$i"});
1132     $where .= " AND lower(p.partnumber) LIKE '$partnumber'";
1133   }
1134
1135   if ($form->{"description_$i"}) {
1136     my $description = $form->like(lc $form->{"description_$i"});
1137     $where .= " AND lower(p.description) LIKE '$description'";
1138   }
1139
1140   if ($form->{"partsgroup_$i"}) {
1141     my $partsgroup = $form->like(lc $form->{"partsgroup_$i"});
1142     $where .= " AND lower(pg.partsgroup) LIKE '$partsgroup'";
1143   }
1144
1145   if ($form->{"description_$i"}) {
1146     $where .= " ORDER BY p.description";
1147   } else {
1148     $where .= " ORDER BY p.partnumber";
1149   }
1150
1151   my $transdate = "";
1152   if ($form->{type} eq "invoice") {
1153     $transdate = "'$form->{invdate}'";
1154   } elsif ($form->{type} eq "purchase_order") {
1155     $transdate = "'$form->{transdate}'";
1156   } elsif ($form->{type} eq "request_quotation") {
1157     $transdate = "'$form->{transdate}'";
1158   }
1159
1160   if ($transdate eq "") {
1161     $transdate = "current_date";
1162   }
1163
1164   # connect to database
1165   my $dbh = $form->dbconnect($myconfig);
1166
1167   my $query = qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
1168                         p.listprice, p.inventory_accno_id,
1169                         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
1170                         c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
1171                         c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
1172                  p.unit, p.assembly, p.bin, p.onhand, p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1173                  pg.partsgroup, p.formel, p.alu
1174                  FROM parts p
1175                  LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
1176                  LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
1177                  LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
1178                  LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1179                  WHERE $where|;
1180   my $sth = $dbh->prepare($query);
1181   $sth->execute || $form->dberror($query);
1182
1183   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1184
1185     # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1186     # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1187     # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1188     if (!$ref->{inventory_accno_id}) {
1189       map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1190     }
1191     delete($ref->{inventory_accno_id});
1192
1193     #set expense_accno=inventory_accno if they are different => bilanz
1194     $vendor_accno =
1195       ($ref->{expense_accno} != $ref->{inventory_accno})
1196       ? $ref->{inventory_accno}
1197       : $ref->{expense_accno};
1198     $vendor_accno =
1199       ($ref->{inventory_accno})
1200       ? $ref->{inventory_accno}
1201       : $ref->{expense_accno};
1202
1203     # get tax rates and description
1204     $accno_id =
1205       ($form->{vc} eq "customer") ? $ref->{income_accno} : $vendor_accno;
1206     $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1207               FROM tax t LEFT JOIN chart c ON (c.id=t.chart_id)
1208               WHERE t.taxkey in (SELECT taxkey_id from chart where accno = '$accno_id')
1209               ORDER BY c.accno|;
1210     $stw = $dbh->prepare($query);
1211     $stw->execute || $form->dberror($query);
1212
1213     $ref->{taxaccounts} = "";
1214     my $i = 0;
1215     while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1216
1217       #    if ($customertax{$ref->{accno}}) {
1218       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1219         $i++;
1220         $ptr->{accno} = $i;
1221       }
1222       $ref->{taxaccounts} .= "$ptr->{accno} ";
1223       if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
1224         $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
1225         $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1226         $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
1227         $form->{taxaccounts} .= "$ptr->{accno} ";
1228       }
1229
1230     }
1231
1232     $stw->finish;
1233     chop $ref->{taxaccounts};
1234
1235     push @{ $form->{item_list} }, $ref;
1236
1237   }
1238
1239   $sth->finish;
1240   $dbh->disconnect;
1241
1242   $main::lxdebug->leave_sub();
1243 }
1244
1245 sub vendor_details {
1246   $main::lxdebug->enter_sub();
1247
1248   my ($self, $myconfig, $form) = @_;
1249
1250   # connect to database
1251   my $dbh = $form->dbconnect($myconfig);
1252
1253   # get contact id, set it if nessessary
1254   ($null, $form->{cp_id}) = split /--/, $form->{contact};
1255
1256   $contact = "";
1257   if ($form->{cp_id}) {
1258     $contact = "and cp.cp_id = $form->{cp_id}";
1259   }
1260
1261   # get rest for the vendor
1262   # fax and phone and email as vendor*
1263   my $query =
1264     qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail
1265                  FROM vendor ct
1266                  LEFT JOIN contacts cp on ct.id = cp.cp_cv_id
1267                  WHERE ct.id = $form->{vendor_id}  $contact order by cp.cp_id limit 1|;
1268   my $sth = $dbh->prepare($query);
1269   $sth->execute || $form->dberror($query);
1270
1271   $ref = $sth->fetchrow_hashref(NAME_lc);
1272
1273   # remove id and taxincluded before copy back
1274   delete @$ref{qw(id taxincluded)};
1275   map { $form->{$_} = $ref->{$_} } keys %$ref;
1276
1277   $sth->finish;
1278   $dbh->disconnect;
1279
1280   $main::lxdebug->leave_sub();
1281 }
1282
1283 sub item_links {
1284   $main::lxdebug->enter_sub();
1285
1286   my ($self, $myconfig, $form) = @_;
1287
1288   # connect to database
1289   my $dbh = $form->dbconnect($myconfig);
1290
1291   my $query = qq|SELECT c.accno, c.description, c.link
1292                  FROM chart c
1293                  WHERE c.link LIKE '%IC%'
1294                  ORDER BY c.accno|;
1295   my $sth = $dbh->prepare($query);
1296   $sth->execute || $form->dberror($query);
1297
1298   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1299     foreach my $key (split(/:/, $ref->{link})) {
1300       if ($key =~ /IC/) {
1301         push @{ $form->{IC_links}{$key} },
1302           { accno       => $ref->{accno},
1303             description => $ref->{description} };
1304       }
1305     }
1306   }
1307
1308   $sth->finish;
1309   $main::lxdebug->leave_sub();
1310 }
1311
1312 sub webdav_folder {
1313   $main::lxdebug->enter_sub();
1314
1315   my ($myconfig, $form) = @_;
1316
1317 SWITCH: {
1318     $path = "webdav/rechnungen/" . $form->{invnumber}, last SWITCH
1319       if ($form->{vc} eq "customer");
1320     $path = "webdav/einkaufsrechnungen/" . $form->{invnumber}, last SWITCH
1321       if ($form->{vc} eq "vendor");
1322   }
1323
1324   if (!-d $path) {
1325     mkdir($path, 0770) or die "can't make directory $!\n";
1326   } else {
1327     if ($form->{id}) {
1328       @files = <$path/*>;
1329       foreach $file (@files) {
1330
1331         $file =~ /\/([^\/]*)$/;
1332         $fname = $1;
1333         $ENV{'SCRIPT_NAME'} =~ /\/([^\/]*)\//;
1334         $lxerp = $1;
1335         $link  = "http://" . $ENV{'SERVER_NAME'} . "/" . $lxerp . "/" . $file;
1336         $form->{WEBDAV}{$fname} = $link;
1337       }
1338     }
1339   }
1340
1341   $main::lxdebug->leave_sub();
1342 }
1343
1344 sub post_payment {
1345   $main::lxdebug->enter_sub();
1346
1347   my ($self, $myconfig, $form, $locale) = @_;
1348
1349   # connect to database, turn off autocommit
1350   my $dbh = $form->dbconnect_noauto($myconfig);
1351
1352   $form->{datepaid} = $form->{invdate};
1353
1354   # total payments, don't move we need it here
1355   for my $i (1 .. $form->{paidaccounts}) {
1356     $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
1357     $form->{paid} += $form->{"paid_$i"};
1358     $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"datepaid_$i"});
1359   }
1360
1361   $form->{exchangerate} =
1362       $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate},
1363                               "buy");
1364
1365   # record payments and offsetting AP
1366   for my $i (1 .. $form->{paidaccounts}) {
1367
1368     if ($form->{"paid_$i"} != 0) {
1369       my ($accno) = split /--/, $form->{"AP_paid_$i"};
1370       $form->{"datepaid_$i"} = $form->{invdate}
1371         unless ($form->{"datepaid_$i"});
1372       $form->{datepaid} = $form->{"datepaid_$i"};
1373
1374       $exchangerate = 0;
1375       if (($form->{currency} eq $form->{defaultcurrency}) || ($form->{defaultcurrency} eq "")) {
1376         $form->{"exchangerate_$i"} = 1;
1377       } else {
1378         $exchangerate =
1379           $form->check_exchangerate($myconfig, $form->{currency},
1380                                     $form->{"datepaid_$i"}, 'buy');
1381
1382         $form->{"exchangerate_$i"} =
1383           ($exchangerate)
1384           ? $exchangerate
1385           : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
1386       }
1387
1388       # record AP
1389       $amount =
1390         $form->round_amount($form->{"paid_$i"} * $form->{"exchangerate"},
1391                             2) * -1;
1392
1393
1394       $query = qq|DELETE FROM acc_trans WHERE trans_id=$form->{id} AND chart_id=(SELECT c.id FROM chart c
1395                                       WHERE c.accno = '$form->{AP}') AND amount=$amount AND transdate='$form->{"datepaid_$i"}'|;
1396       $dbh->do($query) || $form->dberror($query);
1397
1398       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
1399                   transdate)
1400                   VALUES ($form->{id}, (SELECT c.id FROM chart c
1401                                       WHERE c.accno = '$form->{AP}'),
1402                   $amount, '$form->{"datepaid_$i"}')|;
1403       $dbh->do($query) || $form->dberror($query);
1404
1405
1406
1407       $query = qq|DELETE FROM acc_trans WHERE trans_id=$form->{id} AND chart_id=(SELECT c.id FROM chart c
1408                                       WHERE c.accno = '$accno') AND amount=$form->{"paid_$i"} AND transdate='$form->{"datepaid_$i"}' AND source='$form->{"source_$i"}' AND memo='$form->{"memo_$i"}'|;
1409       $dbh->do($query) || $form->dberror($query);
1410
1411       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
1412                   source, memo)
1413                   VALUES ($form->{id}, (SELECT c.id FROM chart c
1414                                       WHERE c.accno = '$accno'),
1415                   $form->{"paid_$i"}, '$form->{"datepaid_$i"}',
1416                   '$form->{"source_$i"}', '$form->{"memo_$i"}')|;
1417       $dbh->do($query) || $form->dberror($query);
1418
1419
1420       # gain/loss
1421       $amount =
1422         $form->{"paid_$i"} * $form->{exchangerate} - $form->{"paid_$i"} *
1423         $form->{"exchangerate_$i"};
1424       if ($amount > 0) {
1425         $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } +=
1426           $amount;
1427       } else {
1428         $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } +=
1429           $amount;
1430       }
1431
1432       $diff = 0;
1433
1434       # update exchange rate
1435       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
1436         $form->update_exchangerate($dbh, $form->{currency},
1437                                    $form->{"datepaid_$i"},
1438                                    $form->{"exchangerate_$i"}, 0);
1439       }
1440     }
1441   }
1442
1443   # record exchange rate differences and gains/losses
1444   foreach my $accno (keys %{ $form->{fx} }) {
1445     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
1446       if (
1447           ($form->{fx}{$accno}{$transdate} =
1448            $form->round_amount($form->{fx}{$accno}{$transdate}, 2)
1449           ) != 0
1450         ) {
1451         $query = qq|DELETE FROM acc_trans WHERE trans_id=$form->{id} AND chart_id=(SELECT c.id FROM chart c
1452                                         WHERE c.accno = '$accno') AND amount=$form->{fx}{$accno}{$transdate} AND transdate='$transdate' AND cleared='0' AND fx_transaction='1'|;
1453         $dbh->do($query) || $form->dberror($query);
1454         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
1455                     transdate, cleared, fx_transaction)
1456                     VALUES ($form->{id},
1457                            (SELECT c.id FROM chart c
1458                             WHERE c.accno = '$accno'),
1459                     $form->{fx}{$accno}{$transdate}, '$transdate', '0', '1')|;
1460         $dbh->do($query) || $form->dberror($query);
1461       }
1462     }
1463   }
1464   my $datepaid = ($form->{paid})    ? qq|'$form->{datepaid}'| : "NULL";
1465
1466   # save AP record
1467   my $query = qq|UPDATE ap set
1468               paid = $form->{paid},
1469               datepaid = $datepaid
1470               WHERE id=$form->{id}|;
1471
1472   $dbh->do($query) || $form->dberror($query);
1473
1474   my $rc = $dbh->commit;
1475   $dbh->disconnect;
1476
1477   $main::lxdebug->leave_sub();
1478
1479   return $rc;
1480 }
1481
1482 1;