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