6060253928121bea6f758606de0b24ff9692be3a
[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 SL::Locale::String qw(t8);
42 use strict;
43 #use warnings;
44
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   CP->paymentaccounts(\%myconfig, \%$form);
64
65   # Standard Konto für Umlaufvermögen
66   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
67   # Entsprechend präventiv die Auswahlliste für Kontonummer
68   # auch mit value= zusammenbauen (s.a. oben bugfix 1771)
69   # Wichtig: Auch das Template anpassen, damit hidden input korrekt die "
70   # escaped.
71   $form->{selectaccount} = "";
72   $form->{"select$form->{ARAP}"} = "";
73
74   map { $form->{selectaccount} .= "<option value=\"$_->{accno}--$_->{description}\">$_->{accno}--$_->{description}</option>\n";
75         $form->{account}        = "$_->{accno}--$_->{description}" if ($_->{accno} eq $accno_arap) } @{ $form->{PR}{"$form->{ARAP}_paid"} };
76
77   # currencies
78   # oldcurrency ist zwar noch hier als fragment enthalten, wird aber bei
79   # der aktualisierung der form auch nicht mitübernommen. das konzept
80   # old_$FOO habe ich auch noch nicht verstanden ...
81   # Ok. Wenn currency übernommen werden, dann in callback-string über-
82   # geben und hier reinparsen, oder besser multibox oder html auslagern?
83   # Antwort: form->currency wird mit oldcurrency oder curr[0] überschrieben
84   # Wofür macht das Sinn?
85   @curr = $form->get_all_currencies();
86   $form->{defaultcurrency} = $form->{currency} = $form->{oldcurrency} =
87     $form->get_default_currency(\%myconfig);
88
89   # Entsprechend präventiv die Auswahlliste für Währungen
90   # auch mit value= zusammenbauen (s.a. oben bugfix 1771)
91   $form->{selectcurrency} = "";
92   map { $form->{selectcurrency} .= "<option value=\"$_\">$_</option>\n" } @curr;
93
94
95   &form_header;
96   &form_footer;
97
98   $lxdebug->leave_sub();
99 }
100
101 sub form_header {
102   $lxdebug->enter_sub;
103
104   $auth->assert('cash');
105
106   $::request->layout->add_javascripts("autocomplete_customer.js");
107
108   my ($arap, $exchangerate);
109
110   if (!$form->{ $form->{vc} . '_id' }) {
111     map { $form->{"addr$_"} = "" } (1 .. 4);
112   }
113
114   # bugfix 1771
115   # geändert von <option>asdf--2929
116   # nach:
117   #              <option value="asdf--2929">asdf--2929</option>
118   # offen: $form->{ARAP} kann raus?
119   for my $item ("account", "currency", $form->{ARAP}) {
120     $form->{$item} = H($form->{$item});
121     $form->{"select$item"} =~ s/ selected//;
122     $form->{"select$item"} =~ s/option value="\Q$form->{$item}\E">\Q$form->{$item}\E/option selected value="$form->{$item}">$form->{$item}/;
123   }
124
125   $form->{openinvoices} = 1;
126
127   # $locale->text('AR')
128   # $locale->text('AP')
129
130   setup_cp_form_action_bar(can_post => !!$form->{rowcount});
131
132   $form->header;
133
134   $arap = lc $form->{ARAP};
135
136   print $::form->parse_html_template('cp/form_header', {
137     is_customer => $form->{vc}   eq 'customer',
138     is_receipt  => $form->{type} eq 'receipt',
139     arap        => $arap,
140   });
141
142   $lxdebug->leave_sub;
143 }
144
145 sub list_invoices {
146   $::lxdebug->enter_sub;
147   $::auth->assert('cash');
148
149   my @columns = qw(amount due paid invnumber id transdate checked);
150   my (@invoices, %total);
151   for my $i (1 .. $::form->{rowcount}) {
152     push @invoices, +{ map { $_ => $::form->{"$_\_$i"} } @columns };
153     $total{$_} += $invoices[-1]{$_} = $::form->parse_amount(\%::myconfig, $invoices[-1]{$_}) for qw(amount due paid);
154   }
155
156   print $::form->parse_html_template('cp/invoices', {
157     invoices => \@invoices,
158     totals   => \%total,
159   });
160
161   $::lxdebug->leave_sub;
162 }
163
164 sub form_footer {
165   $::lxdebug->enter_sub;
166   $::auth->assert('cash');
167
168   print $::form->parse_html_template('cp/form_footer');
169
170   $::lxdebug->leave_sub;
171 }
172
173 sub update {
174   $lxdebug->enter_sub();
175
176   $auth->assert('cash');
177
178   my ($buysell, $updated, $exchangerate, $amount);
179
180   if ($form->{vc} eq 'customer') {
181     $buysell = "buy";
182   } else {
183     $buysell = "sell";
184   }
185
186   # search by invoicenumber,
187   if ($form->{invnumber}) {
188     $form->{open} ='Y'; # only open invoices
189     if ($form->{ARAP} eq 'AR'){
190       # ar_transactions automatically searches by $form->{customer_id} or else
191       # $form->{customer} if available, and these variables will always be set
192       # so we have to empty these values first
193       $form->{customer_id} = '';
194       $form->{customer} = '';
195       AR->ar_transactions(\%myconfig, \%$form);
196
197       # if you search for invoice '11' ar_transactions will also match invoices
198       # 112, 211, ... due to the LIKE
199
200       # so there is now an extra loop that tries to match the invoice number
201       # exactly among all returned results, and then passes the customer_id instead of the name
202       # because the name may not be unique
203
204       my $found_exact_invnumber_match = 0;
205       foreach my $i ( @{ $form->{AR} } ) {
206         next unless $i->{invnumber} eq $form->{invnumber};
207         # found exactly matching invnumber
208         $form->{customer_id} = $i->{customer_id};
209         $found_exact_invnumber_match = 1;
210       };
211
212       unless ( $found_exact_invnumber_match ) {
213         # use first returned entry, may not be the correct one if invnumber doesn't
214         # match uniquely
215         $form->{customer_id} = $form->{AR}[0]{customer_id};
216       };
217     } else {
218       # s.o. nur für zahlungsausgang
219       AP->ap_transactions(\%myconfig, \%$form);
220       $form->{vendor_id} = $form->{AP}[0]{vendor_id};
221     }
222   }
223
224   # determine customer/vendor
225   my $vc = $form->{vc};
226   if (($form->{"previous_${vc}_id"} || $form->{"${vc}_id"}) != $form->{"${vc}_id"}) {
227     IS->get_customer(\%myconfig, \%$form);
228   }
229
230   $form->{oldcurrency} = $form->{currency};
231
232   # get open invoices from ar/ap using a.${vc}_id, i.e. customer_id
233   CP->get_openinvoices(\%myconfig, \%$form) if $form->{"${vc}_id"};
234
235   if (!$form->{forex}) {        # read exchangerate from input field (not hidden)
236     $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate});
237   }
238   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{datepaid}, $buysell);
239   $form->{exchangerate} = $form->{forex} if $form->{forex};
240
241   $amount = $form->{amount} = $form->parse_amount(\%myconfig, $form->{amount});
242
243   if ($form->{"${vc}_id"}) {
244     $form->{rowcount} = 0;
245
246     $form->{queued} = "";
247
248     my $i = 0;
249     foreach my $ref (@{ $form->{PR} }) {
250       $i++;
251       $form->{"id_$i"}        = $ref->{id};
252       $form->{"invnumber_$i"} = $ref->{invnumber};
253       $form->{"transdate_$i"} = $ref->{transdate};
254       $ref->{exchangerate} = 1 unless $ref->{exchangerate};
255       $form->{"amount_$i"} = $ref->{amount} / $ref->{exchangerate};
256       $form->{"due_$i"}    =
257         ($ref->{amount} - $ref->{paid}) / $ref->{exchangerate};
258       $form->{"checked_$i"} = "";
259       $form->{"paid_$i"}    = "";
260
261       # need to format
262       map {
263         $form->{"${_}_$i"} =
264           $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2)
265       } qw(amount due);
266
267     }
268     $form->{rowcount} = $i;
269   }
270
271   # recalculate
272
273   # Modified from $amount = $form->{amount} by J.Zach to update amount to total
274   # payment amount in Zahlungsausgang
275   $amount = 0;
276   for my $i (1 .. $form->{rowcount}) {
277
278     map {
279       $form->{"${_}_$i"} =
280         $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
281     } qw(amount due paid);
282
283     if ($form->{"checked_$i"}) {
284
285       # calculate paid_$i
286       if (!$form->{"paid_$i"}) {
287         $form->{"paid_$i"} = $form->{"due_$i"};
288       }
289
290       # Modified by J.Zach, see abovev
291       $amount += $form->{"paid_$i"};
292
293     } else {
294       $form->{"paid_$i"} = "";
295     }
296
297     map {
298       $form->{"${_}_$i"} =
299         $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2)
300     } qw(amount due paid);
301
302   }
303
304   # Line added by J.Zach, see above
305   $form->{amount}=$amount;
306
307   &form_header;
308   list_invoices() if $form->{"${vc}_id"};
309   &form_footer;
310
311   $lxdebug->leave_sub();
312 }
313
314 sub post {
315   $lxdebug->enter_sub();
316
317   $auth->assert('cash');
318
319   &check_form;
320
321   if ($form->{currency} ne $form->{defaultcurrency}) {
322     $form->error($locale->text('Exchangerate missing!'))
323       unless $form->{exchangerate};
324   }
325
326   # Beim Aktualisieren wird das Konto übernommen
327   # und jetzt auch Beleg und Datum
328   $form->{callback} = "cp.pl?action=payment&vc=$form->{vc}&type=$form->{type}&account=$form->{account}&$form->{currency}" .
329                       "&datepaid=$form->{datepaid}&source=$form->{source}";
330
331   my $msg1 = $::form->{type} eq 'receipt' ? $::locale->text("Receipt posted!") : $::locale->text("Payment posted!");
332   my $msg2 = $::form->{type} eq 'receipt' ? $::locale->text("Cannot post Receipt!") : $::locale->text("Cannot post Payment!");
333
334   # Die Nachrichten (Receipt posted!) werden nicht angezeigt.
335   # Entweder wieder aktivieren oder komplett rausnehmen
336   $form->redirect($msg1) if (CP->process_payment(\%::myconfig, $::form));
337   $form->error($msg2);
338
339   $lxdebug->leave_sub();
340 }
341
342 sub check_form {
343   $lxdebug->enter_sub();
344
345   $auth->assert('cash');
346
347   my ($closedto, $datepaid, $amount);
348
349   my $vc = $form->{vc};
350   if (($form->{"previous_${vc}_id"} || $form->{"${vc}_id"}) != $form->{"${vc}_id"}) {
351     IS->get_customer(\%myconfig, $form) if $vc eq 'customer';
352     IR->get_vendor(\%myconfig, $form)   if $vc eq 'vendor';
353   }
354
355   if ($form->{currency} ne $form->{oldcurrency}) {
356     &update;
357     $::dispatcher->end_request;
358   }
359   $form->error($locale->text('Date missing!')) unless $form->{datepaid};
360   my $selected_check = 1;
361   for my $i (1 .. $form->{rowcount}) {
362     next unless $form->{"checked_$i"};
363     if (abs($form->parse_amount(\%myconfig, $form->{"paid_$i"}, 2)) < 0.01) {
364       $form->error($locale->text('Row #1: amount has to be different from zero.', $i));
365     }
366     undef $selected_check;
367   }
368   $form->error($locale->text('No transaction selected!')) if $selected_check;
369
370   $closedto = $form->datetonum($form->{closedto}, \%myconfig);
371   $datepaid = $form->datetonum($form->{datepaid}, \%myconfig);
372
373   $form->error($locale->text('Cannot process payment for a closed period!'))
374     if ($form->date_closed($form->{"datepaid"}, \%myconfig));
375
376   $amount = $form->parse_amount(\%myconfig, $form->{amount});
377   $form->{amount} = $amount;
378
379   for my $i (1 .. $form->{rowcount}) {
380     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
381       $amount -= $form->parse_amount(\%myconfig, $form->{"paid_$i"});
382
383       push(@{ $form->{paid}      ||= [] }, $form->{"paid_$i"});
384       push(@{ $form->{due}       ||= [] }, $form->{"due_$i"});
385       push(@{ $form->{invnumber} ||= [] }, $form->{"invnumber_$i"});
386       push(@{ $form->{invdate}   ||= [] }, $form->{"transdate_$i"});
387     }
388   }
389
390   if ($form->round_amount($amount, 2) != 0) {
391     push(@{ $form->{paid} }, $form->format_amount(\%myconfig, $amount, 2));
392     push(@{ $form->{due} }, $form->format_amount(\%myconfig, 0, "0"));
393     push(@{ $form->{invnumber} },
394          ($form->{ARAP} eq 'AR')
395          ? $locale->text('Deposit')
396          : $locale->text('Prepayment'));
397     push(@{ $form->{invdate} }, $form->{datepaid});
398   }
399
400   $lxdebug->leave_sub();
401 }
402
403 sub setup_cp_form_action_bar {
404   my (%params) = @_;
405
406   for my $bar ($::request->layout->get('actionbar')) {
407     $bar->add(
408       action => [
409         t8('Update'),
410         submit    => [ '#form', { action => "update" } ],
411         accesskey => 'enter',
412       ],
413       action => [
414         t8('Post'),
415         submit => [ '#form', { action => "post" } ],
416       ],
417     );
418   }
419 }