Preisgruppenpreise als Preisliste bei Kunden anzeigen
[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');
483
484   my $dbh = $::form->get_standard_dbh();
485
486   my ($arap, $db, $qty_sign);
487   if ( $self->is_vendor() ) {
488     $arap = 'ap';
489     $db = 'vendor';
490     $qty_sign = ' * -1 AS qty';
491   } else {
492     $arap = 'ar';
493     $db = 'customer';
494     $qty_sign = '';
495   }
496
497   my $where = ' WHERE 1=1';
498   my @values;
499
500   if ( !$self->is_vendor() && $::form->{shipto_id} && $::form->{shipto_id} ne 'all' ) {
501     $where .= " AND ${arap}.shipto_id = ?";
502     push(@values, $::form->{shipto_id});
503   } else {
504     $where .= " AND ${arap}.${db}_id = ?";
505     push(@values, $::form->{id});
506   }
507
508   if ( $::form->{delivery_from} ) {
509     $where .= " AND ${arap}.transdate >= ?";
510     push(@values, conv_date($::form->{delivery_from}));
511   }
512
513   if ( $::form->{delivery_to} ) {
514     $where .= " AND ${arap}.transdate <= ?";
515     push(@values, conv_date($::form->{delivery_to}));
516   }
517
518   my $query =
519     "SELECT
520        s.shiptoname,
521        i.qty ${qty_sign},
522        ${arap}.id,
523        ${arap}.transdate,
524        ${arap}.invnumber,
525        ${arap}.ordnumber,
526        i.description,
527        i.unit,
528        i.sellprice,
529        oe.id AS oe_id,
530        invoice
531      FROM ${arap}
532
533      LEFT JOIN shipto s
534       ON ". ($arap eq 'ar' ? '(ar.shipto_id = s.shipto_id) ' : '(ap.id = s.trans_id) ') ."
535
536      LEFT JOIN invoice i
537        ON ${arap}.id = i.trans_id
538
539      LEFT JOIN parts p
540        ON p.id = i.parts_id
541
542      LEFT JOIN oe
543        ON (oe.ordnumber = ${arap}.ordnumber AND NOT ${arap}.ordnumber = ''
544            AND ". ($arap eq 'ar' ? 'oe.customer_id IS NOT NULL' : 'oe.vendor_id IS NOT NULL') ." )
545
546      ${where}
547      ORDER BY ${arap}.transdate DESC LIMIT 15";
548
549   $self->{delivery} = selectall_hashref_query($::form, $dbh, $query, @values);
550
551   $self->render('customer_vendor/get_delivery', { layout => 0 });
552 }
553
554 sub action_ajaj_get_shipto {
555   my ($self) = @_;
556
557   my $data = {};
558   $data->{shipto} = {
559     map(
560       {
561         my $name = 'shipto'. $_;
562         $name => $self->{shipto}->$name;
563       }
564       qw(_id name department_1 department_2 street zipcode city gln country contact phone fax email)
565     )
566   };
567
568   $data->{shipto_cvars} = $self->_prepare_cvar_configs_for_ajaj($self->{shipto}->cvars_by_config);
569
570   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
571 }
572
573 sub action_ajaj_get_contact {
574   my ($self) = @_;
575
576   my $data;
577
578   $data->{contact} = {
579     map(
580       {
581         my $name = 'cp_'. $_;
582
583         if ( $_ eq 'birthday' && $self->{contact}->$name ) {
584           $name => $self->{contact}->$name->to_lxoffice;
585         } else {
586           $name => $self->{contact}->$name;
587         }
588       }
589       qw(
590         id gender abteilung title position givenname name email phone1 phone2 fax mobile1 mobile2
591         satphone satfax project street zipcode city privatphone privatemail birthday main
592       )
593     )
594   };
595
596   $data->{contact_cvars} = $self->_prepare_cvar_configs_for_ajaj($self->{contact}->cvars_by_config);
597
598   # avoid two or more main_cp
599   my $has_main_cp = grep { $_->cp_main == 1 } @{ $self->{cv}->contacts };
600   $data->{contact}->{disable_cp_main} = 1 if ($has_main_cp && !$data->{contact}->{cp_main});
601
602   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
603 }
604
605 sub action_ajaj_autocomplete {
606   my ($self, %params) = @_;
607
608   my ($model, $manager, $number, $matches);
609
610   # first see if this is customer or vendor picking
611   if ($::form->{type} eq 'customer') {
612      $model   = $self->customer_models;
613      $manager = 'SL::DB::Manager::Customer';
614      $number  = 'customernumber';
615   } elsif ($::form->{type} eq 'vendor')  {
616      $model   = $self->vendor_models;
617      $manager = 'SL::DB::Manager::Vendor';
618      $number  = 'vendornumber';
619   } else {
620      die "unknown type $::form->{type}";
621   }
622
623   # if someone types something, and hits enter, assume he entered the full name.
624   # if something matches, treat that as sole match
625   # unfortunately get_models can't do more than one per package atm, so we d it
626   # the oldfashioned way.
627   if ($::form->{prefer_exact}) {
628     my $exact_matches;
629     if (1 == scalar @{ $exact_matches = $manager->get_all(
630       query => [
631         obsolete => 0,
632         (salesman_id => SL::DB::Manager::Employee->current->id) x !$::auth->assert('customer_vendor_all_edit', 1),
633         or => [
634           name    => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
635           $number => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
636         ]
637       ],
638       limit => 2,
639     ) }) {
640       $matches = $exact_matches;
641     }
642   }
643
644   $matches //= $model->get;
645
646   my @hashes = map {
647    +{
648      value       => $_->displayable_name,
649      label       => $_->displayable_name,
650      id          => $_->id,
651      $number     => $_->$number,
652      name        => $_->name,
653      type        => $::form->{type},
654      cvars       => { map { ($_->config->name => { value => $_->value_as_text, is_valid => $_->is_valid }) } @{ $_->cvars_by_config } },
655     }
656   } @{ $matches };
657
658   $self->render(\ SL::JSON::to_json(\@hashes), { layout => 0, type => 'json', process => 0 });
659 }
660
661 sub action_test_page {
662   $_[0]->render('customer_vendor/test_page');
663 }
664
665 sub action_ajax_list_prices {
666   my ($self, %params) = @_;
667
668   my $report   = SL::ReportGenerator->new(\%::myconfig, $::form);
669   my @columns  = qw(partnumber description price);
670   my @visible  = qw(partnumber description price);
671   my @sortable = qw(partnumber description price);
672
673   my %column_defs = (
674     partnumber  => { text => $::locale->text('Part Number'),      sub => sub { $_[0]->parts->partnumber  } },
675     description => { text => $::locale->text('Part Description'), sub => sub { $_[0]->parts->description } },
676     price       => { text => $::locale->text('Price'),            sub => sub { $::form->format_amount(\%::myconfig, $_[0]->price, 2) }, align => 'right' },
677   );
678
679   $::form->{sort_by}  ||= 'partnumber';
680   $::form->{sort_dir} //= 1;
681
682   for my $col (@sortable) {
683     $column_defs{$col}{link} = $self->url_for(
684       action   => 'ajax_list_prices',
685       callback => $::form->{callback},
686       db       => $::form->{db},
687       id       => $self->{cv}->id,
688       sort_by  => $col,
689       sort_dir => ($::form->{sort_by} eq $col ? 1 - $::form->{sort_dir} : $::form->{sort_dir})
690     );
691   }
692
693   map { $column_defs{$_}{visible} = 1 } @visible;
694
695   my $pricegroup;
696   $pricegroup = $self->{cv}->pricegroup->pricegroup if $self->{cv}->pricegroup;
697
698   $report->set_columns(%column_defs);
699   $report->set_column_order(@columns);
700   $report->set_options(allow_pdf_export => 0, allow_csv_export => 0);
701   $report->set_sort_indicator($::form->{sort_by}, $::form->{sort_dir});
702   $report->set_export_options(@{ $params{report_generator_export_options} || [] });
703   $report->set_options(
704     %{ $params{report_generator_options} || {} },
705     output_format        => 'HTML',
706     top_info_text        => $::locale->text('Pricegroup') . ': ' . $pricegroup,
707     title                => $::locale->text('Price List'),
708   );
709
710   my $sort_param = $::form->{sort_by} eq 'price'       ? 'price'             :
711                    $::form->{sort_by} eq 'description' ? 'parts.description' :
712                    'parts.partnumber';
713   $sort_param .= ' ' . ($::form->{sort_dir} ? 'ASC' : 'DESC');
714   my $prices = SL::DB::Manager::Price->get_all(where        => [ pricegroup_id => $self->{cv}->pricegroup_id ],
715                                                sort_by      => $sort_param,
716                                                with_objects => 'parts');
717
718   $self->report_generator_list_objects(report => $report, objects => $prices, layout => 0, header => 0);
719 }
720
721 sub is_vendor {
722   return $::form->{db} eq 'vendor';
723 }
724
725 sub is_customer {
726   return $::form->{db} eq 'customer';
727 }
728
729 sub is_orphaned {
730   my ($self) = @_;
731
732   if ( defined($self->{_is_orphaned}) ) {
733     return $self->{_is_orphaned};
734   }
735
736   my $arap      = $self->is_vendor ? 'ap' : 'ar';
737   my $num_args  = 3;
738
739   my $cv = $self->is_vendor ? 'vendor' : 'customer';
740
741   my $query =
742    'SELECT a.id
743     FROM '. $arap .' AS a
744     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
745     WHERE ct.id = ?
746
747     UNION
748
749     SELECT a.id
750     FROM oe a
751     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
752     WHERE ct.id = ?
753
754     UNION
755
756     SELECT a.id
757     FROM delivery_orders a
758     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
759     WHERE ct.id = ?';
760
761
762   if ( $self->is_vendor ) {
763     $query .=
764      ' UNION
765       SELECT 1 FROM makemodel mm WHERE mm.make = ?';
766     $num_args++;
767   }
768
769   my ($dummy) = selectrow_query($::form, $::form->get_standard_dbh(), $query, (conv_i($self->{cv}->id)) x $num_args);
770
771   return $self->{_is_orphaned} = !$dummy;
772 }
773
774 sub _copy_form_to_cvars {
775   my ($self, %params) = @_;
776
777   foreach my $cvar (@{ $params{target}->cvars_by_config }) {
778     my $value = $params{source}->{$cvar->config->name};
779     $value    = $::form->parse_amount(\%::myconfig, $value) if $cvar->config->type eq 'number';
780
781     $cvar->value($value);
782   }
783 }
784
785 sub _instantiate_args {
786   my ($self) = @_;
787
788   my $curr_employee = SL::DB::Manager::Employee->current;
789
790   if ( $::form->{cv}->{id} ) {
791     if ( $self->is_vendor() ) {
792       $self->{cv} = SL::DB::Vendor->new(id => $::form->{cv}->{id})->load();
793     } else {
794       $self->{cv} = SL::DB::Customer->new(id => $::form->{cv}->{id})->load();
795     }
796   } else {
797     $self->{cv} = $self->_new_customer_vendor_object;
798   }
799   $self->{cv}->assign_attributes(%{$::form->{cv}});
800
801   if ( $self->is_customer() && $::form->{cv}->{taxincluded_checked} eq '' ) {
802     $self->{cv}->taxincluded_checked(undef);
803   }
804
805   $self->{cv}->hourly_rate($::instance_conf->get_customer_hourly_rate) if $self->is_customer && !$self->{cv}->hourly_rate;
806
807   if ( $::form->{note}->{id} ) {
808     $self->{note} = SL::DB::Note->new(id => $::form->{note}->{id})->load();
809     $self->{note_followup} = $self->{note}->follow_up;
810     $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
811   } else {
812     $self->{note} = SL::DB::Note->new();
813     $self->{note_followup} = SL::DB::FollowUp->new();
814     $self->{note_followup_link} = SL::DB::FollowUpLink->new();
815   }
816
817   $self->{note}->assign_attributes(%{$::form->{note}});
818   $self->{note}->created_by($curr_employee->id);
819   $self->{note}->trans_module('ct');
820
821   $self->{note_followup}->assign_attributes(%{$::form->{note_followup}});
822   $self->{note_followup}->note($self->{note});
823   $self->{note_followup}->created_by($curr_employee->id);
824
825   $self->{note_followup_link}->trans_type($self->is_vendor() ? 'vendor' : 'customer');
826   $self->{note_followup_link}->trans_info($self->{cv}->name);
827
828   if ( $::form->{shipto}->{shipto_id} ) {
829     $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto}->{shipto_id})->load();
830   } else {
831     $self->{shipto} = SL::DB::Shipto->new();
832   }
833   $self->{shipto}->assign_attributes(%{$::form->{shipto}});
834   $self->{shipto}->module('CT');
835
836   if ( $::form->{contact}->{cp_id} ) {
837     $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact}->{cp_id})->load();
838   } else {
839     $self->{contact} = $self->_new_contact_object;
840   }
841   $self->{contact}->assign_attributes(%{$::form->{contact}});
842
843   $self->_copy_form_to_cvars(target => $self->{cv},      source => $::form->{cv_cvars});
844   $self->_copy_form_to_cvars(target => $self->{contact}, source => $::form->{contact_cvars});
845   $self->_copy_form_to_cvars(target => $self->{shipto},  source => $::form->{shipto_cvars});
846 }
847
848 sub _load_customer_vendor {
849   my ($self) = @_;
850
851   if ( $self->is_vendor() ) {
852     $self->{cv} = SL::DB::Vendor->new(id => $::form->{id})->load();
853   } else {
854     $self->{cv} = SL::DB::Customer->new(id => $::form->{id})->load();
855   }
856
857   if ( $::form->{note_id} ) {
858     $self->{note} = SL::DB::Note->new(id => $::form->{note_id})->load();
859     $self->{note_followup} = $self->{note}->follow_up;
860     $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
861   } else {
862     $self->{note} = SL::DB::Note->new();
863     $self->{note_followup} = SL::DB::FollowUp->new();
864     $self->{note_followup_link} = SL::DB::FollowUpLink->new();
865   }
866
867   if ( $::form->{shipto_id} ) {
868     $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto_id})->load();
869
870     if ( $self->{shipto}->trans_id != $self->{cv}->id ) {
871       die($::locale->text('Error'));
872     }
873   } else {
874     $self->{shipto} = SL::DB::Shipto->new();
875   }
876
877   if ( $::form->{contact_id} ) {
878     $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact_id})->load();
879
880     if ( $self->{contact}->cp_cv_id != $self->{cv}->id ) {
881       die($::locale->text('Error'));
882     }
883   } else {
884     $self->{contact} = $self->_new_contact_object;
885   }
886 }
887
888 sub _check_customer_vendor_all_edit {
889   my ($self) = @_;
890
891   unless ($::auth->assert('customer_vendor_all_edit', 1)) {
892     die($::locale->text("You don't have the rights to edit this customer.") . "\n")
893       if $self->{cv}->is_customer and
894          SL::DB::Manager::Employee->current->id != $self->{cv}->salesman_id;
895   };
896 };
897
898 sub _create_customer_vendor {
899   my ($self) = @_;
900
901   $self->{cv} = $self->_new_customer_vendor_object;
902   $self->{cv}->currency_id($::instance_conf->get_currency_id());
903
904   $self->{note} = SL::DB::Note->new();
905
906   $self->{note_followup} = SL::DB::FollowUp->new();
907
908   $self->{shipto} = SL::DB::Shipto->new();
909
910   $self->{contact} = $self->_new_contact_object;
911 }
912
913 sub _pre_render {
914   my ($self) = @_;
915
916   my $dbh = $::form->get_standard_dbh();
917
918   my $query;
919
920   $self->{all_business} = SL::DB::Manager::Business->get_all();
921
922   $self->{all_employees} = SL::DB::Manager::Employee->get_all(query => [ deleted => 0 ]);
923
924   $query =
925     'SELECT DISTINCT(greeting)
926      FROM customer
927      WHERE greeting IS NOT NULL AND greeting != \'\'
928      UNION
929        SELECT DISTINCT(greeting)
930        FROM vendor
931        WHERE greeting IS NOT NULL AND greeting != \'\'
932      ORDER BY greeting';
933   $self->{all_greetings} = [
934     map(
935       { $_->{greeting}; }
936       selectall_hashref_query($::form, $dbh, $query)
937     )
938   ];
939
940   $query =
941     'SELECT DISTINCT(cp_title) AS title
942      FROM contacts
943      WHERE cp_title IS NOT NULL AND cp_title != \'\'
944      ORDER BY cp_title';
945   $self->{all_titles} = [
946     map(
947       { $_->{title}; }
948       selectall_hashref_query($::form, $dbh, $query)
949     )
950   ];
951
952   $self->{all_currencies} = SL::DB::Manager::Currency->get_all();
953
954   $self->{all_languages} = SL::DB::Manager::Language->get_all();
955
956   $self->{all_taxzones} = SL::DB::Manager::TaxZone->get_all_sorted();
957
958   if ( $::instance_conf->get_vertreter() ) {
959     $query =
960       'SELECT id
961        FROM business
962        WHERE salesman';
963     my $business_ids = [
964       map(
965         { $_->{id}; }
966         selectall_hashref_query($::form, $dbh, $query)
967       )
968     ];
969
970     if ( $business_ids->[0] ) {
971       $self->{all_salesman_customers} = SL::DB::Manager::Customer->get_all(query => [business_id => $business_ids]);
972     } else {
973       $self->{all_salesman_customers} = [];
974     }
975   } else {
976     $self->{all_salesmen} = SL::DB::Manager::Employee->get_all(query => [ or => [ id => $self->{cv}->salesman_id,  deleted => 0 ] ]);
977   }
978
979   $self->{all_payment_terms} = SL::DB::Manager::PaymentTerm->get_all_sorted(where => [ or => [ id       => $self->{cv}->payment_id,
980                                                                                                obsolete => 0 ] ]);
981
982   $self->{all_delivery_terms} = SL::DB::Manager::DeliveryTerm->get_all();
983
984   if ($self->{cv}->is_customer) {
985     $self->{all_pricegroups} = SL::DB::Manager::Pricegroup->get_all_sorted(query => [ or => [ id => $self->{cv}->pricegroup_id, obsolete => 0 ] ]);
986   }
987
988   $query =
989     'SELECT DISTINCT(cp_abteilung) AS department
990      FROM contacts
991      WHERE cp_abteilung IS NOT NULL AND cp_abteilung != \'\'
992      ORDER BY cp_abteilung';
993   $self->{all_departments} = [
994     map(
995       { $_->{department}; }
996       selectall_hashref_query($::form, $dbh, $query)
997     )
998   ];
999
1000   $self->{contacts} = $self->{cv}->contacts;
1001   $self->{contacts} ||= [];
1002
1003   $self->{shiptos} = $self->{cv}->shipto;
1004   $self->{shiptos} ||= [];
1005
1006   $self->{notes} = SL::DB::Manager::Note->get_all(
1007     query => [
1008       trans_id => $self->{cv}->id,
1009       trans_module => 'ct',
1010     ],
1011     with_objects => ['follow_up'],
1012   );
1013
1014   if ( $self->is_vendor()) {
1015     $self->{open_items} = SL::DB::Manager::PurchaseInvoice->get_all_count(
1016       query => [
1017         vendor_id => $self->{cv}->id,
1018         paid => {lt_sql => 'amount'},
1019       ],
1020     );
1021   } else {
1022     $self->{open_items} = SL::DB::Manager::Invoice->get_all_count(
1023       query => [
1024         customer_id => $self->{cv}->id,
1025         paid => {lt_sql => 'amount'},
1026       ],
1027     );
1028   }
1029
1030   if ( $self->is_vendor() ) {
1031     $self->{open_orders} = SL::DB::Manager::Order->get_all_count(
1032       query => [
1033         vendor_id => $self->{cv}->id,
1034         closed => 'F',
1035       ],
1036     );
1037   } else {
1038     $self->{open_orders} = SL::DB::Manager::Order->get_all_count(
1039       query => [
1040         customer_id => $self->{cv}->id,
1041         closed => 'F',
1042       ],
1043     );
1044   }
1045   $self->{template_args} ||= {};
1046
1047   $::request->{layout}->add_javascripts('kivi.CustomerVendor.js');
1048   $::request->{layout}->add_javascripts('kivi.File.js');
1049   $::request->{layout}->add_javascripts('kivi.CustomerVendorTurnover.js');
1050
1051   $self->_setup_form_action_bar;
1052 }
1053
1054 sub _setup_form_action_bar {
1055   my ($self) = @_;
1056
1057   for my $bar ($::request->layout->get('actionbar')) {
1058     $bar->add(
1059       combobox => [
1060         action => [
1061           t8('Save'),
1062           submit    => [ '#form', { action => "CustomerVendor/save" } ],
1063           checks    => [ 'check_taxzone_and_ustid' ],
1064           accesskey => 'enter',
1065         ],
1066         action => [
1067           t8('Save and Close'),
1068           submit => [ '#form', { action => "CustomerVendor/save_and_close" } ],
1069           checks => [ 'check_taxzone_and_ustid' ],
1070         ],
1071       ], # end of combobox "Save"
1072
1073       combobox => [
1074         action => [ t8('Workflow') ],
1075         (action => [
1076           t8('Save and AP Transaction'),
1077           submit => [ '#form', { action => "CustomerVendor/save_and_ap_transaction" } ],
1078           checks => [ 'check_taxzone_and_ustid' ],
1079         ]) x !!$self->is_vendor,
1080         (action => [
1081           t8('Save and AR Transaction'),
1082           submit => [ '#form', { action => "CustomerVendor/save_and_ar_transaction" } ],
1083           checks => [ 'check_taxzone_and_ustid' ],
1084         ]) x !$self->is_vendor,
1085         action => [
1086           t8('Save and Invoice'),
1087           submit => [ '#form', { action => "CustomerVendor/save_and_invoice" } ],
1088           checks => [ 'check_taxzone_and_ustid' ],
1089         ],
1090         action => [
1091           t8('Save and Order'),
1092           submit => [ '#form', { action => "CustomerVendor/save_and_order" } ],
1093           checks => [ 'check_taxzone_and_ustid' ],
1094         ],
1095         (action => [
1096           t8('Save and RFQ'),
1097           submit => [ '#form', { action => "CustomerVendor/save_and_rfq" } ],
1098           checks => [ 'check_taxzone_and_ustid' ],
1099         ]) x !!$self->is_vendor,
1100         (action => [
1101           t8('Save and Quotation'),
1102           submit => [ '#form', { action => "CustomerVendor/save_and_quotation" } ],
1103           checks => [ 'check_taxzone_and_ustid' ],
1104         ]) x !$self->is_vendor,
1105       ], # end of combobox "Workflow"
1106
1107       action => [
1108         t8('Delete'),
1109         submit   => [ '#form', { action => "CustomerVendor/delete" } ],
1110         confirm  => t8('Do you really want to delete this object?'),
1111         disabled => !$self->{cv}->id    ? t8('This object has not been saved yet.')
1112                   : !$self->is_orphaned ? t8('This object has already been used.')
1113                   :                       undef,
1114       ],
1115
1116       'separator',
1117
1118       action => [
1119         t8('History'),
1120         call     => [ 'kivi.CustomerVendor.showHistoryWindow', $self->{cv}->id ],
1121         disabled => !$self->{cv}->id ? t8('This object has not been saved yet.') : undef,
1122       ],
1123     );
1124   }
1125 }
1126
1127 sub _prepare_cvar_configs_for_ajaj {
1128   my ($self, $cvars) = @_;
1129
1130   return {
1131     map {
1132       my $cvar   = $_;
1133       my $result = { type => $cvar->config->type };
1134
1135       if ($cvar->config->type eq 'number') {
1136         $result->{value} = $::form->format_amount(\%::myconfig, $cvar->value, -2);
1137
1138       } elsif ($result->{type} eq 'date') {
1139         $result->{value} = $cvar->value ? $cvar->value->to_kivitendo : undef;
1140
1141       } elsif ($result->{type} =~ m{customer|vendor|part}) {
1142         my $object       = $cvar->value;
1143         my $method       = $result->{type} eq 'part' ? 'description' : 'name';
1144
1145         $result->{id}    = int($cvar->number_value) || undef;
1146         $result->{value} = $object ? $object->$method // '' : '';
1147
1148       } else {
1149         $result->{value} = $cvar->value;
1150       }
1151
1152       ( $cvar->config->name => $result )
1153
1154     } grep { $_->is_valid } @{ $cvars }
1155   };
1156 }
1157
1158 sub normalize_name {
1159   my ($self) = @_;
1160
1161   # check if feature is enabled (select normalize_vc_names from defaults)
1162   return unless ($::instance_conf->get_normalize_vc_names);
1163
1164   return unless $self->{cv};
1165   my $name = $self->{cv}->name;
1166   $name =~ s/\s+$//;
1167   $name =~ s/^\s+//;
1168   $name =~ s/\s+/ /g;
1169   $self->{cv}->name($name);
1170 }
1171
1172 sub home_address_for_google_maps {
1173   my ($self)  = @_;
1174
1175   my $address = $::instance_conf->get_address // '';
1176   $address    =~ s{^\s+|\s+$|\r+}{}g;
1177   $address    =~ s{\n+}{,}g;
1178   $address    =~ s{\s+}{ }g;
1179
1180   return $address;
1181 }
1182
1183 sub init_customer_models {
1184   my ($self) = @_;
1185
1186   SL::Controller::Helper::GetModels->new(
1187     controller   => $self,
1188     model        => 'Customer',
1189     sorted => {
1190       _default  => {
1191         by => 'customernumber',
1192         dir  => 1,
1193       },
1194       customernumber => t8('Customer Number'),
1195     },
1196     query => [
1197      ( salesman_id => SL::DB::Manager::Employee->current->id) x !$::auth->assert('customer_vendor_all_edit', 1),
1198     ],
1199   );
1200 }
1201
1202 sub init_vendor_models {
1203   my ($self) = @_;
1204
1205   SL::Controller::Helper::GetModels->new(
1206     controller => $self,
1207     model      => 'Vendor',
1208     sorted => {
1209       _default  => {
1210         by => 'vendornumber',
1211         dir  => 1,
1212       },
1213       vendornumber => t8('Vendor Number'),
1214     },
1215   );
1216 }
1217
1218 sub _new_customer_vendor_object {
1219   my ($self) = @_;
1220
1221   my $class  = 'SL::DB::' . ($self->is_vendor ? 'Vendor' : 'Customer');
1222   return $class->new(
1223     contacts         => [],
1224     shipto           => [],
1225     custom_variables => [],
1226   );
1227 }
1228
1229 sub _new_contact_object {
1230   my ($self) = @_;
1231
1232   return SL::DB::Contact->new(custom_variables => []);
1233 }
1234
1235 1;