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