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