Rabatt in Kunden-/Lieferanten-Bericht mit aufnehmen können.
[kivitendo-erp.git] / bin / mozilla / ct.pl
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
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 #  Contributors: Reed White <alta@alta-research.com>
16 #
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
21 #
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
30 #
31 # customer/vendor module
32 #
33 #======================================================================
34
35 # $locale->text('Customers')
36 # $locale->text('Vendors')
37 # $locale->text('Add Customer')
38 # $locale->text('Add Vendor')
39 # $locale->text('Edit Customer')
40 # $locale->text('Edit Vendor')
41 # $locale->text('Customer saved!')
42 # $locale->text('Vendor saved!')
43 # $locale->text('Customer deleted!')
44 # $locale->text('Cannot delete customer!')
45 # $locale->text('Vendor deleted!')
46 # $locale->text('Cannot delete vendor!')
47
48 use POSIX qw(strftime);
49
50 use SL::CT;
51 use SL::CVar;
52 use SL::Request qw(flatten);
53 use SL::DB::Business;
54 use SL::DB::Default;
55 use SL::Helper::Flash;
56 use SL::ReportGenerator;
57
58 require "bin/mozilla/common.pl";
59 require "bin/mozilla/reportgenerator.pl";
60
61 use strict;
62 1;
63
64 # end of main
65
66 sub add {
67   $main::lxdebug->enter_sub();
68
69   $main::auth->assert('customer_vendor_edit');
70
71   my $form     = $main::form;
72   my %myconfig = %main::myconfig;
73
74   $form->{title}    = "Add";
75   $form->{callback} = "$form->{script}?action=add&db=$form->{db}" unless $form->{callback};
76
77   CT->populate_drop_down_boxes(\%myconfig, \%$form);
78
79   &form_header;
80   &form_footer;
81
82   $main::lxdebug->leave_sub();
83 }
84
85 sub search {
86   $main::lxdebug->enter_sub();
87
88   $main::auth->assert('customer_vendor_edit');
89
90   my $form     = $main::form;
91   my $locale   = $main::locale;
92
93   $form->{IS_CUSTOMER} = $form->{db} eq 'customer';
94
95   $form->get_lists("business_types" => "ALL_BUSINESS_TYPES");
96   $form->{SHOW_BUSINESS_TYPES} = scalar @{ $form->{ALL_BUSINESS_TYPES} } > 0;
97
98   $form->{CUSTOM_VARIABLES}                  = CVar->get_configs('module' => 'CT');
99   ($form->{CUSTOM_VARIABLES_FILTER_CODE},
100    $form->{CUSTOM_VARIABLES_INCLUSION_CODE}) = CVar->render_search_options('variables'      => $form->{CUSTOM_VARIABLES},
101                                                                            'include_prefix' => 'l_',
102                                                                            'include_value'  => 'Y');
103
104   $form->{title}    = $form->{IS_CUSTOMER} ? $locale->text('Customers') : $locale->text('Vendors');
105
106   $form->header();
107   print $form->parse_html_template('ct/search');
108
109   $main::lxdebug->leave_sub();
110 }
111
112 sub search_contact {
113   $::lxdebug->enter_sub;
114   $::auth->assert('customer_vendor_edit');
115
116   $::form->{CUSTOM_VARIABLES}                  = CVar->get_configs('module' => 'Contacts');
117   ($::form->{CUSTOM_VARIABLES_FILTER_CODE},
118    $::form->{CUSTOM_VARIABLES_INCLUSION_CODE}) = CVar->render_search_options('variables'    => $::form->{CUSTOM_VARIABLES},
119                                                                            'include_prefix' => 'l.',
120                                                                            'filter_prefix'  => 'filter.',
121                                                                            'include_value'  => 'Y');
122
123   $::form->{title} = $::locale->text('Search contacts');
124   $::form->header;
125   print $::form->parse_html_template('ct/search_contact');
126
127   $::lxdebug->leave_sub;
128 }
129
130 sub list_names {
131   $main::lxdebug->enter_sub();
132
133   $main::auth->assert('customer_vendor_edit');
134
135   my $form     = $main::form;
136   my %myconfig = %main::myconfig;
137   my $locale   = $main::locale;
138
139   $form->{IS_CUSTOMER} = $form->{db} eq 'customer';
140
141   report_generator_set_default_sort('name', 1);
142
143   CT->search(\%myconfig, \%$form);
144
145   my $cvar_configs = CVar->get_configs('module' => 'CT');
146
147   my @options;
148   if ($form->{status} eq 'all') {
149     push @options, $locale->text('All');
150   } elsif ($form->{status} eq 'orphaned') {
151     push @options, $locale->text('Orphaned');
152   }
153
154   push @options, $locale->text('Name') . " : $form->{name}"                                    if $form->{name};
155   push @options, $locale->text('Contact') . " : $form->{contact}"                              if $form->{contact};
156   push @options, $locale->text('Number') . qq| : $form->{"$form->{db}number"}|                 if $form->{"$form->{db}number"};
157   push @options, $locale->text('E-mail') . " : $form->{email}"                                 if $form->{email};
158   push @options, $locale->text('Contact person (surname)')           . " : $form->{cp_name}"   if $form->{cp_name};
159   push @options, $locale->text('Billing/shipping address (city)')    . " : $form->{addr_city}" if $form->{addr_city};
160   push @options, $locale->text('Billing/shipping address (zipcode)') . " : $form->{zipcode}"   if $form->{addr_zipcode};
161   push @options, $locale->text('Billing/shipping address (street)')  . " : $form->{street}"    if $form->{addr_street};
162   push @options, $locale->text('Billing/shipping address (country)') . " : $form->{country}"   if $form->{addr_country};
163
164   if ($form->{business_id}) {
165     my $business = SL::DB::Manager::Business->find_by(id => $form->{business_id});
166     if ($business) {
167       my $label = $form->{IS_CUSTOMER} ? $::locale->text('Customer type') : $::locale->text('Vendor type');
168       push @options, $label . " : " . $business->description;
169     }
170   }
171
172   my @columns = (
173     'id',        'name',      "$form->{db}number",   'contact',   'phone',    'discount',
174     'fax',       'email',     'taxnumber',           'street',    'zipcode' , 'city',
175     'business',  'invnumber', 'ordnumber',           'quonumber', 'salesman', 'country'
176   );
177
178   my @includeable_custom_variables = grep { $_->{includeable} } @{ $cvar_configs };
179   my @searchable_custom_variables  = grep { $_->{searchable} }  @{ $cvar_configs };
180   my %column_defs_cvars            = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @includeable_custom_variables;
181
182   push @columns, map { "cvar_$_->{name}" } @includeable_custom_variables;
183
184   my %column_defs = (
185     'id'                => { 'text' => $locale->text('ID'), },
186     "$form->{db}number" => { 'text' => $locale->text('Number'), },
187     'name'              => { 'text' => $form->{IS_CUSTOMER} ? $::locale->text('Customer Name') : $::locale->text('Vendor Name'), },
188     'contact'           => { 'text' => $locale->text('Contact'), },
189     'phone'             => { 'text' => $locale->text('Phone'), },
190     'fax'               => { 'text' => $locale->text('Fax'), },
191     'email'             => { 'text' => $locale->text('E-mail'), },
192     'cc'                => { 'text' => $locale->text('Cc'), },
193     'taxnumber'         => { 'text' => $locale->text('Tax Number'), },
194     'business'          => { 'text' => $locale->text('Type of Business'), },
195     'invnumber'         => { 'text' => $locale->text('Invoice'), },
196     'ordnumber'         => { 'text' => $form->{IS_CUSTOMER} ? $locale->text('Sales Order') : $locale->text('Purchase Order'), },
197     'quonumber'         => { 'text' => $form->{IS_CUSTOMER} ? $locale->text('Quotation')   : $locale->text('Request for Quotation'), },
198     'street'            => { 'text' => $locale->text('Street'), },
199     'zipcode'           => { 'text' => $locale->text('Zipcode'), },
200     'city'              => { 'text' => $locale->text('City'), },
201     'country'           => { 'text' => $locale->text('Country'), },
202     'salesman'          => { 'text' => $locale->text('Salesman'), },
203     'discount'          => { 'text' => $locale->text('Discount'), },
204     %column_defs_cvars,
205   );
206
207   map { $column_defs{$_}->{visible} = $form->{"l_$_"} eq 'Y' } @columns;
208
209   my @hidden_variables  = ( qw(
210       db status obsolete name contact email cp_name addr_street addr_zipcode
211       addr_city addr_country business_id
212     ), "$form->{db}number",
213     map({ "cvar_$_->{name}" } @searchable_custom_variables),
214     map({'cvar_'. $_->{name} .'_qtyop'} grep({$_->{type} eq 'number'} @searchable_custom_variables)),
215     map({ "l_$_" } @columns),
216   );
217
218   my @hidden_nondefault = grep({ $form->{$_} } @hidden_variables);
219   my $callback          = build_std_url('action=list_names', grep { $form->{$_} } @hidden_nondefault);
220   $form->{callback}     = "$callback&sort=" . E($form->{sort}) . "&sortdir=" . E($form->{sortdir});
221
222   foreach (@columns) {
223     my $sortdir              = $form->{sort} eq $_ ? 1 - $form->{sortdir} : $form->{sortdir};
224     $column_defs{$_}->{link} = "${callback}&sort=${_}&sortdir=${sortdir}";
225   }
226
227   my ($ordertype, $quotationtype, $attachment_basename);
228   if ($form->{IS_CUSTOMER}) {
229     $form->{title}       = $locale->text('Customers');
230     $ordertype           = 'sales_order';
231     $quotationtype       = 'sales_quotation';
232     $attachment_basename = $locale->text('customer_list');
233
234   } else {
235     $form->{title}       = $locale->text('Vendors');
236     $ordertype           = 'purchase_order';
237     $quotationtype       = 'request_quotation';
238     $attachment_basename = $locale->text('vendor_list');
239   }
240
241   my $report = SL::ReportGenerator->new(\%myconfig, $form);
242
243   $report->set_options('top_info_text'         => join("\n", @options),
244                        'raw_bottom_info_text'  => $form->parse_html_template('ct/list_names_bottom'),
245                        'output_format'         => 'HTML',
246                        'title'                 => $form->{title},
247                        'attachment_basename'   => $attachment_basename . strftime('_%Y%m%d', localtime time),
248     );
249   $report->set_options_from_form();
250   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
251
252   $report->set_columns(%column_defs);
253   $report->set_column_order(@columns);
254
255   $report->set_export_options('list_names', @hidden_variables, qw(sort sortdir));
256
257   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
258
259   CVar->add_custom_variables_to_report('module'         => 'CT',
260                                        'trans_id_field' => 'id',
261                                        'configs'        => $cvar_configs,
262                                        'column_defs'    => \%column_defs,
263                                        'data'           => $form->{CT});
264
265   my $previous_id;
266
267   foreach my $ref (@{ $form->{CT} }) {
268     my $row = { map { $_ => { 'data' => '' } } @columns };
269
270     if ($ref->{id} ne $previous_id) {
271       $previous_id = $ref->{id};
272       $ref->{discount} = $form->format_amount(\%myconfig, $ref->{discount} * 100.0, 2);
273       map { $row->{$_}->{data} = $ref->{$_} } @columns;
274
275       $row->{name}->{link}  = build_std_url('script=controller.pl', 'action=CustomerVendor/edit', 'id=' . E($ref->{id}), 'callback', @hidden_nondefault);
276       $row->{email}->{link} = 'mailto:' . E($ref->{email});
277     }
278
279     my $base_url              = build_std_url("script=$ref->{module}.pl", 'action=edit', 'id=' . E($ref->{invid}), 'callback', @hidden_nondefault);
280     $row->{invnumber}->{link} = $base_url;
281     $row->{ordnumber}->{link} = $base_url . "&type=${ordertype}";
282     $row->{quonumber}->{link} = $base_url . "&type=${quotationtype}";
283     my $column                = $ref->{formtype} eq 'invoice' ? 'invnumber' : $ref->{formtype} eq 'order' ? 'ordnumber' : 'quonumber';
284     $row->{$column}->{data}   = $ref->{$column};
285
286     $report->add_data($row);
287   }
288
289   $report->generate_with_headers();
290
291   $main::lxdebug->leave_sub();
292 }
293
294 sub list_contacts {
295   $::lxdebug->enter_sub;
296   $::auth->assert('customer_vendor_edit');
297
298   $::form->{sortdir} = 1 unless defined $::form->{sortdir};
299
300   my @contacts     = CT->search_contacts(
301     search_term => $::form->{search_term},
302     filter      => $::form->{filter},
303   );
304
305   my $cvar_configs = CVar->get_configs('module' => 'Contacts');
306
307   my @columns      = qw(
308     cp_id vcname vcnumber cp_name cp_givenname cp_street cp_zipcode cp_city cp_phone1 cp_phone2 cp_privatphone
309     cp_mobile1 cp_mobile2 cp_fax cp_email cp_privatemail cp_abteilung cp_position cp_birthday cp_gender
310   );
311
312   my @includeable_custom_variables = grep { $_->{includeable} } @{ $cvar_configs };
313   my @searchable_custom_variables  = grep { $_->{searchable} }  @{ $cvar_configs };
314   my %column_defs_cvars            = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @includeable_custom_variables;
315
316   push @columns, map { "cvar_$_->{name}" } @includeable_custom_variables;
317
318   my @visible_columns;
319   if ($::form->{l}) {
320     @visible_columns = grep { $::form->{l}{$_} } @columns;
321     push @visible_columns, qw(cp_phone1 cp_phone2)   if $::form->{l}{cp_phone};
322     push @visible_columns, qw(cp_mobile1 cp_mobile2) if $::form->{l}{cp_mobile};
323   } else {
324    @visible_columns = qw(vcname vcnumber cp_name cp_givenname cp_phone1 cp_phone2 cp_mobile1 cp_email);
325   }
326
327   my %column_defs  = (
328     'cp_id'        => { 'text' => $::locale->text('ID'), },
329     'vcname'       => { 'text' => $::locale->text('Customer/Vendor'), },
330     'vcnumber'     => { 'text' => $::locale->text('Customer/Vendor Number'), },
331     'cp_name'      => { 'text' => $::locale->text('Name'), },
332     'cp_givenname' => { 'text' => $::locale->text('Given Name'), },
333     'cp_street'    => { 'text' => $::locale->text('Street'), },
334     'cp_zipcode'   => { 'text' => $::locale->text('Zipcode'), },
335     'cp_city'      => { 'text' => $::locale->text('City'), },
336     'cp_phone1'    => { 'text' => $::locale->text('Phone1'), },
337     'cp_phone2'    => { 'text' => $::locale->text('Phone2'), },
338     'cp_mobile1'   => { 'text' => $::locale->text('Mobile1'), },
339     'cp_mobile2'   => { 'text' => $::locale->text('Mobile2'), },
340     'cp_email'     => { 'text' => $::locale->text('E-mail'), },
341     'cp_abteilung' => { 'text' => $::locale->text('Department'), },
342     'cp_position'  => { 'text' => $::locale->text('Function/position'), },
343     'cp_birthday'  => { 'text' => $::locale->text('Birthday'), },
344     'cp_gender'    => { 'text' => $::locale->text('Gender'), },
345     'cp_fax'       => { 'text' => $::locale->text('Fax'), },
346     'cp_privatphone' => { 'text' => $::locale->text('Private Phone') },
347     'cp_privatemail' => { 'text' => $::locale->text('Private E-mail') },
348     %column_defs_cvars,
349   );
350
351   map { $column_defs{$_}->{visible} = 1 } @visible_columns;
352
353   my @hidden_variables  = (qw(search_term filter l));
354   my $hide_vars         = { map { $_ => $::form->{$_} } @hidden_variables };
355   my @hidden_nondefault = grep({ $::form->{$_} } @hidden_variables);
356   my $callback          = build_std_url('action=list_contacts', join '&', map { E($_->[0]) . '=' . E($_->[1]) } @{ flatten($hide_vars) });
357   $::form->{callback}     = "$callback&sort=" . E($::form->{sort});
358
359   map { $column_defs{$_}->{link} = "${callback}&sort=${_}&sortdir=" . ($::form->{sort} eq $_ ? 1 - $::form->{sortdir} : $::form->{sortdir}) } @columns;
360
361   $::form->{title} = $::locale->text('Contacts');
362
363   my $report     = SL::ReportGenerator->new(\%::myconfig, $::form);
364
365   my @options;
366   push @options, $::locale->text('Search term') . ': ' . $::form->{search_term} if $::form->{search_term};
367   for (qw(cp_name cp_givenname cp_title cp_email cp_abteilung cp_project)) {
368     push @options, $column_defs{$_}{text} . ': ' . $::form->{filter}{$_} if $::form->{filter}{$_};
369   }
370   if ($::form->{filter}{status}) {
371     push @options, $::locale->text('Status') . ': ' . (
372       $::form->{filter}{status} =~ /active/   ? $::locale->text('Active')   :
373       $::form->{filter}{status} =~ /orphaned/ ? $::locale->text('Orphaned') :
374       $::form->{filter}{status} =~ /all/      ? $::locale->text('All')      : ''
375     );
376   }
377
378
379   $report->set_options('top_info_text'       => join("\n", @options),
380                        'output_format'       => 'HTML',
381                        'title'               => $::form->{title},
382                        'attachment_basename' => $::locale->text('contact_list') . strftime('_%Y%m%d', localtime time),
383     );
384   $report->set_options_from_form;
385
386   $report->set_columns(%column_defs);
387   $report->set_column_order(@columns);
388
389   $report->set_export_options('list_contacts', @hidden_variables);
390
391   $report->set_sort_indicator($::form->{sort}, $::form->{sortdir});
392
393   CVar->add_custom_variables_to_report('module'         => 'Contacts',
394                                        'trans_id_field' => 'cp_id',
395                                        'configs'        => $cvar_configs,
396                                        'column_defs'    => \%column_defs,
397                                        'data'           => \@contacts);
398
399
400   foreach my $ref (@contacts) {
401     my $row = { map { $_ => { 'data' => $ref->{$_} } } @columns };
402
403     $row->{vcname}->{link}   = build_std_url('script=controller.pl', 'action=CustomerVendor/edit', 'id=' . E($ref->{vcid}), 'db=' . E($ref->{db}), 'callback', @hidden_nondefault);
404     $row->{vcnumber}->{link} = $row->{vcname}->{link};
405
406     for (qw(cp_email cp_privatemail)) {
407       $row->{$_}->{link} = 'mailto:' . E($ref->{$_}) if $ref->{$_};
408     }
409
410     $report->add_data($row);
411   }
412
413   $report->generate_with_headers;
414
415   $::lxdebug->leave_sub;
416 }
417
418 sub edit {
419   $main::lxdebug->enter_sub();
420
421   $main::auth->assert('customer_vendor_edit');
422
423   my $form     = $main::form;
424   my %myconfig = %main::myconfig;
425
426   # show history button
427   $form->{javascript} = qq|<script type=text/javascript src=js/show_history.js></script>|;
428   #/show hhistory button
429
430   CT->get_tuple(\%myconfig, \%$form);
431   CT->populate_drop_down_boxes(\%myconfig, \%$form);
432
433   $form->{title} = "Edit";
434
435   # format discount
436   $form->{discount} *= 100;
437   # format uri
438   $form->{homepage} = 'http://' . $form->{homepage} unless ((!$form->{homepage}) || $form->{homepage} =~ m|^https?://|);
439
440   &form_header;
441   &form_footer;
442
443   $main::lxdebug->leave_sub();
444 }
445
446 sub _shipto_label {
447   my $s = shift(@_);
448   join('; ', grep { $_ } map { $s->{"shipto$_"} } qw(name department_1 street city)) || ' '
449 }
450
451 sub _contacts_label {
452   join ", ", grep { $_ } $_[0]->{cp_name}, $_[0]->{cp_givenname};
453 }
454
455 sub form_header {
456   $main::lxdebug->enter_sub();
457
458   $main::auth->assert('customer_vendor_edit');
459
460   my $form     = $main::form;
461   my %myconfig = %main::myconfig;
462   my $locale   = $main::locale;
463
464   $form->get_lists(taxzones   => "ALL_TAXZONES",
465                    currencies => "ALL_CURRENCIES");
466   $form->get_pricegroup(\%myconfig, { all => 1 });
467
468   $form->get_lists(customers => { key => "ALL_SALESMAN_CUSTOMERS", business_is_salesman => 1 }) if $::instance_conf->get_vertreter;
469   $form->{ALL_EMPLOYEES}          = SL::DB::Manager::Employee->get_all(query => [ or => [ id => $::form->{FU_created_for_user},  deleted => 0 ] ]);
470   $form->{ALL_SALESMEN}           = SL::DB::Manager::Employee->get_all(query => [ or => [ id => $::form->{salesman_id},  deleted => 0 ] ]);
471   $form->{USER}                   = SL::DB::Manager::Employee->current;
472
473   $form->{taxincluded}    = ($form->{taxincluded}) ? "checked" : "";
474   $form->{is_customer}    = $form->{db}     eq 'customer';
475   $form->{shipto_label}   = \&_shipto_label;
476   $form->{contacts_label} = \&_contacts_label;
477   $form->{taxzone_id}     = 0                                                               if !$form->{id};
478   $form->{SHIPTO_ALL}     = [ +{ shipto_id => '0', shiptoname => $::locale->text('All') }, @{ $form->{SHIPTO} } ];
479
480   $form->{title} = $form->{title_save}
481                 || $locale->text("$form->{title} " . ucfirst $form->{db}) . ($form->{title} eq "Edit" ? " $form->{name}" : '');
482
483   CT->query_titles_and_greetings(\%myconfig, \%$form);
484   map { $form->{"MB_$_"} = [ map +{ id => $_, description => $_ }, @{ $form->{$_} } ] } qw(COMPANY_GREETINGS);
485
486   $form->{NOTES} ||= [ ];
487
488   if (!$form->{'language_id'}) {
489     my $l_id = SL::DB::Default->get->{'language_id'};
490     if ($l_id) {
491       $form->{'default_language_id'} = $l_id;
492     }
493   }
494
495   if (!$form->{'id'}) {
496     $form->{'currency'} = $form->get_default_currency(\%myconfig);
497   } else {
498     $form->{currency} = $form->{curr};
499   }
500
501   $::form->{CUSTOM_VARIABLES} = { };
502   my %specs = ( CT       => { field => 'id',    name_prefix => '',   },
503                 Contacts => { field => 'cp_id', name_prefix => 'cp', },
504               );
505
506   for my $module (keys %specs) {
507     my $spec = $specs{$module};
508
509     $::form->{CUSTOM_VARIABLES}->{$module} = CVar->get_custom_variables(module => $module, trans_id => $::form->{ $spec->{field} });
510     CVar->render_inputs(variables => $::form->{CUSTOM_VARIABLES}->{$module}, name_prefix => $spec->{name_prefix})
511       if scalar @{ $::form->{CUSTOM_VARIABLES}->{$module} };
512   }
513
514   $form->header;
515   print $form->parse_html_template('ct/form_header');
516
517   $main::lxdebug->leave_sub();
518 }
519
520 sub form_footer {
521   $main::lxdebug->enter_sub();
522
523   $main::auth->assert('customer_vendor_edit');
524
525   my $form     = $main::form;
526
527   print $form->parse_html_template('ct/form_footer', { is_orphaned => $form->{status} eq 'orphaned',
528                                                        is_customer => $form->{db}     eq 'customer' });
529   $main::lxdebug->leave_sub();
530 }
531
532 sub _do_save {
533   $main::auth->assert('customer_vendor_edit');
534
535   $::form->isblank("name", $::locale->text("Name missing!"));
536
537   if ($::form->{new_salesman_id} && $::instance_conf->get_vertreter) {
538     $::form->{salesman_id} = $::form->{new_salesman_id};
539     delete $::form->{new_salesman_id};
540   }
541
542   my $res = $::form->{db} eq 'customer' ? CT->save_customer(\%::myconfig, $::form) : CT->save_vendor(\%::myconfig, $::form);
543
544   if (3 == $res) {
545     if ($::form->{"db"} eq "customer") {
546       $::form->error($::locale->text('This customer number is already in use.'));
547     } else {
548       $::form->error($::locale->text('This vendor number is already in use.'));
549     }
550   }
551 }
552
553 sub add_transaction {
554   $main::lxdebug->enter_sub();
555
556   $main::auth->assert('customer_vendor_edit & ' .
557                 '(general_ledger         | invoice_edit         | vendor_invoice_edit | ' .
558                 ' request_quotation_edit | sales_quotation_edit | sales_order_edit    | purchase_order_edit)');
559
560   my $form     = $main::form;
561   my %myconfig = %main::myconfig;
562   my $locale   = $main::locale;
563
564 #  # saving the history
565 #  if(!exists $form->{addition}) {
566 #    $form->{addition} = "ADD TRANSACTION";
567 #    $form->save_history;
568 #  }
569 #  # /saving the history
570
571   _do_save();
572
573   $form->{callback} = $form->escape($form->{callback}, 1);
574   my $name = $form->escape("$form->{name}", 1);
575
576   $form->{callback} =
577     "$form->{script}?action=add&vc=$form->{db}&$form->{db}_id=$form->{id}&$form->{db}=$name&type=$form->{type}&callback=$form->{callback}";
578   $form->redirect;
579
580   $main::lxdebug->leave_sub();
581 }
582
583 sub save_and_ap_transaction {
584   $main::lxdebug->enter_sub();
585
586   $main::auth->assert('customer_vendor_edit & general_ledger');
587
588   my $form     = $main::form;
589   my %myconfig = %main::myconfig;
590
591   $form->{script} = "ap.pl";
592   # saving the history
593   if(!exists $form->{addition}) {
594     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
595     $form->{addition} = "SAVED";
596     $form->save_history;
597   }
598   # /saving the history
599   &add_transaction;
600   $main::lxdebug->leave_sub();
601 }
602
603 sub save_and_ar_transaction {
604   $main::lxdebug->enter_sub();
605
606   $main::auth->assert('customer_vendor_edit & general_ledger');
607
608   my $form     = $main::form;
609   my %myconfig = %main::myconfig;
610
611   $form->{script} = "ar.pl";
612   # saving the history
613   if(!exists $form->{addition}) {
614     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
615     $form->{addition} = "SAVED";
616     $form->save_history;
617   }
618   # /saving the history
619   &add_transaction;
620   $main::lxdebug->leave_sub();
621 }
622
623 sub save_and_invoice {
624   $main::lxdebug->enter_sub();
625
626   my $form     = $main::form;
627   my %myconfig = %main::myconfig;
628
629   if ($form->{db} eq 'customer') {
630     $main::auth->assert('customer_vendor_edit & invoice_edit');
631   } else {
632     $main::auth->assert('customer_vendor_edit & vendor_invoice_edit');
633   }
634
635   $form->{script} = ($form->{db} eq 'customer') ? "is.pl" : "ir.pl";
636   $form->{type} = "invoice";
637   # saving the history
638   if(!exists $form->{addition}) {
639     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
640     $form->{addition} = "SAVED";
641     $form->save_history;
642   }
643   # /saving the history
644   &add_transaction;
645   $main::lxdebug->leave_sub();
646 }
647
648 sub save_and_rfq {
649   $main::lxdebug->enter_sub();
650
651   $main::auth->assert('customer_vendor_edit & request_quotation_edit');
652
653   my $form     = $main::form;
654   my %myconfig = %main::myconfig;
655
656   $form->{script} = "oe.pl";
657   $form->{type}   = "request_quotation";
658   # saving the history
659   if(!exists $form->{addition}) {
660     $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
661     $form->{addition} = "SAVED";
662     $form->save_history;
663   }
664   # /saving the history
665   &add_transaction;
666   $main::lxdebug->leave_sub();
667 }
668
669 sub save_and_quotation {
670   $main::lxdebug->enter_sub();
671
672   $main::auth->assert('customer_vendor_edit & sales_quotation_edit');
673
674   my $form     = $main::form;
675   my %myconfig = %main::myconfig;
676
677   $form->{script} = "oe.pl";
678   $form->{type}   = "sales_quotation";
679   # saving the history
680   if(!exists $form->{addition}) {
681     $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
682     $form->{addition} = "SAVED";
683     $form->save_history;
684   }
685   # /saving the history
686   &add_transaction;
687   $main::lxdebug->leave_sub();
688 }
689
690 sub save_and_order {
691   $main::lxdebug->enter_sub();
692
693   my $form     = $main::form;
694   my %myconfig = %main::myconfig;
695
696   if ($form->{db} eq 'customer') {
697     $main::auth->assert('customer_vendor_edit & sales_order_edit');
698   } else {
699     $main::auth->assert('customer_vendor_edit & purchase_order_edit');
700   }
701
702   $form->{script} = "oe.pl";
703   $form->{type}   =
704     ($form->{db} eq 'customer') ? "sales_order" : "purchase_order";
705   # saving the history
706   if(!exists $form->{addition}) {
707     $form->{snumbers} = qq|ordnumber_| . $form->{ordnumber};
708     $form->{addition} = "SAVED";
709     $form->save_history;
710   }
711   # /saving the history
712   &add_transaction;
713   $main::lxdebug->leave_sub();
714 }
715
716 sub save_and_close {
717   $main::lxdebug->enter_sub();
718
719   $main::auth->assert('customer_vendor_edit');
720
721   my $form     = $main::form;
722   my %myconfig = %main::myconfig;
723   my $locale   = $main::locale;
724
725   my $msg = ucfirst $form->{db};
726   $msg .= " saved!";
727
728   _do_save();
729
730   # saving the history
731   if(!exists $form->{addition}) {
732     $form->{snumbers} = ($form->{"db"} eq "customer" ? qq|customernumber_| . $form->{customernumber} : qq|vendornumber_| . $form->{vendornumber});
733     $form->{addition} = "SAVED";
734     $form->save_history;
735   }
736   # /saving the history
737   $form->redirect($locale->text($msg));
738
739   $main::lxdebug->leave_sub();
740 }
741
742 sub save {
743   $main::lxdebug->enter_sub();
744
745   $main::auth->assert('customer_vendor_edit');
746
747   my $form     = $main::form;
748   my %myconfig = %main::myconfig;
749   my $locale   = $main::locale;
750
751   my $msg = ucfirst $form->{db};
752   $msg .= " saved!";
753
754   _do_save();
755
756   # saving the history
757   if(!exists $form->{addition}) {
758     $form->{snumbers} = ($form->{"db"} eq "customer" ? qq|customernumber_| . $form->{customernumber} : qq|vendornumber_| . $form->{vendornumber});
759     $form->{addition} = "SAVED";
760     $form->save_history;
761   }
762   # /saving the history
763   &edit;
764
765   $main::lxdebug->leave_sub();
766   ::end_of_request();
767 }
768
769 sub delete {
770   $main::lxdebug->enter_sub();
771
772   $main::auth->assert('customer_vendor_edit');
773
774   my $form     = $main::form;
775   my %myconfig = %main::myconfig;
776   my $locale   = $main::locale;
777
778   CT->delete(\%myconfig, \%$form);
779
780   my $msg = ucfirst $form->{db};
781   $msg .= " deleted!";
782   # saving the history
783   if(!exists $form->{addition}) {
784     $form->{snumbers} = ($form->{"db"} eq "customer" ? qq|customernumber_| . $form->{customernumber} : qq|vendornumber_| . $form->{vendornumber});
785     $form->{addition} = "DELETED";
786     $form->save_history;
787   }
788   # /saving the history
789   $form->redirect($locale->text($msg));
790
791   $main::lxdebug->leave_sub();
792 }
793
794 sub display {
795   $main::lxdebug->enter_sub();
796
797   $main::auth->assert('customer_vendor_edit');
798
799   my $form     = $main::form;
800
801   &form_header();
802   &form_footer();
803
804   $main::lxdebug->leave_sub();
805 }
806
807 sub update {
808   $main::lxdebug->enter_sub();
809
810   $main::auth->assert('customer_vendor_edit');
811
812   my $form     = $main::form;
813
814   &display();
815   $main::lxdebug->leave_sub();
816 }
817
818 sub get_contact {
819   $main::lxdebug->enter_sub();
820
821   $main::auth->assert('customer_vendor_edit');
822
823   CT->populate_drop_down_boxes(\%::myconfig, $::form);
824   CT->query_titles_and_greetings(\%::myconfig, $::form);
825   CT->get_contact(\%::myconfig, $::form) if $::form->{cp_id};
826
827   $::form->{CUSTOM_VARIABLES}{Contacts} = CVar->get_custom_variables(module => 'Contacts', trans_id => $::form->{cp_id});
828   CVar->render_inputs(variables => $::form->{CUSTOM_VARIABLES}{Contacts}, name_prefix => 'cp')
829     if scalar @{ $::form->{CUSTOM_VARIABLES}->{Contacts} };
830
831   $::form->{contacts_label} = \&_contacts_label;
832
833   print $::form->ajax_response_header(), $::form->parse_html_template('ct/_contact');
834
835   $main::lxdebug->leave_sub();
836 }
837
838 sub get_shipto {
839   $main::lxdebug->enter_sub();
840
841   $main::auth->assert('customer_vendor_edit');
842
843   CT->populate_drop_down_boxes(\%::myconfig, $::form);
844   CT->get_shipto(\%::myconfig, $::form) if $::form->{shipto_id};
845
846   $::form->{shipto_label} = \&_shipto_label;
847
848   print $::form->ajax_response_header(), $::form->parse_html_template('ct/_shipto');
849
850   $main::lxdebug->leave_sub();
851 }
852
853 sub get_delivery {
854   $::lxdebug->enter_sub;
855
856   $::auth->assert('customer_vendor_edit');
857   $::auth->assert('sales_all_edit');
858
859   CT->get_delivery(\%::myconfig, $::form );
860
861   print $::form->ajax_response_header,
862         $::form->parse_html_template('ct/get_delivery', {
863           is_customer =>  $::form->{db} eq 'customer',
864         });
865
866   $::lxdebug->leave_sub;
867 }
868
869 sub delete_shipto {
870   $::lxdebug->enter_sub;
871   $::auth->assert('customer_vendor_edit');
872
873   if (!$::form->{shipto_id}) {
874     flash('error', $::locale->text('No shipto selected to delete'));
875   } else {
876
877     CT->get_shipto(\%::myconfig, $::form);
878
879     my $shipto = SL::DB::Manager::Shipto->find_by(shipto_id => $::form->{shipto_id});
880
881     if ($shipto->used) {
882       $shipto->detach->save;
883       flash('info', $::locale->text('Shipto is in use and was flagged invalid.'));
884     } else {
885       $shipto->delete;
886       flash('info', $::locale->text('Shipto deleted.'));
887     }
888     delete $::form->{$_} for grep /^shipto/, keys %$::form;
889   }
890
891   edit();
892
893   $::lxdebug->leave_sub;
894 }
895
896 sub delete_contact {
897   $::lxdebug->enter_sub;
898   $::auth->assert('customer_vendor_edit');
899
900   if (!$::form->{cp_id}) {
901     flash('error', $::locale->text('No contact selected to delete'));
902   } else {
903
904     CT->get_contact(\%::myconfig, $::form);
905
906     my $contact = SL::DB::Manager::Contact->find_by(cp_id => $::form->{cp_id});
907
908     if ($contact->used) {
909       $contact->detach->save;
910       flash('info', $::locale->text('Contact is in use and was flagged invalid.'));
911     } else {
912       $contact->delete;
913       flash('info', $::locale->text('Contact deleted.'));
914     }
915     delete $::form->{$_} for grep /^cp_/, keys %$::form;
916   }
917
918   edit();
919
920   $::lxdebug->leave_sub;
921 }
922
923 sub ajax_autocomplete {
924   $main::lxdebug->enter_sub();
925
926   my $form     = $main::form;
927   my %myconfig = %main::myconfig;
928
929   $form->{column}          = 'name'     unless $form->{column} =~ /^name$/;
930   $form->{vc}              = 'customer' unless $form->{vc} =~ /^customer|vendor$/;
931   $form->{db}              = $form->{vc}; # CT expects this
932   $form->{$form->{column}} = $form->{q}           || '';
933   $form->{limit}           = ($form->{limit} * 1) || 10;
934   $form->{searchitems}   ||= '';
935
936   CT->search(\%myconfig, $form);
937
938   print $form->ajax_response_header(),
939         $form->parse_html_template('ct/ajax_autocomplete');
940
941   $main::lxdebug->leave_sub();
942 }
943
944 sub continue { call_sub($main::form->{nextsub}); }