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