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