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