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