Merge branch 'master' of vc.linet-services.de:public/lx-office-erp
[kivitendo-erp.git] / bin / mozilla / dn.pl
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2006
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) 1998-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 # Dunning process module
31 #
32 #======================================================================
33
34 use POSIX;
35
36 use SL::IS;
37 use SL::PE;
38 use SL::DN;
39 use SL::ReportGenerator;
40
41 require "bin/mozilla/common.pl";
42 require "bin/mozilla/reportgenerator.pl";
43 require "bin/mozilla/io.pl";
44
45 use strict;
46
47 1;
48
49 sub edit_config {
50   $main::lxdebug->enter_sub();
51
52   my $form     = $main::form;
53   my %myconfig = %main::myconfig;
54   my $locale   = $main::locale;
55
56   $main::auth->assert('config');
57
58   DN->get_config(\%myconfig, \%$form);
59   $form->get_lists('charts' => { 'key'       => 'ALL_CHARTS',
60                                  'transdate' => 'current_date' });
61
62   $form->{SELECT_AR_AMOUNT} = [];
63   $form->{SELECT_AR}        = [];
64
65   foreach my $chart (@{ $form->{ALL_CHARTS} }) {
66     $chart->{LINKS} = { map { $_, 1 } split m/:/, $chart->{link} };
67
68     if ($chart->{LINKS}->{AR}) {
69       $chart->{AR_selected} = "selected" if $chart->{id} == $form->{AR};
70       push @{ $form->{SELECT_AR} }, $chart;
71     }
72
73     if ($chart->{LINKS}->{AR_amount}) {
74       $chart->{AR_amount_fee_selected}      = "selected" if $chart->{id} == $form->{AR_amount_fee};
75       $chart->{AR_amount_interest_selected} = "selected" if $chart->{id} == $form->{AR_amount_interest};
76       push @{ $form->{SELECT_AR_AMOUNT} }, $chart;
77     }
78   }
79
80   $form->{title}      = $locale->text('Edit Dunning Process Config');
81   $form->{callback} ||= build_std_url("action=edit_config");
82
83   $form->header();
84   print $form->parse_html_template("dunning/edit_config");
85
86   $main::lxdebug->leave_sub();
87 }
88
89 sub add {
90   $main::lxdebug->enter_sub();
91
92   my $form     = $main::form;
93   my %myconfig = %main::myconfig;
94   my $locale   = $main::locale;
95
96   $main::auth->assert('dunning_edit');
97
98   # setup customer selection
99   $form->all_vc(\%myconfig, "customer", "AR");
100
101   DN->get_config(\%myconfig, \%$form);
102
103   $form->{SHOW_CUSTOMER_SELECTION}      = $form->{all_customer}    && scalar @{ $form->{all_customer} };
104   $form->{SHOW_DUNNING_LEVEL_SELECTION} = $form->{DUNNING}         && scalar @{ $form->{DUNNING} };
105   $form->{SHOW_DEPARTMENT_SELECTION}    = $form->{all_departments} && scalar @{ $form->{all_departments} || [] };
106
107   $form->{title}    = $locale->text('Start Dunning Process');
108   $form->{jsscript} = 1;
109   $form->{fokus}    = "search.customer";
110   $form->header();
111
112   print $form->parse_html_template("dunning/add");
113
114   $main::lxdebug->leave_sub();
115 }
116
117 sub show_invoices {
118   $main::lxdebug->enter_sub();
119
120   my $form     = $main::form;
121   my %myconfig = %main::myconfig;
122   my $locale   = $main::locale;
123
124   $main::auth->assert('dunning_edit');
125
126   DN->get_invoices(\%myconfig, \%$form);
127   $form->{title} = $locale->text('Start Dunning Process');
128
129   foreach my $row (@{ $form->{DUNNINGS} }) {
130     $row->{DUNNING_CONFIG} = [ map +{ %{ $_ } }, @{ $form->{DUNNING_CONFIG} } ];
131
132     if ($row->{next_dunning_config_id}) {
133       map { $_->{SELECTED} = $_->{id} == $row->{next_dunning_config_id} } @{ $row->{DUNNING_CONFIG } };
134     }
135     map { $row->{$_} = $form->format_amount(\%myconfig, $row->{$_} * 1, -2) } qw(amount open_amount fee interest);
136
137     if ($row->{'language_id'}) {
138       $row->{language} = SL::DB::Manager::Language->find_by('id' => $row->{'language_id'})->{'description'};
139     }
140   }
141
142   $form->get_lists('printers'  => 'printers',
143                    'languages' => 'languages');
144
145   $form->{type}           = 'dunning';
146   $form->{rowcount}       = scalar @{ $form->{DUNNINGS} };
147   $form->{jsscript}       = 1;
148   $form->{callback}     ||= build_std_url("action=show_invoices", qw(customer invnumber ordnumber groupinvoices minamount dunning_level notes));
149
150   $form->{PRINT_OPTIONS}  = print_options('inline'          => 1,
151                                           'no_queue'        => 1,
152                                           'no_postscript'   => 1,
153                                           'no_html'         => 1,
154                                           'no_opendocument' => 1,);
155
156   $form->header();
157   $form->{onload} = "document.getElementsByName('language_id')[0].disabled =
158         !document.getElementsByName('force_lang')[0].checked;";
159   print $form->parse_html_template("dunning/show_invoices");
160
161   $main::lxdebug->leave_sub();
162 }
163
164 sub save {
165   $main::lxdebug->enter_sub();
166
167   my $form     = $main::form;
168   my %myconfig = %main::myconfig;
169   my $locale   = $main::locale;
170
171   $main::auth->assert('config');
172
173   for my $i (1 .. $form->{rowcount}) {
174     if ($form->{"dunning_description_$i"} ne "") {
175       $form->isblank("dunning_level_$i", $locale->text('Dunning Level missing in row '). $i);
176       $form->isblank("dunning_description_$i", $locale->text('Dunning Description missing in row '). $i);
177       $form->isblank("terms_$i", $locale->text('Terms missing in row '). $i);
178       $form->isblank("payment_terms_$i", $locale->text('Payment Terms missing in row '). $i);
179     }
180   }
181
182   DN->save_config(\%myconfig, \%$form);
183   # saving the history
184   if(!exists $form->{addition} && $form->{id} ne "") {
185     $form->{snumbers} = qq|dunning_id_| . $form->{"dunning_id"};
186     $form->{addition} = "SAVED FOR DUNNING";
187     $form->save_history;
188   }
189   # /saving the history
190   $form->redirect($locale->text('Dunning Process Config saved!'));
191
192   $main::lxdebug->leave_sub();
193 }
194
195 sub save_dunning {
196   $main::lxdebug->enter_sub();
197
198   my $form     = $main::form;
199   my %myconfig = %main::myconfig;
200   my $locale   = $main::locale;
201
202   $main::auth->assert('dunning_edit');
203
204   my $active=1;
205   my @rows = ();
206   undef($form->{DUNNING_PDFS});
207
208   my $saved_language_id = $form->{language_id};
209
210   if ($form->{groupinvoices}) {
211     my %dunnings_for;
212
213     for my $i (1 .. $form->{rowcount}) {
214       next unless ($form->{"active_$i"});
215
216       $dunnings_for{$form->{"customer_id_$i"}} ||= {};
217       my $dunning_levels = $dunnings_for{$form->{"customer_id_$i"}};
218
219       $dunning_levels->{$form->{"next_dunning_config_id_$i"}} ||= [];
220       my $level = $dunning_levels->{$form->{"next_dunning_config_id_$i"}};
221
222       push @{ $level }, { "row"                    => $i,
223                           "invoice_id"             => $form->{"inv_id_$i"},
224                           "customer_id"            => $form->{"customer_id_$i"},
225                           "language_id"            => $form->{"language_id_$i"},
226                           "next_dunning_config_id" => $form->{"next_dunning_config_id_$i"},
227                           "email"                  => $form->{"email_$i"}, };
228     }
229
230     foreach my $levels (values %dunnings_for) {
231       foreach my $level (values %{ $levels }) {
232         next unless scalar @{ $level };
233         if (!$form->{force_lang}) {
234           $form->{language_id} = @{$level}[0]->{language_id};
235         }
236         DN->save_dunning(\%myconfig, $form, $level);
237       }
238     }
239
240   } else {
241     for my $i (1 .. $form->{rowcount}) {
242       next unless $form->{"active_$i"};
243
244       my $level = [ { "row"                    => $i,
245                       "invoice_id"             => $form->{"inv_id_$i"},
246                       "customer_id"            => $form->{"customer_id_$i"},
247                       "language_id"            => $form->{"language_id_$i"},
248                       "next_dunning_config_id" => $form->{"next_dunning_config_id_$i"},
249                       "email"                  => $form->{"email_$i"}, } ];
250       if (!$form->{force_lang}) {
251         $form->{language_id} = @{$level}[0]->{language_id};
252       }
253       DN->save_dunning(\%myconfig, $form, $level);
254     }
255   }
256
257   $form->{language_id} = $saved_language_id;
258
259   if($form->{DUNNING_PDFS}) {
260     DN->melt_pdfs(\%myconfig, $form, $form->{copies});
261   }
262
263   # saving the history
264   if(!exists $form->{addition} && $form->{id} ne "") {
265     $form->{snumbers} = qq|dunning_id_| . $form->{"dunning_id"};
266     $form->{addition} = "DUNNING STARTED";
267     $form->save_history;
268   }
269   # /saving the history
270
271   if ($form->{media} eq 'printer') {
272     delete $form->{callback};
273     $form->redirect($locale->text('Dunning Process started for selected invoices!'));
274   }
275
276   $main::lxdebug->leave_sub();
277 }
278
279 sub set_email {
280   $main::lxdebug->enter_sub();
281
282   my $form     = $main::form;
283   my $locale   = $main::locale;
284
285   $main::auth->assert('dunning_edit');
286
287   $form->{"title"} = $locale->text("Set eMail text");
288   $form->header();
289   print($form->parse_html_template("dunning/set_email"));
290
291   $main::lxdebug->leave_sub();
292 }
293
294 sub search {
295   $main::lxdebug->enter_sub();
296
297   my $form     = $main::form;
298   my %myconfig = %main::myconfig;
299   my $locale   = $main::locale;
300
301   $main::auth->assert('dunning_edit');
302
303   $form->get_lists("customers"   => "ALL_CUSTOMERS",
304                    "departments" => "ALL_DEPARTMENTS",
305                    "salesmen"     => "ALL_SALESMEN");
306
307   DN->get_config(\%myconfig, \%$form);
308
309   $form->{SHOW_CUSTOMER_DDBOX}   = scalar @{ $form->{ALL_CUSTOMERS} } <= $myconfig{vclimit};
310   $form->{SHOW_DEPARTMENT_DDBOX} = scalar @{ $form->{ALL_CUSTOMERS} };
311   $form->{SHOW_DUNNING_LEVELS}   = scalar @{ $form->{DUNNING} };
312
313   $form->{jsscript} = 1;
314   $form->{title}    = $locale->text('Dunnings');
315   $form->{fokus}    = "search.customer";
316   $form->{salesman_labels} = sub { $_[0]->{"name"} || $_[0]->{"login"} };
317
318   $form->header();
319
320   $form->{onload} = qq|focus()|
321     . qq|;setupDateFormat('|. $myconfig{dateformat} .qq|', '|. $locale->text("Falsches Datumsformat!") .qq|')|
322     . qq|;setupPoints('|. $myconfig{numberformat} .qq|', '|. $locale->text("wrongformat") .qq|')|;
323
324   print $form->parse_html_template("dunning/search");
325
326   $main::lxdebug->leave_sub();
327
328 }
329
330 sub show_dunning {
331   $main::lxdebug->enter_sub();
332
333   my $form     = $main::form;
334   my %myconfig = %main::myconfig;
335   my $locale   = $main::locale;
336   my $cgi      = $::request->{cgi};
337
338   $main::auth->assert('dunning_edit');
339
340   my @filter_field_list = qw(customer_id customer dunning_level department_id invnumber ordnumber
341                              transdatefrom transdateto dunningfrom dunningto notes showold l_salesman salesman_id);
342
343   report_generator_set_default_sort('customername', 1);
344
345   DN->get_dunning(\%myconfig, \%$form);
346
347   if (!$form->{callback}) {
348     $form->{callback} = build_std_url("action=show_dunning", @filter_field_list);
349   }
350
351   $form->get_lists('printers'  => 'printers',
352                    'languages' => 'languages');
353
354   $form->{type}          = 'dunning';
355   $form->{PRINT_OPTIONS} = print_options('inline'          => 1,
356                                          'no_queue'        => 1,
357                                          'no_postscript'   => 1,
358                                          'no_html'         => 1,
359                                          'no_opendocument' => 1,);
360   $form->{title}         = $locale->text('Dunning overview');
361
362   my $report = SL::ReportGenerator->new(\%myconfig, $form);
363
364   $report->set_options('std_column_visibility' => 1,
365                        'title'                 => $form->{title});
366   $report->set_export_options('show_dunning', @filter_field_list, qw(sort sortdir));
367
368   my %column_defs         =  (
369     'checkbox'            => { 'text' => '', 'visible' => 'HTML' },
370     'dunning_description' => { 'text' => $locale->text('Dunning Level') },
371     'customername'        => { 'text' => $locale->text('Customername') },
372     'language'            => { 'text' => $locale->text('Language') },
373     'invnumber'           => { 'text' => $locale->text('Invnumber') },
374     'transdate'           => { 'text' => $locale->text('Invdate') },
375     'duedate'             => { 'text' => $locale->text('Invoice Duedate') },
376     'amount'              => { 'text' => $locale->text('Amount') },
377     'dunning_date'        => { 'text' => $locale->text('Dunning Date') },
378     'dunning_duedate'     => { 'text' => $locale->text('Dunning Duedate') },
379     'fee'                 => { 'text' => $locale->text('Total Fees') },
380     'interest'            => { 'text' => $locale->text('Interest') },
381     'salesman'            => { 'text' => $locale->text('Salesperson'), 'visible' => $form->{l_salesman} ? 1 : 0 },
382   );
383
384   $report->set_columns(%column_defs);
385   $report->set_column_order(qw(checkbox dunning_description customername language invnumber transdate
386                                duedate amount dunning_date dunning_duedate fee interest salesman));
387   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
388
389   my $edit_url  = sub { build_std_url('script=' . ($_[0]->{invoice} ? 'is' : 'ar') . '.pl', 'action=edit', 'callback') . '&id=' . $::form->escape($_[0]->{id}) };
390   my $print_url = sub { build_std_url('action=print_dunning', 'format=pdf', 'media=screen', 'dunning_id='.$_[0]->{dunning_id}, 'language_id=' . $_[0]->{language_id}) };
391   my $sort_url  = build_std_url('action=show_dunning', grep { $form->{$_} } @filter_field_list);
392
393   foreach my $name (qw(dunning_description customername invnumber transdate duedate dunning_date dunning_duedate salesman)) {
394     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
395     $column_defs{$name}->{link} = $sort_url . "&sort=$name&sortdir=$sortdir";
396   }
397
398   my %alignment = map { $_ => 'right' } qw(transdate duedate amount dunning_date dunning_duedate fee interest salesman);
399
400   my ($current_dunning_rows, $previous_dunning_id, $first_row_for_dunning);
401
402   $current_dunning_rows  = [];
403   $first_row_for_dunning = 1;
404   $form->{rowcount}      = scalar @{ $form->{DUNNINGS} };
405
406   my $i = 0;
407
408   foreach my $ref (@{ $form->{DUNNINGS} }) {
409     $i++;
410
411     if ($previous_dunning_id != $ref->{dunning_id}) {
412       $report->add_data($current_dunning_rows) if (scalar @{ $current_dunning_rows });
413       $current_dunning_rows  = [];
414       $first_row_for_dunning = 1;
415     }
416
417     if ($ref->{'language_id'}) {
418       $ref->{language} = SL::DB::Manager::Language->find_by('id' => $ref->{'language_id'})->{'description'};
419     }
420
421     my $row = { };
422     foreach my $column (keys %{ $ref }) {
423       $row->{$column} = {
424         'data'  => $first_row_for_dunning || (($column ne 'dunning_description') && ($column ne 'customername')) ? $ref->{$column} : '',
425
426         'align' => $alignment{$column},
427
428         'link'  => (  $column eq 'invnumber'           ? $edit_url->($ref)
429                     : $column eq 'dunning_description' ? $print_url->($ref)
430                     :                                    ''),
431       };
432     }
433
434     $row->{checkbox} = !$first_row_for_dunning ? { } : {
435       'raw_data' =>   $cgi->hidden('-name' => "dunning_id_$i", '-value' => $ref->{dunning_id})
436                     . $cgi->checkbox('-name' => "selected_$i", '-value' => 1, '-label' => ''),
437       'valign'   => 'center',
438       'align'    => 'center',
439     };
440
441     if ($first_row_for_dunning) {
442       $row->{language} = {'raw_data' => $cgi->hidden('-name' => "language_id_$i", '-value' => $ref->{language_id})
443                                         . " $ref->{language}" };
444     } else {
445       $row->{language} = { };
446     }
447
448     push @{ $current_dunning_rows }, $row;
449
450     $previous_dunning_id   = $ref->{dunning_id};
451     $first_row_for_dunning = 0;
452   }
453
454   $report->add_data($current_dunning_rows) if (scalar @{ $current_dunning_rows });
455
456   $report->set_options('raw_top_info_text'    => $form->parse_html_template('dunning/show_dunning_top'),
457                        'raw_bottom_info_text' => $form->parse_html_template('dunning/show_dunning_bottom'),
458                        'output_format'        => 'HTML',
459                        'attachment_basename'  => $locale->text('dunning_list') . strftime('_%Y%m%d', localtime time),
460     );
461
462   $report->set_options_from_form();
463
464   $form->{onload} = "document.getElementsByName('language_id')[0].disabled =
465         !document.getElementsByName('force_lang')[0].checked;";
466   $report->generate_with_headers();
467
468   $main::lxdebug->leave_sub();
469
470 }
471
472 sub print_dunning {
473   $main::lxdebug->enter_sub();
474
475   my $form     = $main::form;
476
477   $main::auth->assert('dunning_edit');
478
479   $form->{rowcount}     = 1;
480   $form->{selected_1}   = 1;
481   $form->{dunning_id_1} = $form->{dunning_id};
482   $form->{language_id_1} = $form->{language_id};
483
484   print_multiple();
485
486   $main::lxdebug->leave_sub();
487 }
488
489 sub print_multiple {
490   $main::lxdebug->enter_sub();
491
492   my $form     = $main::form;
493   my %myconfig = %main::myconfig;
494   my $locale   = $main::locale;
495
496   $main::auth->assert('dunning_edit');
497
498   $form->{title} = $locale->text('Print dunnings');
499
500   my @dunning_ids = map { $form->{"dunning_id_$_"} } grep { $form->{"selected_$_"} } (1..$form->{rowcount});
501   my @language_ids = map { $form->{"language_id_$_"} } grep { $form->{"selected_$_"} } (1..$form->{rowcount});
502
503   if (!scalar @dunning_ids) {
504     $form->error($locale->text('No dunnings have been selected for printing.'));
505   }
506
507   $form->{DUNNING_PDFS} = [];
508
509   my $saved_language_id = $form->{language_id};
510   my $i = 0;
511   foreach my $dunning_id (@dunning_ids) {
512     if (!$form->{force_lang}) {
513       $form->{language_id} = $language_ids[$i];
514     }
515     DN->print_invoice_for_fees(\%myconfig, $form, $dunning_id);
516     DN->print_dunning(\%myconfig, $form, $dunning_id);
517     $i++;
518   }
519   $form->{language_id} = $saved_language_id;
520
521   if (scalar @{ $form->{DUNNING_PDFS} }) {
522     $form->{dunning_id} = strftime("%Y%m%d", localtime time);
523     DN->melt_pdfs(\%myconfig, $form, $form->{copies});
524
525     if ($form->{media} eq 'printer') {
526       $form->header();
527       $form->info($locale->text('The dunnings have been printed.'));
528     }
529
530   } else {
531     $form->redirect($locale->text('Could not print dunning.'));
532   }
533
534   $main::lxdebug->leave_sub();
535 }
536
537 sub continue {
538   call_sub($main::form->{nextsub});
539 }
540
541 # end of main