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