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