Merge pull request #6 from cwittmer/fixFSF
[kivitendo-erp.git] / bin / mozilla / cp.pl
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) 2002
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
28 # MA 02110-1335, USA.
29 #======================================================================
30 #
31 # Payment module
32 #
33 #======================================================================
34
35 use SL::CP;
36 use SL::IS;
37 use SL::IR;
38 use SL::AR;
39 use SL::AP;
40 use Data::Dumper;
41 use strict;
42 #use warnings;
43
44 require "bin/mozilla/arap.pl";
45 require "bin/mozilla/common.pl";
46
47 our ($form, %myconfig, $lxdebug, $locale, $auth);
48
49 1;
50
51 # end of main
52
53 sub payment {
54   $lxdebug->enter_sub();
55
56   $auth->assert('cash');
57
58   my (@curr);
59
60   $form->{ARAP} = ($form->{type} eq 'receipt') ? "AR" : "AP";
61   $form->{arap} = lc $form->{ARAP};
62
63   # setup customer/vendor selection for open invoices
64   if ($form->{all_vc}) {
65     # Dieser Zweig funktioniert derzeit NIE. Ggf. ganz raus oder
66     # alle offenen Zahlungen wieder korrekt anzeigen. jb 12.10.2010
67     $form->all_vc(\%myconfig, $form->{vc}, $form->{ARAP});
68   } else {
69     CP->get_openvc(\%myconfig, \%$form);
70   }
71   # Auswahlliste für vc zusammenbauen
72   # Erweiterung für schliessende option und erweiterung um value
73   # für bugfix 1771 (doppelte Leerzeichen werden nicht 'gepostet')
74   $form->{"select$form->{vc}"} = "";
75
76   if ($form->{"all_$form->{vc}"}) {
77     $form->{"select$form->{vc}"} .= "<option value=\"\"></option>\n";
78     # s.o. jb 12.10.2010
79     $form->{"$form->{vc}_id"} = $form->{"all_$form->{vc}"}->[0]->{id};
80     # hotfix for 2450. TODO remove legacy code and use L
81     map { $form->{"select$form->{vc}"} .= "<option value=\"" . H($_->{name}) . "--$_->{id}\">" . H($_->{name}) . "--$_->{id}</option>\n" }
82       @{ $form->{"all_$form->{vc}"} };
83   }
84   CP->paymentaccounts(\%myconfig, \%$form);
85
86   # Standard Konto für Umlaufvermögen
87   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
88   # Entsprechend präventiv die Auswahlliste für Kontonummer
89   # auch mit value= zusammenbauen (s.a. oben bugfix 1771)
90   # Wichtig: Auch das Template anpassen, damit hidden input korrekt die "
91   # escaped.
92   $form->{selectaccount} = "";
93   $form->{"select$form->{ARAP}"} = "";
94
95   map { $form->{selectaccount} .= "<option value=\"$_->{accno}--$_->{description}\">$_->{accno}--$_->{description}</option>\n";
96         $form->{account}        = "$_->{accno}--$_->{description}" if ($_->{accno} eq $accno_arap) } @{ $form->{PR}{"$form->{ARAP}_paid"} };
97
98   # Braucht man das hier überhaupt? Erstmal auskommentieren .. jan 18.12.2010
99   #  map {
100   #    $form->{"select$form->{ARAP}"} .=
101   #      "<option>$_->{accno}--$_->{description}\n"
102   #  } @{ $form->{PR}{ $form->{ARAP} } };
103   # ENDE LOESCHMICH in 2012
104
105   # currencies
106   # oldcurrency ist zwar noch hier als fragment enthalten, wird aber bei
107   # der aktualisierung der form auch nicht mitübernommen. das konzept
108   # old_$FOO habe ich auch noch nicht verstanden ...
109   # Ok. Wenn currency übernommen werden, dann in callback-string über-
110   # geben und hier reinparsen, oder besser multibox oder html auslagern?
111   # Antwort: form->currency wird mit oldcurrency oder curr[0] überschrieben
112   # Wofür macht das Sinn?
113   @curr = $form->get_all_currencies();
114   $form->{defaultcurrency} = $form->{currency} = $form->{oldcurrency} =
115     $form->get_default_currency(\%myconfig);
116
117   # Entsprechend präventiv die Auswahlliste für Währungen
118   # auch mit value= zusammenbauen (s.a. oben bugfix 1771)
119   $form->{selectcurrency} = "";
120   map { $form->{selectcurrency} .= "<option value=\"$_\">$_</option>\n" } @curr;
121
122
123   &form_header;
124   &form_footer;
125
126   $lxdebug->leave_sub();
127 }
128
129 sub form_header {
130   $lxdebug->enter_sub;
131
132   $auth->assert('cash');
133
134   my ($vc, $arap, $exchangerate);
135
136   if ($form->{ $form->{vc} } eq "") {
137     map { $form->{"addr$_"} = "" } (1 .. 4);
138   }
139
140   # sometimes it happens that values in customer arrive without the signs '--'
141   # but in order to select the right option field we need values with '--'
142   if ($form->{vc} eq "customer" && $form->{"all_$form->{vc}"}){
143     my ($customername) = split /--/, $form->{ $form->{vc} };
144     $form->{ $form->{vc} } = $customername . "--" . $form->{customer_id};
145   }
146   # bugfix 1771
147   # geändert von <option>asdf--2929
148   # nach:
149   #              <option value="asdf--2929">asdf--2929</option>
150   # offen: $form->{ARAP} kann raus?
151   for my $item ($form->{vc}, "account", "currency", $form->{ARAP}) {
152     $form->{$item} = H($form->{$item});
153     $form->{"select$item"} =~ s/ selected//;
154     $form->{"select$item"} =~ s/option value="\Q$form->{$item}\E">\Q$form->{$item}\E/option selected value="$form->{$item}">$form->{$item}/;
155   }
156
157   $vc =
158     ($form->{"select$form->{vc}"})
159     ? qq|<select name=$form->{vc}>$form->{"select$form->{vc}"}\n</select>|
160     : qq|<input name=$form->{vc} size=35 value="$form->{$form->{vc}}">|;
161
162   $form->{openinvoices} = $form->{all_vc} ? "" : 1;
163
164   # $locale->text('AR')
165   # $locale->text('AP')
166
167   $form->header;
168
169   $arap = lc $form->{ARAP};
170
171   print $::form->parse_html_template('cp/form_header', {
172     is_customer => $form->{vc}   eq 'customer',
173     is_receipt  => $form->{type} eq 'receipt',
174     arap        => $arap,
175     vccontent   => $vc,
176   });
177
178   $lxdebug->leave_sub;
179 }
180
181 sub list_invoices {
182   $::lxdebug->enter_sub;
183   $::auth->assert('cash');
184
185   my @columns = qw(amount due paid invnumber id transdate checked);
186   my (@invoices, %total);
187   for my $i (1 .. $::form->{rowcount}) {
188     push @invoices, +{ map { $_ => $::form->{"$_\_$i"} } @columns };
189     $total{$_} += $invoices[-1]{$_} = $::form->parse_amount(\%::myconfig, $invoices[-1]{$_}) for qw(amount due paid);
190   }
191
192   print $::form->parse_html_template('cp/invoices', {
193     invoices => \@invoices,
194     totals   => \%total,
195   });
196
197   $::lxdebug->leave_sub;
198 }
199
200 sub form_footer {
201   $::lxdebug->enter_sub;
202   $::auth->assert('cash');
203
204   print $::form->parse_html_template('cp/form_footer');
205
206   $::lxdebug->leave_sub;
207 }
208
209 sub update {
210   $lxdebug->enter_sub();
211
212   $auth->assert('cash');
213
214   my ($new_name_selected) = @_;
215
216   my ($buysell, $newvc, $updated, $exchangerate, $amount);
217
218   if ($form->{vc} eq 'customer') {
219     $buysell = "buy";
220   } else {
221     $buysell = "sell";
222   }
223
224   # if we switched to all_vc
225   # funktioniert derzeit nicht 12.10.2010 jb
226   if ($form->{all_vc} ne $form->{oldall_vc}) {
227
228     $form->{openinvoices} = ($form->{all_vc}) ? 0 : 1;
229
230     $form->{"select$form->{vc}"} = "";
231
232     if ($form->{all_vc}) {
233       $form->all_vc(\%myconfig, $form->{vc}, $form->{ARAP});
234
235       if ($form->{"all_$form->{vc}"}) {
236         map {
237           $form->{"select$form->{vc}"} .=
238             "<option>$_->{name}--$_->{id}\n"
239         } @{ $form->{"all_$form->{vc}"} };
240       }
241     } else {  # ab hier wieder ausgeführter code (s.o.):
242       CP->get_openvc(\%myconfig, \%$form);
243
244       if ($form->{"all_$form->{vc}"}) {
245         $newvc =
246           qq|$form->{"all_$form->{vc}"}[0]->{name}--$form->{"all_$form->{vc}"}[0]->{id}|;
247         map {
248           $form->{"select$form->{vc}"} .=
249             "<option>$_->{name}--$_->{id}\n"
250         } @{ $form->{"all_$form->{vc}"} };
251       }
252
253       # if the name is not the same
254       if ($form->{"select$form->{vc}"} !~ /$form->{$form->{vc}}/) {
255         $form->{ $form->{vc} } = $newvc;
256       }
257     }
258   }
259
260   # search by customernumber
261   # the customernumber has to be correct otherwise nothing is found
262   if ($form->{vc} eq 'customer' and $form->{customernumber} and $form->{ARAP} eq 'AR') {
263     $form->{open} ='Y'; # only open invoices
264     # ar_transactions automatically searches by $form->{customer_id} or else
265     # $form->{customer} if available, and these variables will always be set
266     # so we have to empty these values first
267     $form->{customer_id} = '';
268     $form->{customer} = '';
269     AR->ar_transactions(\%myconfig, \%$form);
270
271     # Here we just take the first returned value even if the custumernumber
272     # may not be unique
273     $form->{customer} = $form->{AR}[0]{name};
274     $form->{customer_id} = $form->{AR}[0]{customer_id};
275   }
276
277   # search by invoicenumber,
278   if ($form->{invnumber}) {
279     $form->{open} ='Y'; # only open invoices
280     if ($form->{ARAP} eq 'AR'){
281       # ar_transactions automatically searches by $form->{customer_id} or else
282       # $form->{customer} if available, and these variables will always be set
283       # so we have to empty these values first
284       $form->{customer_id} = '';
285       $form->{customer} = '';
286       AR->ar_transactions(\%myconfig, \%$form);
287
288       # if you search for invoice '11' ar_transactions will also match invoices
289       # 112, 211, ... due to the LIKE
290
291       # so there is now an extra loop that tries to match the invoice number
292       # exactly among all returned results, and then passes the customer_id instead of the name
293       # because the name may not be unique
294
295       my $found_exact_invnumber_match = 0;
296       foreach my $i ( @{ $form->{AR} } ) {
297         next unless $i->{invnumber} eq $form->{invnumber};
298         # found exactly matching invnumber
299         $form->{$form->{vc}} = $i->{name};
300         $form->{customer_id} = $i->{customer_id};
301         #$form->{"old${form->{vc}"} = $i->{customer_id};
302         $found_exact_invnumber_match = 1;
303       };
304
305       unless ( $found_exact_invnumber_match ) {
306         # use first returned entry, may not be the correct one if invnumber doesn't
307         # match uniquely
308         $form->{$form->{vc}} = $form->{AR}[0]{name};
309         $form->{customer_id} = $form->{AR}[0]{customer_id};
310       };
311     } else {
312       # s.o. nur für zahlungsausgang
313       AP->ap_transactions(\%myconfig, \%$form);
314       $form->{$form->{vc}} = $form->{AP}[0]{name};
315     }
316   }
317
318   # determine customer/vendor
319   if ( $form->{customer_id} and ($form->{invnumber} or $form->{customernumber}) ) {
320     # we already know the exact customer_id, so fill $form with customer data
321     IS->get_customer(\%myconfig, \%$form);
322     $updated = 1;
323   } else {
324     # check_name is called with "customer" or "vendor" and otherwise uses contents of $form
325     # check_name also runs get_customer/get_vendor
326     $updated = &check_name($form->{vc});
327   };
328
329   if ($new_name_selected || $updated) {
330     # get open invoices from ar/ap using $form->{vc} and a.${vc}_id, i.e. customer_id
331     CP->get_openinvoices(\%myconfig, \%$form);
332     ($newvc) = split /--/, $form->{ $form->{vc} };
333     $form->{"old$form->{vc}"} = qq|$newvc--$form->{"$form->{vc}_id"}|;
334     $updated = 1;
335   }
336
337   if ($form->{currency} ne $form->{oldcurrency}) {
338     $form->{oldcurrency} = $form->{currency};
339     if (!$updated) {
340       CP->get_openinvoices(\%myconfig, \%$form);
341       $updated = 1;
342     }
343   }
344
345   if (!$form->{forex}) {        # read exchangerate from input field (not hidden)
346     $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate});
347   }
348   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{datepaid}, $buysell);
349   $form->{exchangerate} = $form->{forex} if $form->{forex};
350
351   $amount = $form->{amount} = $form->parse_amount(\%myconfig, $form->{amount});
352
353   if ($updated) {
354     $form->{rowcount} = 0;
355
356     $form->{queued} = "";
357
358     my $i = 0;
359     foreach my $ref (@{ $form->{PR} }) {
360       $i++;
361       $form->{"id_$i"}        = $ref->{id};
362       $form->{"invnumber_$i"} = $ref->{invnumber};
363       $form->{"transdate_$i"} = $ref->{transdate};
364       $ref->{exchangerate} = 1 unless $ref->{exchangerate};
365       $form->{"amount_$i"} = $ref->{amount} / $ref->{exchangerate};
366       $form->{"due_$i"}    =
367         ($ref->{amount} - $ref->{paid}) / $ref->{exchangerate};
368       $form->{"checked_$i"} = "";
369       $form->{"paid_$i"}    = "";
370
371       # need to format
372       map {
373         $form->{"${_}_$i"} =
374           $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2)
375       } qw(amount due);
376
377     }
378     $form->{rowcount} = $i;
379   }
380
381   # recalculate
382
383   # Modified from $amount = $form->{amount} by J.Zach to update amount to total
384   # payment amount in Zahlungsausgang
385   $amount = 0;
386   for my $i (1 .. $form->{rowcount}) {
387
388     map {
389       $form->{"${_}_$i"} =
390         $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
391     } qw(amount due paid);
392
393     if ($form->{"checked_$i"}) {
394
395       # calculate paid_$i
396       if (!$form->{"paid_$i"}) {
397         $form->{"paid_$i"} = $form->{"due_$i"};
398       }
399
400       # Modified by J.Zach, see abovev
401       $amount += $form->{"paid_$i"};
402
403     } else {
404       $form->{"paid_$i"} = "";
405     }
406
407     map {
408       $form->{"${_}_$i"} =
409         $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2)
410     } qw(amount due paid);
411
412   }
413
414   # Line added by J.Zach, see above
415   $form->{amount}=$amount;
416
417   &form_header;
418   &list_invoices;
419   &form_footer;
420
421   $lxdebug->leave_sub();
422 }
423
424 sub post {
425   $lxdebug->enter_sub();
426
427   $auth->assert('cash');
428
429   &check_form;
430
431   if ($form->{currency} ne $form->{defaultcurrency}) {
432     $form->error($locale->text('Exchangerate missing!'))
433       unless $form->{exchangerate};
434   }
435
436   # Beim Aktualisieren wird das Konto übernommen
437   # und jetzt auch Beleg und Datum
438   $form->{callback} = "cp.pl?action=payment&vc=$form->{vc}&type=$form->{type}&account=$form->{account}&$form->{currency}" .
439                       "&datepaid=$form->{datepaid}&source=$form->{source}";
440
441   my $msg1 = $::form->{type} eq 'receipt' ? $::locale->text("Receipt posted!") : $::locale->text("Payment posted!");
442   my $msg2 = $::form->{type} eq 'receipt' ? $::locale->text("Cannot post Receipt!") : $::locale->text("Cannot post Payment!");
443
444   # Die Nachrichten (Receipt posted!) werden nicht angezeigt.
445   # Entweder wieder aktivieren oder komplett rausnehmen
446   $form->redirect($msg1) if (CP->process_payment(\%::myconfig, $::form));
447   $form->error($msg2);
448
449   $lxdebug->leave_sub();
450 }
451
452 sub check_form {
453   $lxdebug->enter_sub();
454
455   $auth->assert('cash');
456
457   my ($closedto, $datepaid, $amount);
458
459   &check_name($form->{vc});
460
461   if ($form->{currency} ne $form->{oldcurrency}) {
462     &update;
463     $::dispatcher->end_request;
464   }
465   $form->error($locale->text('Date missing!')) unless $form->{datepaid};
466   my $selected_check = 1;
467   for my $i (1 .. $form->{rowcount}) {
468     next unless $form->{"checked_$i"};
469     if (abs($form->parse_amount(\%myconfig, $form->{"paid_$i"}, 2)) < 0.01) {
470       $form->error($locale->text('Row #1: amount has to be different from zero.', $i));
471     }
472     undef $selected_check;
473   }
474   $form->error($locale->text('No transaction selected!')) if $selected_check;
475
476   $closedto = $form->datetonum($form->{closedto}, \%myconfig);
477   $datepaid = $form->datetonum($form->{datepaid}, \%myconfig);
478
479   $form->error($locale->text('Cannot process payment for a closed period!'))
480     if ($form->date_closed($form->{"datepaid"}, \%myconfig));
481
482   $amount = $form->parse_amount(\%myconfig, $form->{amount});
483   $form->{amount} = $amount;
484
485   for my $i (1 .. $form->{rowcount}) {
486     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
487       $amount -= $form->parse_amount(\%myconfig, $form->{"paid_$i"});
488
489       push(@{ $form->{paid}      ||= [] }, $form->{"paid_$i"});
490       push(@{ $form->{due}       ||= [] }, $form->{"due_$i"});
491       push(@{ $form->{invnumber} ||= [] }, $form->{"invnumber_$i"});
492       push(@{ $form->{invdate}   ||= [] }, $form->{"transdate_$i"});
493     }
494   }
495
496   if ($form->round_amount($amount, 2) != 0) {
497     push(@{ $form->{paid} }, $form->format_amount(\%myconfig, $amount, 2));
498     push(@{ $form->{due} }, $form->format_amount(\%myconfig, 0, "0"));
499     push(@{ $form->{invnumber} },
500          ($form->{ARAP} eq 'AR')
501          ? $locale->text('Deposit')
502          : $locale->text('Prepayment'));
503     push(@{ $form->{invdate} }, $form->{datepaid});
504   }
505
506   $lxdebug->leave_sub();
507 }