Merge pull request #7 from freiphone/master
[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., 51 Franklin Street, Fifth Floor, Boston,
28 # MA 02110-1335, USA.
29 #======================================================================
30 #
31 # Dunning process module
32 #
33 #======================================================================
34
35 use POSIX qw(strftime);
36
37 use SL::IS;
38 use SL::DN;
39 use SL::DB::Department;
40 use SL::DB::Dunning;
41 use SL::Helper::Flash qw(flash);
42 use SL::Locale::String qw(t8);
43 use SL::ReportGenerator;
44
45 require "bin/mozilla/common.pl";
46 require "bin/mozilla/reportgenerator.pl";
47 require "bin/mozilla/io.pl";
48
49 use strict;
50
51 1;
52
53 sub edit_config {
54   $main::lxdebug->enter_sub();
55
56   my $form     = $main::form;
57   my %myconfig = %main::myconfig;
58   my $locale   = $main::locale;
59
60   $main::auth->assert('config');
61
62   DN->get_config(\%myconfig, \%$form);
63   $form->get_lists('charts' => { 'key'       => 'ALL_CHARTS',
64                                  'transdate' => 'current_date' });
65
66   $form->{SELECT_AR_AMOUNT} = [];
67   $form->{SELECT_AR}        = [];
68
69   foreach my $chart (@{ $form->{ALL_CHARTS} }) {
70     $chart->{LINKS} = { map { $_, 1 } split m/:/, $chart->{link} };
71
72     if ($chart->{LINKS}->{AR}) {
73       $chart->{AR_selected} = "selected" if $chart->{id} == $form->{AR};
74       push @{ $form->{SELECT_AR} }, $chart;
75     }
76
77     if ($chart->{LINKS}->{AR_amount}) {
78       $chart->{AR_amount_fee_selected}      = "selected" if $chart->{id} == $form->{AR_amount_fee};
79       $chart->{AR_amount_interest_selected} = "selected" if $chart->{id} == $form->{AR_amount_interest};
80       push @{ $form->{SELECT_AR_AMOUNT} }, $chart;
81     }
82   }
83
84   $form->{title}      = $locale->text('Edit Dunning Process Config');
85   $form->{callback} ||= build_std_url("action=edit_config");
86
87   setup_dn_edit_config_action_bar();
88
89   $form->header();
90   print $form->parse_html_template("dunning/edit_config");
91
92   $main::lxdebug->leave_sub();
93 }
94
95 sub add {
96   $main::lxdebug->enter_sub();
97
98   my $form     = $main::form;
99   my %myconfig = %main::myconfig;
100   my $locale   = $main::locale;
101
102   $main::auth->assert('dunning_edit');
103
104   DN->get_config(\%myconfig, \%$form);
105
106   $form->{SHOW_DUNNING_LEVEL_SELECTION} = $form->{DUNNING}         && scalar @{ $form->{DUNNING} };
107   $form->{SHOW_DEPARTMENT_SELECTION}    = $form->{all_departments} && scalar @{ $form->{all_departments} || [] };
108
109   $form->{title}    = $locale->text('Start Dunning Process');
110
111   setup_dn_add_action_bar();
112   $form->header();
113
114   print $form->parse_html_template("dunning/add");
115
116   $main::lxdebug->leave_sub();
117 }
118
119 sub show_invoices {
120   $main::lxdebug->enter_sub();
121
122   my $form     = $main::form;
123   my %myconfig = %main::myconfig;
124   my $locale   = $main::locale;
125
126   $main::auth->assert('dunning_edit');
127
128   DN->get_invoices(\%myconfig, \%$form);
129   $form->{title} = $locale->text('Start Dunning Process');
130
131   foreach my $row (@{ $form->{DUNNINGS} }) {
132     $row->{DUNNING_CONFIG} = [ map +{ %{ $_ } }, @{ $form->{DUNNING_CONFIG} } ];
133
134     if ($row->{next_dunning_config_id}) {
135       map { $_->{SELECTED} = $_->{id} == $row->{next_dunning_config_id} } @{ $row->{DUNNING_CONFIG } };
136     }
137     map { $row->{$_} = $form->format_amount(\%myconfig, $row->{$_} * 1, 2) } qw(amount open_amount fee interest);
138
139     if ($row->{'language_id'}) {
140       $row->{language} = SL::DB::Manager::Language->find_by_or_create('id' => $row->{'language_id'})->{'description'};
141     }
142   }
143
144   $form->get_lists('printers'  => 'printers',
145                    'languages' => 'languages');
146
147   $form->{type}           = 'dunning';
148   $form->{rowcount}       = scalar @{ $form->{DUNNINGS} };
149   $form->{callback}     ||= build_std_url("action=show_invoices", qw(customer invnumber ordnumber groupinvoices minamount dunning_level notes));
150
151   $form->{PRINT_OPTIONS}  = print_options('inline'          => 1,
152                                           'no_queue'        => 1,
153                                           'no_postscript'   => 1,
154                                           'no_html'         => 1,
155                                           'no_opendocument' => 1,);
156
157   setup_dn_show_invoices_action_bar();
158   $form->header();
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 (scalar @{ $form->{DUNNING_PDFS} }) {
260     $form->{dunning_id} = strftime("%Y%m%d", localtime time) if scalar @{ $form->{DUNNING_PDFS}} > 1;
261     DN->melt_pdfs(\%myconfig, $form, $form->{copies});
262   }
263
264   # saving the history
265   if(!exists $form->{addition} && $form->{id} ne "") {
266     $form->{snumbers} = qq|dunning_id_| . $form->{"dunning_id"};
267     $form->{addition} = "DUNNING STARTED";
268     $form->save_history;
269   }
270   # /saving the history
271
272   if ($form->{media} eq 'printer') {
273     delete $form->{callback};
274     $form->redirect($locale->text('Dunning Process started for selected invoices!'));
275   }
276
277   $main::lxdebug->leave_sub();
278 }
279
280 sub set_email {
281   $main::lxdebug->enter_sub();
282
283   my $form     = $main::form;
284   my $locale   = $main::locale;
285
286   $main::auth->assert('dunning_edit');
287
288   $form->{"title"} = $locale->text("Set eMail text");
289   $form->header(no_layout => 1);
290   print($form->parse_html_template("dunning/set_email"));
291
292   $main::lxdebug->leave_sub();
293 }
294
295 sub search {
296   $main::lxdebug->enter_sub();
297
298   my $form     = $main::form;
299   my %myconfig = %main::myconfig;
300   my $locale   = $main::locale;
301
302   $main::auth->assert('dunning_edit');
303
304   $form->get_lists("customers"   => "ALL_CUSTOMERS",
305                    "departments" => "ALL_DEPARTMENTS");
306   $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
307
308   DN->get_config(\%myconfig, \%$form);
309
310   $form->{SHOW_DUNNING_LEVELS}   = scalar @{ $form->{DUNNING} };
311
312   $form->{title}    = $locale->text('Dunnings');
313
314   setup_dn_search_action_bar();
315   $form->header();
316
317   print $form->parse_html_template("dunning/search");
318
319   $main::lxdebug->leave_sub();
320
321 }
322
323 sub show_dunning {
324   $main::lxdebug->enter_sub();
325
326   my $form     = $main::form;
327   my %myconfig = %main::myconfig;
328   my $locale   = $main::locale;
329   my $cgi      = $::request->{cgi};
330
331   $main::auth->assert('dunning_edit');
332
333   my @filter_field_list = qw(customer_id customer dunning_level department_id invnumber ordnumber
334                              transdatefrom transdateto dunningfrom dunningto notes showold l_salesman salesman_id);
335
336   report_generator_set_default_sort('customername', 1);
337
338   DN->get_dunning(\%myconfig, \%$form);
339
340   if (!$form->{callback}) {
341     $form->{callback} = build_std_url("action=show_dunning", @filter_field_list);
342   }
343
344   $form->get_lists('printers'  => 'printers',
345                    'languages' => 'languages');
346
347   $form->{type}          = 'dunning';
348   $form->{PRINT_OPTIONS} = print_options('inline'          => 1,
349                                          'no_queue'        => 1,
350                                          'no_postscript'   => 1,
351                                          'no_html'         => 1,
352                                          'no_opendocument' => 1,);
353   $form->{title}         = $locale->text('Dunning overview');
354
355   my $report = SL::ReportGenerator->new(\%myconfig, $form);
356
357   $report->set_options('std_column_visibility' => 1,
358                        'title'                 => $form->{title});
359   $report->set_export_options('show_dunning', @filter_field_list, qw(sort sortdir));
360
361   my %column_defs         =  (
362     'checkbox'            => { 'text' => '', 'visible' => 'HTML' },
363     'dunning_description' => { 'text' => $locale->text('Dunning Level') },
364     'customername'        => { 'text' => $locale->text('Customername') },
365     'language'            => { 'text' => $locale->text('Language') },
366     'invnumber'           => { 'text' => $locale->text('Invnumber') },
367     'transdate'           => { 'text' => $locale->text('Invdate') },
368     'duedate'             => { 'text' => $locale->text('Invoice Duedate') },
369     'amount'              => { 'text' => $locale->text('Amount') },
370     'dunning_date'        => { 'text' => $locale->text('Dunning Date') },
371     'dunning_duedate'     => { 'text' => $locale->text('Dunning Duedate') },
372     'fee'                 => { 'text' => $locale->text('Total Fees') },
373     'interest'            => { 'text' => $locale->text('Interest') },
374     'salesman'            => { 'text' => $locale->text('Salesperson'), 'visible' => $form->{l_salesman} ? 1 : 0 },
375   );
376
377   $report->set_columns(%column_defs);
378   $report->set_column_order(qw(checkbox dunning_description customername language invnumber transdate
379                                duedate amount dunning_date dunning_duedate fee interest salesman));
380   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
381
382   my $edit_url  = sub { build_std_url('script=' . ($_[0]->{invoice} ? 'is' : 'ar') . '.pl', 'action=edit', 'callback') . '&id=' . $::form->escape($_[0]->{id}) };
383   my $print_url = sub { build_std_url('action=print_dunning', 'format=pdf', 'media=screen', 'dunning_id='.$_[0]->{dunning_id}, 'language_id=' . $_[0]->{language_id}) };
384   my $sort_url  = build_std_url('action=show_dunning', grep { $form->{$_} } @filter_field_list);
385
386   foreach my $name (qw(dunning_description customername invnumber transdate duedate dunning_date dunning_duedate salesman)) {
387     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
388     $column_defs{$name}->{link} = $sort_url . "&sort=$name&sortdir=$sortdir";
389   }
390
391   my %alignment = map { $_ => 'right' } qw(transdate duedate amount dunning_date dunning_duedate fee interest salesman);
392
393   my ($current_dunning_rows, $previous_dunning_id, $first_row_for_dunning);
394
395   $current_dunning_rows  = [];
396   $first_row_for_dunning = 1;
397   $form->{rowcount}      = scalar @{ $form->{DUNNINGS} };
398
399   my $i = 0;
400
401   foreach my $ref (@{ $form->{DUNNINGS} }) {
402     $i++;
403
404     if ($previous_dunning_id != $ref->{dunning_id}) {
405       $report->add_data($current_dunning_rows) if (scalar @{ $current_dunning_rows });
406       $current_dunning_rows  = [];
407       $first_row_for_dunning = 1;
408     }
409
410     if ($ref->{'language_id'}) {
411       $ref->{language} = SL::DB::Manager::Language->find_by('id' => $ref->{'language_id'})->{'description'};
412     }
413
414     my $row = { };
415     foreach my $column (keys %{ $ref }) {
416       $row->{$column} = {
417         'data'  => $first_row_for_dunning || (($column ne 'dunning_description') && ($column ne 'customername')) ? $ref->{$column} : '',
418
419         'align' => $alignment{$column},
420
421         'link'  => (  $column eq 'invnumber'           ? $edit_url->($ref)
422                     : $column eq 'dunning_description' ? $print_url->($ref)
423                     :                                    ''),
424       };
425     }
426
427     $row->{checkbox} = !$first_row_for_dunning ? { } : {
428       'raw_data' =>   $cgi->hidden('-name' => "dunning_id_$i", '-value' => $ref->{dunning_id})
429                     . $cgi->checkbox('-name' => "selected_$i", '-value' => 1, '-label' => ''),
430       'valign'   => 'center',
431       'align'    => 'center',
432     };
433
434     if ($first_row_for_dunning) {
435       $row->{language} = {'raw_data' => $cgi->hidden('-name' => "language_id_$i", '-value' => $ref->{language_id})
436                                         . " $ref->{language}" };
437     } else {
438       $row->{language} = { };
439     }
440
441     push @{ $current_dunning_rows }, $row;
442
443     $previous_dunning_id   = $ref->{dunning_id};
444     $first_row_for_dunning = 0;
445   }
446
447   $report->add_data($current_dunning_rows) if (scalar @{ $current_dunning_rows });
448
449   $report->set_options('raw_top_info_text'    => $form->parse_html_template('dunning/show_dunning_top'),
450                        'raw_bottom_info_text' => $form->parse_html_template('dunning/show_dunning_bottom'),
451                        'output_format'        => 'HTML',
452                        'attachment_basename'  => $locale->text('dunning_list') . strftime('_%Y%m%d', localtime time),
453     );
454
455   $report->set_options_from_form();
456
457   setup_dn_show_dunning_action_bar();
458   $report->generate_with_headers();
459
460   $main::lxdebug->leave_sub();
461
462 }
463
464 sub print_dunning {
465   $main::lxdebug->enter_sub();
466
467   my $form     = $main::form;
468
469   $main::auth->assert('dunning_edit');
470
471   $form->{rowcount}     = 1;
472   $form->{selected_1}   = 1;
473   $form->{dunning_id_1} = $form->{dunning_id};
474   $form->{language_id_1} = $form->{language_id};
475
476   print_multiple();
477
478   $main::lxdebug->leave_sub();
479 }
480
481 sub delete {
482   $main::auth->assert('dunning_edit');
483
484   my @dunning_ids = map { $::form->{"dunning_id_$_"} } grep { $::form->{"selected_$_"} } (1..$::form->{rowcount});
485
486   if (!scalar @dunning_ids) {
487     $::form->error($::locale->text('No dunnings have been selected for printing.'));
488   }
489
490   my $dunnings = SL::DB::Manager::Dunning->get_all(query => [ dunning_id => \@dunning_ids ]);
491
492   SL::DB::Dunning->new->db->with_transaction(sub {
493     for my $dunning (@$dunnings) {
494       SL::DB::Manager::Invoice->find_by(id => $dunning->trans_id)->update_attributes(dunning_config_id => undef);
495       $dunning->delete;
496     }
497   });
498
499   flash('info', t8('#1 dunnings have been deleted', scalar @$dunnings));
500
501   search();
502 }
503
504 sub print_multiple {
505   $main::lxdebug->enter_sub();
506
507   my $form     = $main::form;
508   my %myconfig = %main::myconfig;
509   my $locale   = $main::locale;
510
511   $main::auth->assert('dunning_edit');
512
513   $form->{title} = $locale->text('Print dunnings');
514
515   my @dunning_ids = map { $form->{"dunning_id_$_"} } grep { $form->{"selected_$_"} } (1..$form->{rowcount});
516   my @language_ids = map { $form->{"language_id_$_"} } grep { $form->{"selected_$_"} } (1..$form->{rowcount});
517
518   if (!scalar @dunning_ids) {
519     $form->error($locale->text('No dunnings have been selected for printing.'));
520   }
521
522   $form->{DUNNING_PDFS} = [];
523
524   my $saved_language_id = $form->{language_id};
525   my $i = 0;
526   foreach my $dunning_id (@dunning_ids) {
527     if (!$form->{force_lang}) {
528       $form->{language_id} = $language_ids[$i];
529     }
530     $form->{dunning_id} = $dunning_id;
531     DN->print_invoice_for_fees(\%myconfig, $form, $dunning_id);
532     DN->print_dunning(\%myconfig, $form, $dunning_id);
533     $i++;
534   }
535   $form->{language_id} = $saved_language_id;
536
537   if (scalar @{ $form->{DUNNING_PDFS} }) {
538     $form->{dunning_id} = strftime("%Y%m%d", localtime time) if scalar @{ $form->{DUNNING_PDFS}} > 1;
539     DN->melt_pdfs(\%myconfig, $form, $form->{copies});
540
541     if ($form->{media} eq 'printer') {
542       $form->header();
543       $form->info($locale->text('The dunnings have been printed.'));
544     }
545
546   } else {
547     $form->redirect($locale->text('Could not print dunning.'));
548   }
549
550   $main::lxdebug->leave_sub();
551 }
552
553 sub continue {
554   call_sub($main::form->{nextsub});
555 }
556
557 sub dispatcher {
558   foreach my $action (qw(delete print_multiple)) {
559     if ($::form->{"action_${action}"}) {
560       call_sub($action);
561       return;
562     }
563   }
564
565   $::form->error($::locale->text('No action defined.'));
566 }
567
568 sub setup_dn_add_action_bar {
569   my %params = @_;
570
571   for my $bar ($::request->layout->get('actionbar')) {
572     $bar->add(
573       action => [
574         t8('Search'),
575         submit    => [ '#form', { action => "show_invoices" } ],
576         accesskey => 'enter',
577       ],
578     );
579   }
580 }
581
582 sub setup_dn_show_invoices_action_bar {
583   my %params = @_;
584
585   for my $bar ($::request->layout->get('actionbar')) {
586     $bar->add(
587       action => [
588         t8('Create'),
589         submit    => [ '#form', { action => "save_dunning" } ],
590         checks    => [ [ 'kivi.check_if_entries_selected', '[name^=active_]' ] ],
591         accesskey => 'enter',
592         only_once => 1,
593       ],
594     );
595   }
596 }
597
598 sub setup_dn_search_action_bar {
599   my %params = @_;
600
601   for my $bar ($::request->layout->get('actionbar')) {
602     $bar->add(
603       action => [
604         t8('Search'),
605         submit    => [ '#form', { action => "show_dunning" } ],
606         accesskey => 'enter',
607       ],
608     );
609   }
610 }
611
612 sub setup_dn_show_dunning_action_bar {
613   my %params = @_;
614
615   for my $bar ($::request->layout->get('actionbar')) {
616     $bar->add(
617       action => [
618         t8('Print'),
619         submit    => [ '#form', { action => "print_multiple" } ],
620         checks    => [ [ 'kivi.check_if_entries_selected', '[name^=selected_]' ] ],
621         accesskey => 'enter',
622       ],
623
624       action => [
625         t8('Delete'),
626         submit  => [ '#form', { action => "delete" } ],
627         checks  => [ [ 'kivi.check_if_entries_selected', '[name^=selected_]' ] ],
628         confirm => $::locale->text('This resets the dunning process for the selected invoices. Posted dunning invoices will not be changed!'),
629       ],
630     );
631   }
632 }
633
634 sub setup_dn_edit_config_action_bar {
635   my %params = @_;
636
637   for my $bar ($::request->layout->get('actionbar')) {
638     $bar->add(
639       action => [
640         t8('Save'),
641         submit    => [ '#form', { action => "save" } ],
642         accesskey => 'enter',
643       ],
644     );
645   }
646 }
647
648 # end of main