Anreden: Kunden-/Lieferantenstamm: Freitext-Feld und/oder Auswahlliste
[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::Util qw(trim);
13 use SL::Controller::Helper::GetModels;
14 use SL::Controller::Helper::ReportGenerator;
15 use SL::Controller::Helper::ParseFilter;
16
17 use SL::DB::Customer;
18 use SL::DB::Vendor;
19 use SL::DB::Business;
20 use SL::DB::Employee;
21 use SL::DB::Greeting;
22 use SL::DB::Language;
23 use SL::DB::TaxZone;
24 use SL::DB::Note;
25 use SL::DB::PaymentTerm;
26 use SL::DB::Pricegroup;
27 use SL::DB::Price;
28 use SL::DB::Contact;
29 use SL::DB::FollowUp;
30 use SL::DB::FollowUpLink;
31 use SL::DB::History;
32 use SL::DB::Currency;
33 use SL::DB::Invoice;
34 use SL::DB::PurchaseInvoice;
35 use SL::DB::Order;
36
37 use Data::Dumper;
38
39 use Rose::Object::MakeMethods::Generic (
40   'scalar --get_set_init' => [ qw(customer_models vendor_models) ],
41 );
42
43 # safety
44 __PACKAGE__->run_before(
45   sub {
46     $::auth->assert('customer_vendor_edit');
47   },
48   except => [ qw(ajaj_autocomplete) ],
49 );
50 __PACKAGE__->run_before(
51   '_instantiate_args',
52   only => [
53     'save',
54     'save_and_ap_transaction',
55     'save_and_ar_transaction',
56     'save_and_close',
57     'save_and_invoice',
58     'save_and_order',
59     'save_and_quotation',
60     'save_and_rfq',
61     'delete',
62     'delete_contact',
63     'delete_shipto',
64   ]
65 );
66
67 __PACKAGE__->run_before(
68   '_load_customer_vendor',
69   only => [
70     'edit',
71     'show',
72     'update',
73     'ajaj_get_shipto',
74     'ajaj_get_contact',
75     'ajax_list_prices',
76   ]
77 );
78
79 # make sure this comes after _load_customer_vendor
80 __PACKAGE__->run_before(
81   '_check_customer_vendor_all_edit',
82   only => [
83     'edit',
84     'show',
85     'update',
86     'delete',
87     'save',
88     'save_and_ap_transaction',
89     'save_and_ar_transaction',
90     'save_and_close',
91     'save_and_invoice',
92     'save_and_order',
93     'save_and_quotation',
94     'save_and_rfq',
95     'delete',
96     'delete_contact',
97     'delete_shipto',
98   ]
99 );
100
101 __PACKAGE__->run_before(
102   '_create_customer_vendor',
103   only => [
104     'add',
105   ]
106 );
107
108 __PACKAGE__->run_before('normalize_name');
109
110
111 sub action_add {
112   my ($self) = @_;
113
114   $self->_pre_render();
115   $self->{cv}->assign_attributes(hourly_rate => $::instance_conf->get_customer_hourly_rate) if $self->{cv}->is_customer;
116
117   $self->render(
118     'customer_vendor/form',
119     title => ($self->is_vendor() ? $::locale->text('Add Vendor') : $::locale->text('Add Customer')),
120     %{$self->{template_args}}
121   );
122 }
123
124 sub action_edit {
125   my ($self) = @_;
126
127   $self->_pre_render();
128   $self->render(
129     'customer_vendor/form',
130     title => ($self->is_vendor() ? $::locale->text('Edit Vendor') : $::locale->text('Edit Customer')),
131     %{$self->{template_args}}
132   );
133 }
134
135 sub action_show {
136   my ($self) = @_;
137
138   if ($::request->type eq 'json') {
139     my $cv_hash;
140     if (!$self->{cv}) {
141       # TODO error
142     } else {
143       $cv_hash          = $self->{cv}->as_tree;
144       $cv_hash->{cvars} = $self->{cv}->cvar_as_hashref;
145     }
146
147     $self->render(\ SL::JSON::to_json($cv_hash), { layout => 0, type => 'json', process => 0 });
148   }
149 }
150
151 sub _save {
152   my ($self) = @_;
153
154   my @errors = $self->{cv}->validate;
155   if (@errors) {
156     flash('error', @errors);
157     $self->_pre_render();
158     $self->render(
159       'customer_vendor/form',
160       title => ($self->is_vendor() ? t8('Edit Vendor') : t8('Edit Customer')),
161       %{$self->{template_args}}
162     );
163     $::dispatcher->end_request;
164   }
165
166   $self->{cv}->greeting(trim $self->{cv}->greeting);
167   my $save_greeting  = $self->{cv}->greeting
168                     && $::instance_conf->get_vc_greetings_use_textfield
169                     && SL::DB::Manager::Greeting->get_all_count(where => [description => $self->{cv}->greeting]) == 0;
170
171   my $db = $self->{cv}->db;
172
173   $db->with_transaction(sub {
174     my $cvs_by_nr;
175     if ( $self->is_vendor() ) {
176       if ( $self->{cv}->vendornumber ) {
177         $cvs_by_nr = SL::DB::Manager::Vendor->get_all(query => [vendornumber => $self->{cv}->vendornumber]);
178       }
179     } else {
180       if ( $self->{cv}->customernumber ) {
181         $cvs_by_nr = SL::DB::Manager::Customer->get_all(query => [customernumber => $self->{cv}->customernumber]);
182       }
183     }
184
185     foreach my $entry (@{$cvs_by_nr}) {
186       if( $entry->id != $self->{cv}->id ) {
187         my $msg =
188           $self->is_vendor() ? $::locale->text('This vendor number is already in use.') : $::locale->text('This customer number is already in use.');
189
190         $::form->error($msg);
191       }
192     }
193
194     $self->{cv}->save(cascade => 1);
195
196     SL::DB::Greeting->new(description => $self->{cv}->greeting)->save if $save_greeting;
197
198     $self->{contact}->cp_cv_id($self->{cv}->id);
199     if( $self->{contact}->cp_name ne '' || $self->{contact}->cp_givenname ne '' ) {
200       $self->{contact}->save(cascade => 1);
201     }
202
203     if( $self->{note}->subject ne '' && $self->{note}->body ne '' ) {
204
205       if ( !$self->{note_followup}->follow_up_date ) {
206         $::form->error($::locale->text('Date missing!'));
207       }
208
209       $self->{note}->trans_id($self->{cv}->id);
210       $self->{note}->save();
211
212       $self->{note_followup}->save();
213
214       $self->{note_followup_link}->follow_up_id($self->{note_followup}->id);
215       $self->{note_followup_link}->trans_id($self->{cv}->id);
216       $self->{note_followup_link}->save();
217
218       SL::Helper::Flash::flash_later('info', $::locale->text('Follow-Up saved.'));
219     }
220
221     $self->{shipto}->trans_id($self->{cv}->id);
222     if(any { $self->{shipto}->$_ ne '' } qw(shiptoname shiptodepartment_1 shiptodepartment_2 shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax shiptoemail)) {
223       $self->{shipto}->save(cascade => 1);
224     }
225
226     my $snumbers = $self->is_vendor() ? 'vendornumber_'. $self->{cv}->vendornumber : 'customernumber_'. $self->{cv}->customernumber;
227     SL::DB::History->new(
228       trans_id => $self->{cv}->id,
229       snumbers => $snumbers,
230       employee_id => SL::DB::Manager::Employee->current->id,
231       addition => 'SAVED',
232     )->save();
233
234     if ( $::form->{delete_notes} ) {
235       foreach my $note_id (@{ $::form->{delete_notes} }) {
236         my $note = SL::DB::Note->new(id => $note_id)->load();
237         if ( $note->follow_up ) {
238           if ( $note->follow_up->follow_up_link ) {
239             $note->follow_up->follow_up_link->delete(cascade => 'delete');
240           }
241           $note->follow_up->delete(cascade => 'delete');
242         }
243         $note->delete(cascade => 'delete');
244       }
245     }
246
247     1;
248   }) || die($db->error);
249
250 }
251
252 sub action_save {
253   my ($self) = @_;
254
255   $self->_save();
256
257   my @redirect_params = (
258     action => 'edit',
259     id     => $self->{cv}->id,
260     db     => ($self->is_vendor() ? 'vendor' : 'customer'),
261   );
262
263   if ( $self->{contact}->cp_id ) {
264     push(@redirect_params, contact_id => $self->{contact}->cp_id);
265   }
266
267   if ( $self->{shipto}->shipto_id ) {
268     push(@redirect_params, shipto_id => $self->{shipto}->shipto_id);
269   }
270
271   $self->redirect_to(@redirect_params);
272 }
273
274 sub action_save_and_close {
275   my ($self) = @_;
276
277   $self->_save();
278
279   my $msg = $self->is_vendor() ? $::locale->text('Vendor saved') : $::locale->text('Customer saved');
280   $::form->redirect($msg);
281 }
282
283 sub _transaction {
284   my ($self, $script) = @_;
285
286   $::auth->assert('gl_transactions | ap_transactions | ar_transactions'.
287                     '| invoice_edit         | vendor_invoice_edit | ' .
288                  ' request_quotation_edit | sales_quotation_edit | sales_order_edit    | purchase_order_edit');
289
290   $self->_save();
291
292   my $name = $::form->escape($self->{cv}->name, 1);
293   my $db = $self->is_vendor() ? 'vendor' : 'customer';
294   my $action = 'add';
295
296   if ($::instance_conf->get_feature_experimental_order && 'oe.pl' eq $script) {
297     $script = 'controller.pl';
298     $action = 'Order/' . $action;
299   }
300
301   my $url = $self->url_for(
302     controller => $script,
303     action     => $action,
304     vc         => $db,
305     $db .'_id' => $self->{cv}->id,
306     $db        => $name,
307     type       => $::form->{type},
308     callback   => $::form->{callback},
309   );
310
311   print $::form->redirect_header($url);
312 }
313
314 sub action_save_and_ar_transaction {
315   my ($self) = @_;
316
317   $main::auth->assert('ar_transactions');
318
319   $self->_transaction('ar.pl');
320 }
321
322 sub action_save_and_ap_transaction {
323   my ($self) = @_;
324
325   $main::auth->assert('ap_transactions');
326
327   $self->_transaction('ap.pl');
328 }
329
330 sub action_save_and_invoice {
331   my ($self) = @_;
332
333   if ( $self->is_vendor() ) {
334     $::auth->assert('vendor_invoice_edit');
335   } else {
336     $::auth->assert('invoice_edit');
337   }
338
339   $::form->{type} = 'invoice';
340   $self->_transaction($self->is_vendor() ? 'ir.pl' : 'is.pl');
341 }
342
343 sub action_save_and_order {
344   my ($self) = @_;
345
346   if ( $self->is_vendor() ) {
347     $::auth->assert('purchase_order_edit');
348   } else {
349     $::auth->assert('sales_order_edit');
350   }
351
352   $::form->{type} = $self->is_vendor() ? 'purchase_order' : 'sales_order';
353   $self->_transaction('oe.pl');
354 }
355
356 sub action_save_and_rfq {
357   my ($self) = @_;
358
359   $::auth->assert('request_quotation_edit');
360
361   $::form->{type} = 'request_quotation';
362   $self->_transaction('oe.pl');
363 }
364
365 sub action_save_and_quotation {
366   my ($self) = @_;
367
368   $::auth->assert('sales_quotation_edit');
369
370   $::form->{type} = 'sales_quotation';
371   $self->_transaction('oe.pl');
372 }
373
374 sub action_delete {
375   my ($self) = @_;
376
377   my $db = $self->{cv}->db;
378
379   if( !$self->is_orphaned() ) {
380     $self->action_edit();
381   } else {
382
383     $db->with_transaction(sub {
384       $self->{cv}->delete(cascade => 1);
385
386       my $snumbers = $self->is_vendor() ? 'vendornumber_'. $self->{cv}->vendornumber : 'customernumber_'. $self->{cv}->customernumber;
387       SL::DB::History->new(
388         trans_id => $self->{cv}->id,
389         snumbers => $snumbers,
390         employee_id => SL::DB::Manager::Employee->current->id,
391         addition => 'DELETED',
392       )->save();
393     }) || die($db->error);
394
395     my $msg = $self->is_vendor() ? $::locale->text('Vendor deleted!') : $::locale->text('Customer deleted!');
396     $::form->redirect($msg);
397   }
398
399 }
400
401
402 sub action_delete_contact {
403   my ($self) = @_;
404
405   my $db = $self->{contact}->db;
406
407   if ( !$self->{contact}->cp_id ) {
408     SL::Helper::Flash::flash('error', $::locale->text('No contact selected to delete'));
409   } else {
410
411     $db->with_transaction(sub {
412       if ( $self->{contact}->used ) {
413         $self->{contact}->detach();
414         $self->{contact}->save();
415         SL::Helper::Flash::flash('info', $::locale->text('Contact is in use and was flagged invalid.'));
416       } else {
417         $self->{contact}->delete(cascade => 1);
418         SL::Helper::Flash::flash('info', $::locale->text('Contact deleted.'));
419       }
420
421       1;
422     }) || die($db->error);
423
424     $self->{contact} = $self->_new_contact_object;
425   }
426
427   $self->action_edit();
428 }
429
430 sub action_delete_shipto {
431   my ($self) = @_;
432
433   my $db = $self->{shipto}->db;
434
435   if ( !$self->{shipto}->shipto_id ) {
436     SL::Helper::Flash::flash('error', $::locale->text('No shipto selected to delete'));
437   } else {
438
439     $db->with_transaction(sub {
440       if ( $self->{shipto}->used ) {
441         $self->{shipto}->detach();
442         $self->{shipto}->save(cascade => 1);
443         SL::Helper::Flash::flash('info', $::locale->text('Shipto is in use and was flagged invalid.'));
444       } else {
445         $self->{shipto}->delete(cascade => 1);
446         SL::Helper::Flash::flash('info', $::locale->text('Shipto deleted.'));
447       }
448
449       1;
450     }) || die($db->error);
451
452     $self->{shipto} = SL::DB::Shipto->new();
453   }
454
455   $self->action_edit();
456 }
457
458
459 sub action_search {
460   my ($self) = @_;
461
462   my @url_params = (
463     controller => 'ct.pl',
464     action => 'search',
465     db => $self->is_vendor() ? 'vendor' : 'customer',
466   );
467
468   if ( $::form->{callback} ) {
469     push(@url_params, callback => $::form->{callback});
470   }
471
472   $self->redirect_to(@url_params);
473 }
474
475
476 sub action_search_contact {
477   my ($self) = @_;
478
479   my $url = 'ct.pl?action=search_contact&db=customer';
480
481   if ( $::form->{callback} ) {
482     $url .= '&callback='. $::form->escape($::form->{callback});
483   }
484
485   print $::form->redirect_header($url);
486 }
487
488 sub action_get_delivery {
489   my ($self) = @_;
490
491   $::auth->assert('sales_all_edit')    if $self->is_customer();
492   $::auth->assert('purchase_all_edit') if $self->is_vendor();
493
494   my $dbh = $::form->get_standard_dbh();
495
496   my ($arap, $db, $qty_sign);
497   if ( $self->is_vendor() ) {
498     $arap = 'ap';
499     $db = 'vendor';
500     $qty_sign = ' * -1 AS qty';
501   } else {
502     $arap = 'ar';
503     $db = 'customer';
504     $qty_sign = '';
505   }
506
507   my $where = ' WHERE 1=1';
508   my @values;
509
510   if ( !$self->is_vendor() && $::form->{shipto_id} && $::form->{shipto_id} ne 'all' ) {
511     $where .= " AND ${arap}.shipto_id = ?";
512     push(@values, $::form->{shipto_id});
513   } else {
514     $where .= " AND ${arap}.${db}_id = ?";
515     push(@values, $::form->{id});
516   }
517
518   if ( $::form->{delivery_from} ) {
519     $where .= " AND ${arap}.transdate >= ?";
520     push(@values, conv_date($::form->{delivery_from}));
521   }
522
523   if ( $::form->{delivery_to} ) {
524     $where .= " AND ${arap}.transdate <= ?";
525     push(@values, conv_date($::form->{delivery_to}));
526   }
527
528   my $query =
529     "SELECT
530        s.shiptoname,
531        i.qty ${qty_sign},
532        ${arap}.id,
533        ${arap}.transdate,
534        ${arap}.invnumber,
535        ${arap}.ordnumber,
536        i.description,
537        i.unit,
538        i.sellprice,
539        oe.id AS oe_id,
540        invoice
541      FROM ${arap}
542
543      LEFT JOIN shipto s
544       ON ". ($arap eq 'ar' ? '(ar.shipto_id = s.shipto_id) ' : '(ap.id = s.trans_id) ') ."
545
546      LEFT JOIN invoice i
547        ON ${arap}.id = i.trans_id
548
549      LEFT JOIN parts p
550        ON p.id = i.parts_id
551
552      LEFT JOIN oe
553        ON (oe.ordnumber = ${arap}.ordnumber AND NOT ${arap}.ordnumber = ''
554            AND ". ($arap eq 'ar' ? 'oe.customer_id IS NOT NULL' : 'oe.vendor_id IS NOT NULL') ." )
555
556      ${where}
557      ORDER BY ${arap}.transdate DESC LIMIT 15";
558
559   $self->{delivery} = selectall_hashref_query($::form, $dbh, $query, @values);
560
561   $self->render('customer_vendor/get_delivery', { layout => 0 });
562 }
563
564 sub action_ajaj_get_shipto {
565   my ($self) = @_;
566
567   my $data = {};
568   $data->{shipto} = {
569     map(
570       {
571         my $name = 'shipto'. $_;
572         $name => $self->{shipto}->$name;
573       }
574       qw(_id name department_1 department_2 street zipcode city gln country contact phone fax email)
575     )
576   };
577
578   $data->{shipto_cvars} = $self->_prepare_cvar_configs_for_ajaj($self->{shipto}->cvars_by_config);
579
580   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
581 }
582
583 sub action_ajaj_get_contact {
584   my ($self) = @_;
585
586   my $data;
587
588   $data->{contact} = {
589     map(
590       {
591         my $name = 'cp_'. $_;
592
593         if ( $_ eq 'birthday' && $self->{contact}->$name ) {
594           $name => $self->{contact}->$name->to_lxoffice;
595         } else {
596           $name => $self->{contact}->$name;
597         }
598       }
599       qw(
600         id gender abteilung title position givenname name email phone1 phone2 fax mobile1 mobile2
601         satphone satfax project street zipcode city privatphone privatemail birthday main
602       )
603     )
604   };
605
606   $data->{contact_cvars} = $self->_prepare_cvar_configs_for_ajaj($self->{contact}->cvars_by_config);
607
608   # avoid two or more main_cp
609   my $has_main_cp = grep { $_->cp_main == 1 } @{ $self->{cv}->contacts };
610   $data->{contact}->{disable_cp_main} = 1 if ($has_main_cp && !$data->{contact}->{cp_main});
611
612   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
613 }
614
615 sub action_ajaj_autocomplete {
616   my ($self, %params) = @_;
617
618   my ($model, $manager, $number, $matches);
619
620   # first see if this is customer or vendor picking
621   if ($::form->{type} eq 'customer') {
622      $model   = $self->customer_models;
623      $manager = 'SL::DB::Manager::Customer';
624      $number  = 'customernumber';
625   } elsif ($::form->{type} eq 'vendor')  {
626      $model   = $self->vendor_models;
627      $manager = 'SL::DB::Manager::Vendor';
628      $number  = 'vendornumber';
629   } else {
630      die "unknown type $::form->{type}";
631   }
632
633   # if someone types something, and hits enter, assume he entered the full name.
634   # if something matches, treat that as the sole match
635   # unfortunately get_models can't do more than one per package atm, so we do it
636   # the oldfashioned way.
637   if ($::form->{prefer_exact}) {
638     my $exact_matches;
639     if (1 == scalar @{ $exact_matches = $manager->get_all(
640       query => [
641         obsolete => 0,
642         (salesman_id => SL::DB::Manager::Employee->current->id) x !$::auth->assert('customer_vendor_all_edit', 1),
643         or => [
644           name    => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
645           $number => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
646         ]
647       ],
648       limit => 2,
649     ) }) {
650       $matches = $exact_matches;
651     }
652   }
653
654   $matches //= $model->get;
655
656   my @hashes = map {
657    +{
658      value       => $_->displayable_name,
659      label       => $_->displayable_name,
660      id          => $_->id,
661      $number     => $_->$number,
662      name        => $_->name,
663      type        => $::form->{type},
664      cvars       => { map { ($_->config->name => { value => $_->value_as_text, is_valid => $_->is_valid }) } @{ $_->cvars_by_config } },
665     }
666   } @{ $matches };
667
668   $self->render(\ SL::JSON::to_json(\@hashes), { layout => 0, type => 'json', process => 0 });
669 }
670
671 sub action_test_page {
672   $_[0]->render('customer_vendor/test_page');
673 }
674
675 sub action_ajax_list_prices {
676   my ($self, %params) = @_;
677
678   my $report   = SL::ReportGenerator->new(\%::myconfig, $::form);
679   my @columns  = qw(partnumber description price);
680   my @visible  = qw(partnumber description price);
681   my @sortable = qw(partnumber description price);
682
683   my %column_defs = (
684     partnumber  => { text => $::locale->text('Part Number'),      sub => sub { $_[0]->parts->partnumber  } },
685     description => { text => $::locale->text('Part Description'), sub => sub { $_[0]->parts->description } },
686     price       => { text => $::locale->text('Price'),            sub => sub { $::form->format_amount(\%::myconfig, $_[0]->price, 2) }, align => 'right' },
687   );
688
689   $::form->{sort_by}  ||= 'partnumber';
690   $::form->{sort_dir} //= 1;
691
692   for my $col (@sortable) {
693     $column_defs{$col}{link} = $self->url_for(
694       action   => 'ajax_list_prices',
695       callback => $::form->{callback},
696       db       => $::form->{db},
697       id       => $self->{cv}->id,
698       sort_by  => $col,
699       sort_dir => ($::form->{sort_by} eq $col ? 1 - $::form->{sort_dir} : $::form->{sort_dir})
700     );
701   }
702
703   map { $column_defs{$_}{visible} = 1 } @visible;
704
705   my $pricegroup;
706   $pricegroup = $self->{cv}->pricegroup->pricegroup if $self->{cv}->pricegroup;
707
708   $report->set_columns(%column_defs);
709   $report->set_column_order(@columns);
710   $report->set_options(allow_pdf_export => 0, allow_csv_export => 0);
711   $report->set_sort_indicator($::form->{sort_by}, $::form->{sort_dir});
712   $report->set_export_options(@{ $params{report_generator_export_options} || [] });
713   $report->set_options(
714     %{ $params{report_generator_options} || {} },
715     output_format        => 'HTML',
716     top_info_text        => $::locale->text('Pricegroup') . ': ' . $pricegroup,
717     title                => $::locale->text('Price List'),
718   );
719
720   my $sort_param = $::form->{sort_by} eq 'price'       ? 'price'             :
721                    $::form->{sort_by} eq 'description' ? 'parts.description' :
722                    'parts.partnumber';
723   $sort_param .= ' ' . ($::form->{sort_dir} ? 'ASC' : 'DESC');
724   my $prices = SL::DB::Manager::Price->get_all(where        => [ pricegroup_id => $self->{cv}->pricegroup_id ],
725                                                sort_by      => $sort_param,
726                                                with_objects => 'parts');
727
728   $self->report_generator_list_objects(report => $report, objects => $prices, layout => 0, header => 0);
729 }
730
731 sub is_vendor {
732   return $::form->{db} eq 'vendor';
733 }
734
735 sub is_customer {
736   return $::form->{db} eq 'customer';
737 }
738
739 sub is_orphaned {
740   my ($self) = @_;
741
742   if ( defined($self->{_is_orphaned}) ) {
743     return $self->{_is_orphaned};
744   }
745
746   my $arap      = $self->is_vendor ? 'ap' : 'ar';
747   my $num_args  = 3;
748
749   my $cv = $self->is_vendor ? 'vendor' : 'customer';
750
751   my $query =
752    'SELECT a.id
753     FROM '. $arap .' AS a
754     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
755     WHERE ct.id = ?
756
757     UNION
758
759     SELECT a.id
760     FROM oe a
761     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
762     WHERE ct.id = ?
763
764     UNION
765
766     SELECT a.id
767     FROM delivery_orders a
768     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
769     WHERE ct.id = ?';
770
771
772   if ( $self->is_vendor ) {
773     $query .=
774      ' UNION
775       SELECT 1 FROM makemodel mm WHERE mm.make = ?';
776     $num_args++;
777   }
778
779   my ($dummy) = selectrow_query($::form, $::form->get_standard_dbh(), $query, (conv_i($self->{cv}->id)) x $num_args);
780
781   return $self->{_is_orphaned} = !$dummy;
782 }
783
784 sub _copy_form_to_cvars {
785   my ($self, %params) = @_;
786
787   foreach my $cvar (@{ $params{target}->cvars_by_config }) {
788     my $value = $params{source}->{$cvar->config->name};
789     $value    = $::form->parse_amount(\%::myconfig, $value) if $cvar->config->type eq 'number';
790
791     $cvar->value($value);
792   }
793 }
794
795 sub _instantiate_args {
796   my ($self) = @_;
797
798   my $curr_employee = SL::DB::Manager::Employee->current;
799
800   if ( $::form->{cv}->{id} ) {
801     if ( $self->is_vendor() ) {
802       $self->{cv} = SL::DB::Vendor->new(id => $::form->{cv}->{id})->load();
803     } else {
804       $self->{cv} = SL::DB::Customer->new(id => $::form->{cv}->{id})->load();
805     }
806   } else {
807     $self->{cv} = $self->_new_customer_vendor_object;
808   }
809   $self->{cv}->assign_attributes(%{$::form->{cv}});
810
811   if ( $self->is_customer() && $::form->{cv}->{taxincluded_checked} eq '' ) {
812     $self->{cv}->taxincluded_checked(undef);
813   }
814
815   $self->{cv}->hourly_rate($::instance_conf->get_customer_hourly_rate) if $self->is_customer && !$self->{cv}->hourly_rate;
816
817   if ( $::form->{note}->{id} ) {
818     $self->{note} = SL::DB::Note->new(id => $::form->{note}->{id})->load();
819     $self->{note_followup} = $self->{note}->follow_up;
820     $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
821   } else {
822     $self->{note} = SL::DB::Note->new();
823     $self->{note_followup} = SL::DB::FollowUp->new();
824     $self->{note_followup_link} = SL::DB::FollowUpLink->new();
825   }
826
827   $self->{note}->assign_attributes(%{$::form->{note}});
828   $self->{note}->created_by($curr_employee->id);
829   $self->{note}->trans_module('ct');
830
831   $self->{note_followup}->assign_attributes(%{$::form->{note_followup}});
832   $self->{note_followup}->note($self->{note});
833   $self->{note_followup}->created_by($curr_employee->id);
834
835   $self->{note_followup_link}->trans_type($self->is_vendor() ? 'vendor' : 'customer');
836   $self->{note_followup_link}->trans_info($self->{cv}->name);
837
838   if ( $::form->{shipto}->{shipto_id} ) {
839     $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto}->{shipto_id})->load();
840   } else {
841     $self->{shipto} = SL::DB::Shipto->new();
842   }
843   $self->{shipto}->assign_attributes(%{$::form->{shipto}});
844   $self->{shipto}->module('CT');
845
846   if ( $::form->{contact}->{cp_id} ) {
847     $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact}->{cp_id})->load();
848   } else {
849     $self->{contact} = $self->_new_contact_object;
850   }
851   $self->{contact}->assign_attributes(%{$::form->{contact}});
852
853   $self->_copy_form_to_cvars(target => $self->{cv},      source => $::form->{cv_cvars});
854   $self->_copy_form_to_cvars(target => $self->{contact}, source => $::form->{contact_cvars});
855   $self->_copy_form_to_cvars(target => $self->{shipto},  source => $::form->{shipto_cvars});
856 }
857
858 sub _load_customer_vendor {
859   my ($self) = @_;
860
861   if ( $self->is_vendor() ) {
862     $self->{cv} = SL::DB::Vendor->new(id => $::form->{id})->load();
863   } else {
864     $self->{cv} = SL::DB::Customer->new(id => $::form->{id})->load();
865   }
866
867   if ( $::form->{note_id} ) {
868     $self->{note} = SL::DB::Note->new(id => $::form->{note_id})->load();
869     $self->{note_followup} = $self->{note}->follow_up;
870     $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
871   } else {
872     $self->{note} = SL::DB::Note->new();
873     $self->{note_followup} = SL::DB::FollowUp->new();
874     $self->{note_followup_link} = SL::DB::FollowUpLink->new();
875   }
876
877   if ( $::form->{shipto_id} ) {
878     $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto_id})->load();
879
880     if ( $self->{shipto}->trans_id != $self->{cv}->id ) {
881       die($::locale->text('Error'));
882     }
883   } else {
884     $self->{shipto} = SL::DB::Shipto->new();
885   }
886
887   if ( $::form->{contact_id} ) {
888     $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact_id})->load();
889
890     if ( $self->{contact}->cp_cv_id != $self->{cv}->id ) {
891       die($::locale->text('Error'));
892     }
893   } else {
894     $self->{contact} = $self->_new_contact_object;
895   }
896 }
897
898 sub _check_customer_vendor_all_edit {
899   my ($self) = @_;
900
901   unless ($::auth->assert('customer_vendor_all_edit', 1)) {
902     die($::locale->text("You don't have the rights to edit this customer.") . "\n")
903       if $self->{cv}->is_customer and
904          SL::DB::Manager::Employee->current->id != $self->{cv}->salesman_id;
905   };
906 };
907
908 sub _create_customer_vendor {
909   my ($self) = @_;
910
911   $self->{cv} = $self->_new_customer_vendor_object;
912   $self->{cv}->currency_id($::instance_conf->get_currency_id());
913
914   $self->{note} = SL::DB::Note->new();
915
916   $self->{note_followup} = SL::DB::FollowUp->new();
917
918   $self->{shipto} = SL::DB::Shipto->new();
919
920   $self->{contact} = $self->_new_contact_object;
921 }
922
923 sub _pre_render {
924   my ($self) = @_;
925
926   my $dbh = $::form->get_standard_dbh();
927
928   my $query;
929
930   $self->{all_business} = SL::DB::Manager::Business->get_all();
931
932   $self->{all_employees} = SL::DB::Manager::Employee->get_all(query => [ deleted => 0 ]);
933
934   $self->{all_greetings} = SL::DB::Manager::Greeting->get_all_sorted();
935   if ($self->{cv}->id && $self->{cv}->greeting && !grep {$self->{cv}->greeting eq $_->description} @{$self->{all_greetings}}) {
936     unshift @{$self->{all_greetings}}, (SL::DB::Greeting->new(description => $self->{cv}->greeting));
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;