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