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