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