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