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