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