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