0fdd832dfce90e3da5d12d932dc36ee9d33662bc
[kivitendo-erp.git] / SL / Controller / CustomerVendor.pm
1 package SL::Controller::CustomerVendor;
2
3 use strict;
4 use parent qw(SL::Controller::Base);
5
6 use List::MoreUtils qw(any);
7
8 use SL::JSON;
9 use SL::DBUtils;
10 use SL::Helper::Flash;
11 use SL::Locale::String;
12 use SL::Controller::Helper::GetModels;
13 use SL::Controller::Helper::ReportGenerator;
14 use SL::Controller::Helper::ParseFilter;
15
16 use SL::DB::Customer;
17 use SL::DB::Vendor;
18 use SL::DB::Business;
19 use SL::DB::Employee;
20 use SL::DB::Language;
21 use SL::DB::TaxZone;
22 use SL::DB::Note;
23 use SL::DB::PaymentTerm;
24 use SL::DB::Pricegroup;
25 use SL::DB::Price;
26 use SL::DB::Contact;
27 use SL::DB::FollowUp;
28 use SL::DB::FollowUpLink;
29 use SL::DB::History;
30 use SL::DB::Currency;
31 use SL::DB::Invoice;
32 use SL::DB::PurchaseInvoice;
33 use SL::DB::Order;
34
35 use Data::Dumper;
36
37 use Rose::Object::MakeMethods::Generic (
38   'scalar --get_set_init' => [ qw(customer_models vendor_models) ],
39 );
40
41 # safety
42 __PACKAGE__->run_before(
43   sub {
44     $::auth->assert('customer_vendor_edit');
45   },
46   except => [ qw(ajaj_autocomplete) ],
47 );
48 __PACKAGE__->run_before(
49   '_instantiate_args',
50   only => [
51     'save',
52     'save_and_ap_transaction',
53     'save_and_ar_transaction',
54     'save_and_close',
55     'save_and_invoice',
56     'save_and_order',
57     'save_and_quotation',
58     'save_and_rfq',
59     'delete',
60     'delete_contact',
61     'delete_shipto',
62   ]
63 );
64
65 __PACKAGE__->run_before(
66   '_load_customer_vendor',
67   only => [
68     'edit',
69     'show',
70     'update',
71     'ajaj_get_shipto',
72     'ajaj_get_contact',
73     'ajax_list_prices',
74   ]
75 );
76
77 # make sure this comes after _load_customer_vendor
78 __PACKAGE__->run_before(
79   '_check_customer_vendor_all_edit',
80   only => [
81     'edit',
82     'show',
83     'update',
84     'delete',
85     'save',
86     'save_and_ap_transaction',
87     'save_and_ar_transaction',
88     'save_and_close',
89     'save_and_invoice',
90     'save_and_order',
91     'save_and_quotation',
92     'save_and_rfq',
93     'delete',
94     'delete_contact',
95     'delete_shipto',
96   ]
97 );
98
99 __PACKAGE__->run_before(
100   '_create_customer_vendor',
101   only => [
102     'add',
103   ]
104 );
105
106 __PACKAGE__->run_before('normalize_name');
107
108
109 sub action_add {
110   my ($self) = @_;
111
112   $self->_pre_render();
113   $self->{cv}->assign_attributes(hourly_rate => $::instance_conf->get_customer_hourly_rate) if $self->{cv}->is_customer;
114
115   $self->render(
116     'customer_vendor/form',
117     title => ($self->is_vendor() ? $::locale->text('Add Vendor') : $::locale->text('Add Customer')),
118     %{$self->{template_args}}
119   );
120 }
121
122 sub action_edit {
123   my ($self) = @_;
124
125   $self->_pre_render();
126   $self->render(
127     'customer_vendor/form',
128     title => ($self->is_vendor() ? $::locale->text('Edit Vendor') : $::locale->text('Edit Customer')),
129     %{$self->{template_args}}
130   );
131 }
132
133 sub action_show {
134   my ($self) = @_;
135
136   if ($::request->type eq 'json') {
137     my $cv_hash;
138     if (!$self->{cv}) {
139       # TODO error
140     } else {
141       $cv_hash          = $self->{cv}->as_tree;
142       $cv_hash->{cvars} = $self->{cv}->cvar_as_hashref;
143     }
144
145     $self->render(\ SL::JSON::to_json($cv_hash), { layout => 0, type => 'json', process => 0 });
146   }
147 }
148
149 sub _save {
150   my ($self) = @_;
151
152   my @errors = $self->{cv}->validate;
153   if (@errors) {
154     flash('error', @errors);
155     $self->_pre_render();
156     $self->render(
157       'customer_vendor/form',
158       title => ($self->is_vendor() ? t8('Edit Vendor') : t8('Edit Customer')),
159       %{$self->{template_args}}
160     );
161     $::dispatcher->end_request;
162   }
163
164   my $db = $self->{cv}->db;
165
166   $db->with_transaction(sub {
167     my $cvs_by_nr;
168     if ( $self->is_vendor() ) {
169       if ( $self->{cv}->vendornumber ) {
170         $cvs_by_nr = SL::DB::Manager::Vendor->get_all(query => [vendornumber => $self->{cv}->vendornumber]);
171       }
172     } else {
173       if ( $self->{cv}->customernumber ) {
174         $cvs_by_nr = SL::DB::Manager::Customer->get_all(query => [customernumber => $self->{cv}->customernumber]);
175       }
176     }
177
178     foreach my $entry (@{$cvs_by_nr}) {
179       if( $entry->id != $self->{cv}->id ) {
180         my $msg =
181           $self->is_vendor() ? $::locale->text('This vendor number is already in use.') : $::locale->text('This customer number is already in use.');
182
183         $::form->error($msg);
184       }
185     }
186
187     $self->{cv}->save(cascade => 1);
188
189     $self->{contact}->cp_cv_id($self->{cv}->id);
190     if( $self->{contact}->cp_name ne '' || $self->{contact}->cp_givenname ne '' ) {
191       $self->{contact}->save(cascade => 1);
192     }
193
194     if( $self->{note}->subject ne '' && $self->{note}->body ne '' ) {
195
196       if ( !$self->{note_followup}->follow_up_date ) {
197         $::form->error($::locale->text('Date missing!'));
198       }
199
200       $self->{note}->trans_id($self->{cv}->id);
201       $self->{note}->save();
202
203       $self->{note_followup}->save();
204
205       $self->{note_followup_link}->follow_up_id($self->{note_followup}->id);
206       $self->{note_followup_link}->trans_id($self->{cv}->id);
207       $self->{note_followup_link}->save();
208
209       SL::Helper::Flash::flash_later('info', $::locale->text('Follow-Up saved.'));
210     }
211
212     $self->{shipto}->trans_id($self->{cv}->id);
213     if(any { $self->{shipto}->$_ ne '' } qw(shiptoname shiptodepartment_1 shiptodepartment_2 shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax shiptoemail)) {
214       $self->{shipto}->save(cascade => 1);
215     }
216
217     my $snumbers = $self->is_vendor() ? 'vendornumber_'. $self->{cv}->vendornumber : 'customernumber_'. $self->{cv}->customernumber;
218     SL::DB::History->new(
219       trans_id => $self->{cv}->id,
220       snumbers => $snumbers,
221       employee_id => SL::DB::Manager::Employee->current->id,
222       addition => 'SAVED',
223     )->save();
224
225     if ( $::form->{delete_notes} ) {
226       foreach my $note_id (@{ $::form->{delete_notes} }) {
227         my $note = SL::DB::Note->new(id => $note_id)->load();
228         if ( $note->follow_up ) {
229           if ( $note->follow_up->follow_up_link ) {
230             $note->follow_up->follow_up_link->delete(cascade => 'delete');
231           }
232           $note->follow_up->delete(cascade => 'delete');
233         }
234         $note->delete(cascade => 'delete');
235       }
236     }
237
238     1;
239   }) || die($db->error);
240
241 }
242
243 sub action_save {
244   my ($self) = @_;
245
246   $self->_save();
247
248   my @redirect_params = (
249     action => 'edit',
250     id     => $self->{cv}->id,
251     db     => ($self->is_vendor() ? 'vendor' : 'customer'),
252   );
253
254   if ( $self->{contact}->cp_id ) {
255     push(@redirect_params, contact_id => $self->{contact}->cp_id);
256   }
257
258   if ( $self->{shipto}->shipto_id ) {
259     push(@redirect_params, shipto_id => $self->{shipto}->shipto_id);
260   }
261
262   $self->redirect_to(@redirect_params);
263 }
264
265 sub action_save_and_close {
266   my ($self) = @_;
267
268   $self->_save();
269
270   my $msg = $self->is_vendor() ? $::locale->text('Vendor saved') : $::locale->text('Customer saved');
271   $::form->redirect($msg);
272 }
273
274 sub _transaction {
275   my ($self, $script) = @_;
276
277   $::auth->assert('gl_transactions | ap_transactions | ar_transactions'.
278                     '| invoice_edit         | vendor_invoice_edit | ' .
279                  ' request_quotation_edit | sales_quotation_edit | sales_order_edit    | purchase_order_edit');
280
281   $self->_save();
282
283   my $name = $::form->escape($self->{cv}->name, 1);
284   my $db = $self->is_vendor() ? 'vendor' : 'customer';
285   my $action = 'add';
286
287   if ($::instance_conf->get_feature_experimental_order && 'oe.pl' eq $script) {
288     $script = 'controller.pl';
289     $action = 'Order/' . $action;
290   }
291
292   my $url = $self->url_for(
293     controller => $script,
294     action     => $action,
295     vc         => $db,
296     $db .'_id' => $self->{cv}->id,
297     $db        => $name,
298     type       => $::form->{type},
299     callback   => $::form->{callback},
300   );
301
302   print $::form->redirect_header($url);
303 }
304
305 sub action_save_and_ar_transaction {
306   my ($self) = @_;
307
308   $main::auth->assert('ar_transactions');
309
310   $self->_transaction('ar.pl');
311 }
312
313 sub action_save_and_ap_transaction {
314   my ($self) = @_;
315
316   $main::auth->assert('ap_transactions');
317
318   $self->_transaction('ap.pl');
319 }
320
321 sub action_save_and_invoice {
322   my ($self) = @_;
323
324   if ( $self->is_vendor() ) {
325     $::auth->assert('vendor_invoice_edit');
326   } else {
327     $::auth->assert('invoice_edit');
328   }
329
330   $::form->{type} = 'invoice';
331   $self->_transaction($self->is_vendor() ? 'ir.pl' : 'is.pl');
332 }
333
334 sub action_save_and_order {
335   my ($self) = @_;
336
337   if ( $self->is_vendor() ) {
338     $::auth->assert('purchase_order_edit');
339   } else {
340     $::auth->assert('sales_order_edit');
341   }
342
343   $::form->{type} = $self->is_vendor() ? 'purchase_order' : 'sales_order';
344   $self->_transaction('oe.pl');
345 }
346
347 sub action_save_and_rfq {
348   my ($self) = @_;
349
350   $::auth->assert('request_quotation_edit');
351
352   $::form->{type} = 'request_quotation';
353   $self->_transaction('oe.pl');
354 }
355
356 sub action_save_and_quotation {
357   my ($self) = @_;
358
359   $::auth->assert('sales_quotation_edit');
360
361   $::form->{type} = 'sales_quotation';
362   $self->_transaction('oe.pl');
363 }
364
365 sub action_delete {
366   my ($self) = @_;
367
368   my $db = $self->{cv}->db;
369
370   if( !$self->is_orphaned() ) {
371     $self->action_edit();
372   } else {
373
374     $db->with_transaction(sub {
375       $self->{cv}->delete(cascade => 1);
376
377       my $snumbers = $self->is_vendor() ? 'vendornumber_'. $self->{cv}->vendornumber : 'customernumber_'. $self->{cv}->customernumber;
378       SL::DB::History->new(
379         trans_id => $self->{cv}->id,
380         snumbers => $snumbers,
381         employee_id => SL::DB::Manager::Employee->current->id,
382         addition => 'DELETED',
383       )->save();
384     }) || die($db->error);
385
386     my $msg = $self->is_vendor() ? $::locale->text('Vendor deleted!') : $::locale->text('Customer deleted!');
387     $::form->redirect($msg);
388   }
389
390 }
391
392
393 sub action_delete_contact {
394   my ($self) = @_;
395
396   my $db = $self->{contact}->db;
397
398   if ( !$self->{contact}->cp_id ) {
399     SL::Helper::Flash::flash('error', $::locale->text('No contact selected to delete'));
400   } else {
401
402     $db->with_transaction(sub {
403       if ( $self->{contact}->used ) {
404         $self->{contact}->detach();
405         $self->{contact}->save();
406         SL::Helper::Flash::flash('info', $::locale->text('Contact is in use and was flagged invalid.'));
407       } else {
408         $self->{contact}->delete(cascade => 1);
409         SL::Helper::Flash::flash('info', $::locale->text('Contact deleted.'));
410       }
411
412       1;
413     }) || die($db->error);
414
415     $self->{contact} = $self->_new_contact_object;
416   }
417
418   $self->action_edit();
419 }
420
421 sub action_delete_shipto {
422   my ($self) = @_;
423
424   my $db = $self->{shipto}->db;
425
426   if ( !$self->{shipto}->shipto_id ) {
427     SL::Helper::Flash::flash('error', $::locale->text('No shipto selected to delete'));
428   } else {
429
430     $db->with_transaction(sub {
431       if ( $self->{shipto}->used ) {
432         $self->{shipto}->detach();
433         $self->{shipto}->save(cascade => 1);
434         SL::Helper::Flash::flash('info', $::locale->text('Shipto is in use and was flagged invalid.'));
435       } else {
436         $self->{shipto}->delete(cascade => 1);
437         SL::Helper::Flash::flash('info', $::locale->text('Shipto deleted.'));
438       }
439
440       1;
441     }) || die($db->error);
442
443     $self->{shipto} = SL::DB::Shipto->new();
444   }
445
446   $self->action_edit();
447 }
448
449
450 sub action_search {
451   my ($self) = @_;
452
453   my @url_params = (
454     controller => 'ct.pl',
455     action => 'search',
456     db => $self->is_vendor() ? 'vendor' : 'customer',
457   );
458
459   if ( $::form->{callback} ) {
460     push(@url_params, callback => $::form->{callback});
461   }
462
463   $self->redirect_to(@url_params);
464 }
465
466
467 sub action_search_contact {
468   my ($self) = @_;
469
470   my $url = 'ct.pl?action=search_contact&db=customer';
471
472   if ( $::form->{callback} ) {
473     $url .= '&callback='. $::form->escape($::form->{callback});
474   }
475
476   print $::form->redirect_header($url);
477 }
478
479 sub action_get_delivery {
480   my ($self) = @_;
481
482   $::auth->assert('sales_all_edit')    if $self->is_customer();
483   $::auth->assert('purchase_all_edit') if $self->is_vendor();
484
485   my $dbh = $::form->get_standard_dbh();
486
487   my ($arap, $db, $qty_sign);
488   if ( $self->is_vendor() ) {
489     $arap = 'ap';
490     $db = 'vendor';
491     $qty_sign = ' * -1 AS qty';
492   } else {
493     $arap = 'ar';
494     $db = 'customer';
495     $qty_sign = '';
496   }
497
498   my $where = ' WHERE 1=1';
499   my @values;
500
501   if ( !$self->is_vendor() && $::form->{shipto_id} && $::form->{shipto_id} ne 'all' ) {
502     $where .= " AND ${arap}.shipto_id = ?";
503     push(@values, $::form->{shipto_id});
504   } else {
505     $where .= " AND ${arap}.${db}_id = ?";
506     push(@values, $::form->{id});
507   }
508
509   if ( $::form->{delivery_from} ) {
510     $where .= " AND ${arap}.transdate >= ?";
511     push(@values, conv_date($::form->{delivery_from}));
512   }
513
514   if ( $::form->{delivery_to} ) {
515     $where .= " AND ${arap}.transdate <= ?";
516     push(@values, conv_date($::form->{delivery_to}));
517   }
518
519   my $query =
520     "SELECT
521        s.shiptoname,
522        i.qty ${qty_sign},
523        ${arap}.id,
524        ${arap}.transdate,
525        ${arap}.invnumber,
526        ${arap}.ordnumber,
527        i.description,
528        i.unit,
529        i.sellprice,
530        oe.id AS oe_id,
531        invoice
532      FROM ${arap}
533
534      LEFT JOIN shipto s
535       ON ". ($arap eq 'ar' ? '(ar.shipto_id = s.shipto_id) ' : '(ap.id = s.trans_id) ') ."
536
537      LEFT JOIN invoice i
538        ON ${arap}.id = i.trans_id
539
540      LEFT JOIN parts p
541        ON p.id = i.parts_id
542
543      LEFT JOIN oe
544        ON (oe.ordnumber = ${arap}.ordnumber AND NOT ${arap}.ordnumber = ''
545            AND ". ($arap eq 'ar' ? 'oe.customer_id IS NOT NULL' : 'oe.vendor_id IS NOT NULL') ." )
546
547      ${where}
548      ORDER BY ${arap}.transdate DESC LIMIT 15";
549
550   $self->{delivery} = selectall_hashref_query($::form, $dbh, $query, @values);
551
552   $self->render('customer_vendor/get_delivery', { layout => 0 });
553 }
554
555 sub action_ajaj_get_shipto {
556   my ($self) = @_;
557
558   my $data = {};
559   $data->{shipto} = {
560     map(
561       {
562         my $name = 'shipto'. $_;
563         $name => $self->{shipto}->$name;
564       }
565       qw(_id name department_1 department_2 street zipcode city gln country contact phone fax email)
566     )
567   };
568
569   $data->{shipto_cvars} = $self->_prepare_cvar_configs_for_ajaj($self->{shipto}->cvars_by_config);
570
571   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
572 }
573
574 sub action_ajaj_get_contact {
575   my ($self) = @_;
576
577   my $data;
578
579   $data->{contact} = {
580     map(
581       {
582         my $name = 'cp_'. $_;
583
584         if ( $_ eq 'birthday' && $self->{contact}->$name ) {
585           $name => $self->{contact}->$name->to_lxoffice;
586         } else {
587           $name => $self->{contact}->$name;
588         }
589       }
590       qw(
591         id gender abteilung title position givenname name email phone1 phone2 fax mobile1 mobile2
592         satphone satfax project street zipcode city privatphone privatemail birthday main
593       )
594     )
595   };
596
597   $data->{contact_cvars} = $self->_prepare_cvar_configs_for_ajaj($self->{contact}->cvars_by_config);
598
599   # avoid two or more main_cp
600   my $has_main_cp = grep { $_->cp_main == 1 } @{ $self->{cv}->contacts };
601   $data->{contact}->{disable_cp_main} = 1 if ($has_main_cp && !$data->{contact}->{cp_main});
602
603   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
604 }
605
606 sub action_ajaj_autocomplete {
607   my ($self, %params) = @_;
608
609   my ($model, $manager, $number, $matches);
610
611   # first see if this is customer or vendor picking
612   if ($::form->{type} eq 'customer') {
613      $model   = $self->customer_models;
614      $manager = 'SL::DB::Manager::Customer';
615      $number  = 'customernumber';
616   } elsif ($::form->{type} eq 'vendor')  {
617      $model   = $self->vendor_models;
618      $manager = 'SL::DB::Manager::Vendor';
619      $number  = 'vendornumber';
620   } else {
621      die "unknown type $::form->{type}";
622   }
623
624   # if someone types something, and hits enter, assume he entered the full name.
625   # if something matches, treat that as the sole match
626   # unfortunately get_models can't do more than one per package atm, so we do it
627   # the oldfashioned way.
628   if ($::form->{prefer_exact}) {
629     my $exact_matches;
630     if (1 == scalar @{ $exact_matches = $manager->get_all(
631       query => [
632         obsolete => 0,
633         (salesman_id => SL::DB::Manager::Employee->current->id) x !$::auth->assert('customer_vendor_all_edit', 1),
634         or => [
635           name    => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
636           $number => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
637         ]
638       ],
639       limit => 2,
640     ) }) {
641       $matches = $exact_matches;
642     }
643   }
644
645   $matches //= $model->get;
646
647   my @hashes = map {
648    +{
649      value       => $_->displayable_name,
650      label       => $_->displayable_name,
651      id          => $_->id,
652      $number     => $_->$number,
653      name        => $_->name,
654      type        => $::form->{type},
655      cvars       => { map { ($_->config->name => { value => $_->value_as_text, is_valid => $_->is_valid }) } @{ $_->cvars_by_config } },
656     }
657   } @{ $matches };
658
659   $self->render(\ SL::JSON::to_json(\@hashes), { layout => 0, type => 'json', process => 0 });
660 }
661
662 sub action_test_page {
663   $_[0]->render('customer_vendor/test_page');
664 }
665
666 sub action_ajax_list_prices {
667   my ($self, %params) = @_;
668
669   my $report   = SL::ReportGenerator->new(\%::myconfig, $::form);
670   my @columns  = qw(partnumber description price);
671   my @visible  = qw(partnumber description price);
672   my @sortable = qw(partnumber description price);
673
674   my %column_defs = (
675     partnumber  => { text => $::locale->text('Part Number'),      sub => sub { $_[0]->parts->partnumber  } },
676     description => { text => $::locale->text('Part Description'), sub => sub { $_[0]->parts->description } },
677     price       => { text => $::locale->text('Price'),            sub => sub { $::form->format_amount(\%::myconfig, $_[0]->price, 2) }, align => 'right' },
678   );
679
680   $::form->{sort_by}  ||= 'partnumber';
681   $::form->{sort_dir} //= 1;
682
683   for my $col (@sortable) {
684     $column_defs{$col}{link} = $self->url_for(
685       action   => 'ajax_list_prices',
686       callback => $::form->{callback},
687       db       => $::form->{db},
688       id       => $self->{cv}->id,
689       sort_by  => $col,
690       sort_dir => ($::form->{sort_by} eq $col ? 1 - $::form->{sort_dir} : $::form->{sort_dir})
691     );
692   }
693
694   map { $column_defs{$_}{visible} = 1 } @visible;
695
696   my $pricegroup;
697   $pricegroup = $self->{cv}->pricegroup->pricegroup if $self->{cv}->pricegroup;
698
699   $report->set_columns(%column_defs);
700   $report->set_column_order(@columns);
701   $report->set_options(allow_pdf_export => 0, allow_csv_export => 0);
702   $report->set_sort_indicator($::form->{sort_by}, $::form->{sort_dir});
703   $report->set_export_options(@{ $params{report_generator_export_options} || [] });
704   $report->set_options(
705     %{ $params{report_generator_options} || {} },
706     output_format        => 'HTML',
707     top_info_text        => $::locale->text('Pricegroup') . ': ' . $pricegroup,
708     title                => $::locale->text('Price List'),
709   );
710
711   my $sort_param = $::form->{sort_by} eq 'price'       ? 'price'             :
712                    $::form->{sort_by} eq 'description' ? 'parts.description' :
713                    'parts.partnumber';
714   $sort_param .= ' ' . ($::form->{sort_dir} ? 'ASC' : 'DESC');
715   my $prices = SL::DB::Manager::Price->get_all(where        => [ pricegroup_id => $self->{cv}->pricegroup_id ],
716                                                sort_by      => $sort_param,
717                                                with_objects => 'parts');
718
719   $self->report_generator_list_objects(report => $report, objects => $prices, layout => 0, header => 0);
720 }
721
722 sub is_vendor {
723   return $::form->{db} eq 'vendor';
724 }
725
726 sub is_customer {
727   return $::form->{db} eq 'customer';
728 }
729
730 sub is_orphaned {
731   my ($self) = @_;
732
733   if ( defined($self->{_is_orphaned}) ) {
734     return $self->{_is_orphaned};
735   }
736
737   my $arap      = $self->is_vendor ? 'ap' : 'ar';
738   my $num_args  = 3;
739
740   my $cv = $self->is_vendor ? 'vendor' : 'customer';
741
742   my $query =
743    'SELECT a.id
744     FROM '. $arap .' AS a
745     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
746     WHERE ct.id = ?
747
748     UNION
749
750     SELECT a.id
751     FROM oe a
752     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
753     WHERE ct.id = ?
754
755     UNION
756
757     SELECT a.id
758     FROM delivery_orders a
759     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
760     WHERE ct.id = ?';
761
762
763   if ( $self->is_vendor ) {
764     $query .=
765      ' UNION
766       SELECT 1 FROM makemodel mm WHERE mm.make = ?';
767     $num_args++;
768   }
769
770   my ($dummy) = selectrow_query($::form, $::form->get_standard_dbh(), $query, (conv_i($self->{cv}->id)) x $num_args);
771
772   return $self->{_is_orphaned} = !$dummy;
773 }
774
775 sub _copy_form_to_cvars {
776   my ($self, %params) = @_;
777
778   foreach my $cvar (@{ $params{target}->cvars_by_config }) {
779     my $value = $params{source}->{$cvar->config->name};
780     $value    = $::form->parse_amount(\%::myconfig, $value) if $cvar->config->type eq 'number';
781
782     $cvar->value($value);
783   }
784 }
785
786 sub _instantiate_args {
787   my ($self) = @_;
788
789   my $curr_employee = SL::DB::Manager::Employee->current;
790
791   if ( $::form->{cv}->{id} ) {
792     if ( $self->is_vendor() ) {
793       $self->{cv} = SL::DB::Vendor->new(id => $::form->{cv}->{id})->load();
794     } else {
795       $self->{cv} = SL::DB::Customer->new(id => $::form->{cv}->{id})->load();
796     }
797   } else {
798     $self->{cv} = $self->_new_customer_vendor_object;
799   }
800   $self->{cv}->assign_attributes(%{$::form->{cv}});
801
802   if ( $self->is_customer() && $::form->{cv}->{taxincluded_checked} eq '' ) {
803     $self->{cv}->taxincluded_checked(undef);
804   }
805
806   $self->{cv}->hourly_rate($::instance_conf->get_customer_hourly_rate) if $self->is_customer && !$self->{cv}->hourly_rate;
807
808   if ( $::form->{note}->{id} ) {
809     $self->{note} = SL::DB::Note->new(id => $::form->{note}->{id})->load();
810     $self->{note_followup} = $self->{note}->follow_up;
811     $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
812   } else {
813     $self->{note} = SL::DB::Note->new();
814     $self->{note_followup} = SL::DB::FollowUp->new();
815     $self->{note_followup_link} = SL::DB::FollowUpLink->new();
816   }
817
818   $self->{note}->assign_attributes(%{$::form->{note}});
819   $self->{note}->created_by($curr_employee->id);
820   $self->{note}->trans_module('ct');
821
822   $self->{note_followup}->assign_attributes(%{$::form->{note_followup}});
823   $self->{note_followup}->note($self->{note});
824   $self->{note_followup}->created_by($curr_employee->id);
825
826   $self->{note_followup_link}->trans_type($self->is_vendor() ? 'vendor' : 'customer');
827   $self->{note_followup_link}->trans_info($self->{cv}->name);
828
829   if ( $::form->{shipto}->{shipto_id} ) {
830     $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto}->{shipto_id})->load();
831   } else {
832     $self->{shipto} = SL::DB::Shipto->new();
833   }
834   $self->{shipto}->assign_attributes(%{$::form->{shipto}});
835   $self->{shipto}->module('CT');
836
837   if ( $::form->{contact}->{cp_id} ) {
838     $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact}->{cp_id})->load();
839   } else {
840     $self->{contact} = $self->_new_contact_object;
841   }
842   $self->{contact}->assign_attributes(%{$::form->{contact}});
843
844   $self->_copy_form_to_cvars(target => $self->{cv},      source => $::form->{cv_cvars});
845   $self->_copy_form_to_cvars(target => $self->{contact}, source => $::form->{contact_cvars});
846   $self->_copy_form_to_cvars(target => $self->{shipto},  source => $::form->{shipto_cvars});
847 }
848
849 sub _load_customer_vendor {
850   my ($self) = @_;
851
852   if ( $self->is_vendor() ) {
853     $self->{cv} = SL::DB::Vendor->new(id => $::form->{id})->load();
854   } else {
855     $self->{cv} = SL::DB::Customer->new(id => $::form->{id})->load();
856   }
857
858   if ( $::form->{note_id} ) {
859     $self->{note} = SL::DB::Note->new(id => $::form->{note_id})->load();
860     $self->{note_followup} = $self->{note}->follow_up;
861     $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
862   } else {
863     $self->{note} = SL::DB::Note->new();
864     $self->{note_followup} = SL::DB::FollowUp->new();
865     $self->{note_followup_link} = SL::DB::FollowUpLink->new();
866   }
867
868   if ( $::form->{shipto_id} ) {
869     $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto_id})->load();
870
871     if ( $self->{shipto}->trans_id != $self->{cv}->id ) {
872       die($::locale->text('Error'));
873     }
874   } else {
875     $self->{shipto} = SL::DB::Shipto->new();
876   }
877
878   if ( $::form->{contact_id} ) {
879     $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact_id})->load();
880
881     if ( $self->{contact}->cp_cv_id != $self->{cv}->id ) {
882       die($::locale->text('Error'));
883     }
884   } else {
885     $self->{contact} = $self->_new_contact_object;
886   }
887 }
888
889 sub _check_customer_vendor_all_edit {
890   my ($self) = @_;
891
892   unless ($::auth->assert('customer_vendor_all_edit', 1)) {
893     die($::locale->text("You don't have the rights to edit this customer.") . "\n")
894       if $self->{cv}->is_customer and
895          SL::DB::Manager::Employee->current->id != $self->{cv}->salesman_id;
896   };
897 };
898
899 sub _create_customer_vendor {
900   my ($self) = @_;
901
902   $self->{cv} = $self->_new_customer_vendor_object;
903   $self->{cv}->currency_id($::instance_conf->get_currency_id());
904
905   $self->{note} = SL::DB::Note->new();
906
907   $self->{note_followup} = SL::DB::FollowUp->new();
908
909   $self->{shipto} = SL::DB::Shipto->new();
910
911   $self->{contact} = $self->_new_contact_object;
912 }
913
914 sub _pre_render {
915   my ($self) = @_;
916
917   my $dbh = $::form->get_standard_dbh();
918
919   my $query;
920
921   $self->{all_business} = SL::DB::Manager::Business->get_all();
922
923   $self->{all_employees} = SL::DB::Manager::Employee->get_all(query => [ deleted => 0 ]);
924
925   $query =
926     'SELECT DISTINCT(greeting)
927      FROM customer
928      WHERE greeting IS NOT NULL AND greeting != \'\'
929      UNION
930        SELECT DISTINCT(greeting)
931        FROM vendor
932        WHERE greeting IS NOT NULL AND greeting != \'\'
933      ORDER BY greeting';
934   $self->{all_greetings} = [
935     map(
936       { $_->{greeting}; }
937       selectall_hashref_query($::form, $dbh, $query)
938     )
939   ];
940
941   $query =
942     'SELECT DISTINCT(cp_title) AS title
943      FROM contacts
944      WHERE cp_title IS NOT NULL AND cp_title != \'\'
945      ORDER BY cp_title';
946   $self->{all_titles} = [
947     map(
948       { $_->{title}; }
949       selectall_hashref_query($::form, $dbh, $query)
950     )
951   ];
952
953   $self->{all_currencies} = SL::DB::Manager::Currency->get_all();
954
955   $self->{all_languages} = SL::DB::Manager::Language->get_all();
956
957   $self->{all_taxzones} = SL::DB::Manager::TaxZone->get_all_sorted();
958
959   if ( $::instance_conf->get_vertreter() ) {
960     $query =
961       'SELECT id
962        FROM business
963        WHERE salesman';
964     my $business_ids = [
965       map(
966         { $_->{id}; }
967         selectall_hashref_query($::form, $dbh, $query)
968       )
969     ];
970
971     if ( $business_ids->[0] ) {
972       $self->{all_salesman_customers} = SL::DB::Manager::Customer->get_all(query => [business_id => $business_ids]);
973     } else {
974       $self->{all_salesman_customers} = [];
975     }
976   } else {
977     $self->{all_salesmen} = SL::DB::Manager::Employee->get_all(query => [ or => [ id => $self->{cv}->salesman_id,  deleted => 0 ] ]);
978   }
979
980   $self->{all_payment_terms} = SL::DB::Manager::PaymentTerm->get_all_sorted(where => [ or => [ id       => $self->{cv}->payment_id,
981                                                                                                obsolete => 0 ] ]);
982
983   $self->{all_delivery_terms} = SL::DB::Manager::DeliveryTerm->get_all();
984
985   if ($self->{cv}->is_customer) {
986     $self->{all_pricegroups} = SL::DB::Manager::Pricegroup->get_all_sorted(query => [ or => [ id => $self->{cv}->pricegroup_id, obsolete => 0 ] ]);
987   }
988
989   $query =
990     'SELECT DISTINCT(cp_abteilung) AS department
991      FROM contacts
992      WHERE cp_abteilung IS NOT NULL AND cp_abteilung != \'\'
993      ORDER BY cp_abteilung';
994   $self->{all_departments} = [
995     map(
996       { $_->{department}; }
997       selectall_hashref_query($::form, $dbh, $query)
998     )
999   ];
1000
1001   $self->{contacts} = $self->{cv}->contacts;
1002   $self->{contacts} ||= [];
1003
1004   $self->{shiptos} = $self->{cv}->shipto;
1005   $self->{shiptos} ||= [];
1006
1007   $self->{notes} = SL::DB::Manager::Note->get_all(
1008     query => [
1009       trans_id => $self->{cv}->id,
1010       trans_module => 'ct',
1011     ],
1012     with_objects => ['follow_up'],
1013   );
1014
1015   if ( $self->is_vendor()) {
1016     $self->{open_items} = SL::DB::Manager::PurchaseInvoice->get_all_count(
1017       query => [
1018         vendor_id => $self->{cv}->id,
1019         paid => {lt_sql => 'amount'},
1020       ],
1021     );
1022   } else {
1023     $self->{open_items} = SL::DB::Manager::Invoice->get_all_count(
1024       query => [
1025         customer_id => $self->{cv}->id,
1026         paid => {lt_sql => 'amount'},
1027       ],
1028     );
1029   }
1030
1031   if ( $self->is_vendor() ) {
1032     $self->{open_orders} = SL::DB::Manager::Order->get_all_count(
1033       query => [
1034         vendor_id => $self->{cv}->id,
1035         closed => 'F',
1036       ],
1037     );
1038   } else {
1039     $self->{open_orders} = SL::DB::Manager::Order->get_all_count(
1040       query => [
1041         customer_id => $self->{cv}->id,
1042         closed => 'F',
1043       ],
1044     );
1045   }
1046   $self->{template_args} ||= {};
1047
1048   $::request->{layout}->add_javascripts('kivi.CustomerVendor.js');
1049   $::request->{layout}->add_javascripts('kivi.File.js');
1050   $::request->{layout}->add_javascripts('kivi.CustomerVendorTurnover.js');
1051
1052   $self->_setup_form_action_bar;
1053 }
1054
1055 sub _setup_form_action_bar {
1056   my ($self) = @_;
1057
1058   for my $bar ($::request->layout->get('actionbar')) {
1059     $bar->add(
1060       combobox => [
1061         action => [
1062           t8('Save'),
1063           submit    => [ '#form', { action => "CustomerVendor/save" } ],
1064           checks    => [ 'check_taxzone_and_ustid' ],
1065           accesskey => 'enter',
1066         ],
1067         action => [
1068           t8('Save and Close'),
1069           submit => [ '#form', { action => "CustomerVendor/save_and_close" } ],
1070           checks => [ 'check_taxzone_and_ustid' ],
1071         ],
1072       ], # end of combobox "Save"
1073
1074       combobox => [
1075         action => [ t8('Workflow') ],
1076         (action => [
1077           t8('Save and AP Transaction'),
1078           submit => [ '#form', { action => "CustomerVendor/save_and_ap_transaction" } ],
1079           checks => [ 'check_taxzone_and_ustid' ],
1080         ]) x !!$self->is_vendor,
1081         (action => [
1082           t8('Save and AR Transaction'),
1083           submit => [ '#form', { action => "CustomerVendor/save_and_ar_transaction" } ],
1084           checks => [ 'check_taxzone_and_ustid' ],
1085         ]) x !$self->is_vendor,
1086         action => [
1087           t8('Save and Invoice'),
1088           submit => [ '#form', { action => "CustomerVendor/save_and_invoice" } ],
1089           checks => [ 'check_taxzone_and_ustid' ],
1090         ],
1091         action => [
1092           t8('Save and Order'),
1093           submit => [ '#form', { action => "CustomerVendor/save_and_order" } ],
1094           checks => [ 'check_taxzone_and_ustid' ],
1095         ],
1096         (action => [
1097           t8('Save and RFQ'),
1098           submit => [ '#form', { action => "CustomerVendor/save_and_rfq" } ],
1099           checks => [ 'check_taxzone_and_ustid' ],
1100         ]) x !!$self->is_vendor,
1101         (action => [
1102           t8('Save and Quotation'),
1103           submit => [ '#form', { action => "CustomerVendor/save_and_quotation" } ],
1104           checks => [ 'check_taxzone_and_ustid' ],
1105         ]) x !$self->is_vendor,
1106       ], # end of combobox "Workflow"
1107
1108       action => [
1109         t8('Delete'),
1110         submit   => [ '#form', { action => "CustomerVendor/delete" } ],
1111         confirm  => t8('Do you really want to delete this object?'),
1112         disabled => !$self->{cv}->id    ? t8('This object has not been saved yet.')
1113                   : !$self->is_orphaned ? t8('This object has already been used.')
1114                   :                       undef,
1115       ],
1116
1117       'separator',
1118
1119       action => [
1120         t8('History'),
1121         call     => [ 'kivi.CustomerVendor.showHistoryWindow', $self->{cv}->id ],
1122         disabled => !$self->{cv}->id ? t8('This object has not been saved yet.') : undef,
1123       ],
1124     );
1125   }
1126 }
1127
1128 sub _prepare_cvar_configs_for_ajaj {
1129   my ($self, $cvars) = @_;
1130
1131   return {
1132     map {
1133       my $cvar   = $_;
1134       my $result = { type => $cvar->config->type };
1135
1136       if ($cvar->config->type eq 'number') {
1137         $result->{value} = $::form->format_amount(\%::myconfig, $cvar->value, -2);
1138
1139       } elsif ($result->{type} eq 'date') {
1140         $result->{value} = $cvar->value ? $cvar->value->to_kivitendo : undef;
1141
1142       } elsif ($result->{type} =~ m{customer|vendor|part}) {
1143         my $object       = $cvar->value;
1144         my $method       = $result->{type} eq 'part' ? 'description' : 'name';
1145
1146         $result->{id}    = int($cvar->number_value) || undef;
1147         $result->{value} = $object ? $object->$method // '' : '';
1148
1149       } else {
1150         $result->{value} = $cvar->value;
1151       }
1152
1153       ( $cvar->config->name => $result )
1154
1155     } grep { $_->is_valid } @{ $cvars }
1156   };
1157 }
1158
1159 sub normalize_name {
1160   my ($self) = @_;
1161
1162   # check if feature is enabled (select normalize_vc_names from defaults)
1163   return unless ($::instance_conf->get_normalize_vc_names);
1164
1165   return unless $self->{cv};
1166   my $name = $self->{cv}->name;
1167   $name =~ s/\s+$//;
1168   $name =~ s/^\s+//;
1169   $name =~ s/\s+/ /g;
1170   $self->{cv}->name($name);
1171 }
1172
1173 sub home_address_for_google_maps {
1174   my ($self)  = @_;
1175
1176   my $address = $::instance_conf->get_address // '';
1177   $address    =~ s{^\s+|\s+$|\r+}{}g;
1178   $address    =~ s{\n+}{,}g;
1179   $address    =~ s{\s+}{ }g;
1180
1181   return $address;
1182 }
1183
1184 sub init_customer_models {
1185   my ($self) = @_;
1186
1187   SL::Controller::Helper::GetModels->new(
1188     controller   => $self,
1189     model        => 'Customer',
1190     sorted => {
1191       _default  => {
1192         by => 'customernumber',
1193         dir  => 1,
1194       },
1195       customernumber => t8('Customer Number'),
1196     },
1197     query => [
1198      ( salesman_id => SL::DB::Manager::Employee->current->id) x !$::auth->assert('customer_vendor_all_edit', 1),
1199     ],
1200   );
1201 }
1202
1203 sub init_vendor_models {
1204   my ($self) = @_;
1205
1206   SL::Controller::Helper::GetModels->new(
1207     controller => $self,
1208     model      => 'Vendor',
1209     sorted => {
1210       _default  => {
1211         by => 'vendornumber',
1212         dir  => 1,
1213       },
1214       vendornumber => t8('Vendor Number'),
1215     },
1216   );
1217 }
1218
1219 sub _new_customer_vendor_object {
1220   my ($self) = @_;
1221
1222   my $class  = 'SL::DB::' . ($self->is_vendor ? 'Vendor' : 'Customer');
1223   return $class->new(
1224     contacts         => [],
1225     shipto           => [],
1226     custom_variables => [],
1227   );
1228 }
1229
1230 sub _new_contact_object {
1231   my ($self) = @_;
1232
1233   return SL::DB::Contact->new(custom_variables => []);
1234 }
1235
1236 1;