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