847dc71dfd41951cd6b1cebec15b1e2b6c9e2539
[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 SL::JSON;
7 use SL::DBUtils;
8 use SL::Helper::Flash;
9
10 use SL::DB::Customer;
11 use SL::DB::Vendor;
12 use SL::DB::Business;
13 use SL::DB::Employee;
14 use SL::DB::Language;
15 use SL::DB::TaxZone;
16 use SL::DB::Note;
17 use SL::DB::PaymentTerm;
18 use SL::DB::Pricegroup;
19 use SL::DB::Contact;
20 use SL::DB::FollowUp;
21 use SL::DB::History;
22 use SL::DB::Currency;
23
24 # safety
25 __PACKAGE__->run_before(
26   sub {
27     $::auth->assert('customer_vendor_edit');
28   }
29 );
30
31 __PACKAGE__->run_before(
32   '_instantiate_args',
33   only => [
34     'save',
35     'save_and_ap_transaction',
36     'save_and_ar_transaction',
37     'save_and_close',
38     'save_and_invoice',
39     'save_and_order',
40     'save_and_quotation',
41     'save_and_rfq',
42     'delete_contact',
43     'delete_shipto',
44   ]
45 );
46
47 __PACKAGE__->run_before(
48   '_load_customer_vendor',
49   only => [
50     'edit',
51     'update',
52     'ajaj_get_shipto',
53     'ajaj_get_contact',
54   ]
55 );
56 __PACKAGE__->run_before(
57   '_create_customer_vendor',
58   only => [
59     'add',
60   ]
61 );
62
63 sub action_add {
64   my ($self) = @_;
65
66   $self->_pre_render();
67   $self->render(
68     'customer_vendor/form',
69     title => ($self->is_vendor() ? $::locale->text('Add Vendor') : $::locale->text('Add Customer')),
70     %{$self->{template_args}}
71   );
72 }
73
74 sub action_edit {
75   my ($self) = @_;
76
77   $self->_pre_render();
78   $self->render(
79     'customer_vendor/form',
80     title => ($self->is_vendor() ? $::locale->text('Edit Vendor') : $::locale->text('Edit Customer')),
81     %{$self->{template_args}}
82   );
83 }
84
85 sub _save {
86   my ($self) = @_;
87
88   my $db = $self->{cv}->db;
89
90   $db->do_transaction(sub {
91     my $cvs_by_nr;
92     if ( $self->is_vendor() ) {
93       if ( $self->{cv}->vendornumber ) {
94         $cvs_by_nr = SL::DB::Manager::Vendor->get_all(query => [vendornumber => $self->{cv}->vendornumber]);
95       }
96     }
97     else {
98       if ( $self->{cv}->customernumber ) {
99         $cvs_by_nr = SL::DB::Manager::Customer->get_all(query => [customernumber => $self->{cv}->customernumber]);
100       }
101     }
102
103     foreach my $entry (@{$cvs_by_nr}) {
104       if( $entry->id != $self->{cv}->id ) {
105         my $msg =
106           $self->is_vendor() ? $::locale->text('This vendor number is already in use.') : $::locale->text('This customer number is already in use.');
107
108         $::form->error($msg);
109       }
110     }
111
112     $self->{cv}->save(cascade => 1);
113
114     $self->{contact}->cp_cv_id($self->{cv}->id);
115     if( $self->{contact}->cp_name ne '' || $self->{contact}->cp_givenname ne '' ) {
116       $self->{contact}->save();
117     }
118
119     if( $self->{note}->subject ne '' && $self->{note}->body ne '' ) {
120       $self->{note}->trans_id($self->{cv}->id);
121       $self->{note}->save();
122       $self->{note_followup}->save();
123
124       $self->{note} = SL::DB::Note->new();
125       $self->{note_followup} = SL::DB::FollowUp->new();
126     }
127
128     $self->{shipto}->trans_id($self->{cv}->id);
129     if( $self->{shipto}->shiptoname ne '' ) {
130       $self->{shipto}->save();
131     }
132
133     my $snumbers = $self->is_vendor() ? 'vendornumber_'. $self->{cv}->vendornumber : 'customernumber_'. $self->{cv}->customernumber;
134     SL::DB::History->new(
135       trans_id => $self->{cv}->id,
136       snumbers => $snumbers,
137       employee_id => SL::DB::Manager::Employee->current->id,
138       addition => 'SAVED',
139     )->save();
140   }) || die($db->error);
141
142 }
143
144 sub action_save {
145   my ($self) = @_;
146
147   $self->_save();
148
149   $self->redirect_to(action => 'edit', id => $self->{cv}->id);
150 }
151
152 sub action_save_and_close {
153   my ($self) = @_;
154
155   $self->_save();
156
157   my $msg = $self->is_vendor() ? $::locale->text('Vendor saved') : $::locale->text('Customer saved');
158   $::form->redirect($msg);
159 }
160
161 sub _transaction {
162   my ($self, $script) = @_;
163
164   $::auth->assert('general_ledger         | invoice_edit         | vendor_invoice_edit | ' .
165                  ' request_quotation_edit | sales_quotation_edit | sales_order_edit    | purchase_order_edit');
166
167   $self->_save();
168
169   my $callback = $::form->escape($::form->{callback}, 1);
170   my $name = $::form->escape($self->{cv}->name, 1);
171   my $db = $self->is_vendor() ? 'vendor' : 'customer';
172
173   my $url =
174     $script .'?'.
175     'action=add&'.
176     'vc='. $db .'&'.
177     $db .'_id=' . $self->{cv}->id .'&'.
178     $db .'='. $name .'&'.
179     'type='. $::form->{type} .'&'.
180     'callback='. $callback;
181
182   print $::form->redirect_header($url);
183 }
184
185 sub action_save_and_ar_transaction {
186   my ($self) = @_;
187
188   $main::auth->assert('general_ledger');
189
190   $self->_transaction('ar.pl');
191 }
192
193 sub action_save_and_ap_transaction {
194   my ($self) = @_;
195
196   $main::auth->assert('general_ledger');
197
198   $self->_transaction('ap.pl');
199 }
200
201 sub action_save_and_invoice {
202   my ($self) = @_;
203
204   if ( $self->is_vendor() ) {
205     $::auth->assert('vendor_invoice_edit');
206   } else {
207     $::auth->assert('invoice_edit');
208   }
209
210   $::form->{type} = 'invoice';
211   $self->_transaction($self->is_vendor() ? 'ir.pl' : 'is.pl');
212 }
213
214 sub action_save_and_order {
215   my ($self) = @_;
216
217   if ( $self->is_vendor() ) {
218     $::auth->assert('purchase_order_edit');
219   } else {
220     $::auth->assert('sales_order_edit');
221   }
222
223   $::form->{type} = $self->is_vendor() ? 'purchase_order' : 'sales_order';
224   $self->_transaction('oe.pl');
225 }
226
227 sub action_save_and_rfq {
228   my ($self) = @_;
229
230   $::auth->assert('request_quotation_edit');
231
232   $::form->{type} = 'request_quotation';
233   $self->_transaction('oe.pl');
234 }
235
236 sub action_save_and_quotation {
237   my ($self) = @_;
238
239   $::auth->assert('sales_quotation_edit');
240
241   $::form->{type} = 'sales_quotation';
242   $self->_transaction('oe.pl');
243 }
244
245 sub action_delete {
246   my ($self) = @_;
247
248   my $db = $self->{cv}->db;
249
250   if( !$self->is_orphaned() ) {
251     $self->action_edit();
252   }
253   else {
254
255     $db->do_transaction(sub {
256       $self->{cv}->delete(cascade => 1);
257
258       my $snumbers = $self->is_vendor() ? 'vendornumber_'. $self->{cv}->vendornumber : 'customernumber_'. $self->{cv}->customernumber;
259       SL::DB::History->new(
260         trans_id => $self->{cv}->id,
261         snumbers => $snumbers,
262         employee_id => SL::DB::Manager::Employee->current->id,
263         addition => 'DELETED',
264       )->save();
265     }) || die($db->error);
266
267     my $msg = $self->is_vendor() ? $::locale->text('Vendor deleted!') : $::locale->text('Customer deleted!');
268     $::form->redirect($msg);
269   }
270
271 }
272
273
274 sub action_delete_contact {
275   my ($self) = @_;
276
277   my $db = $self->{contact}->db;
278
279   if ( !$self->{contact}->cp_id ) {
280     SL::Helper::Flash::flash('error', $::locale->text('No contact selected to delete'));
281   } else {
282
283     $db->do_transaction(sub {
284       if ( $self->{contact}->used ) {
285         $self->{contact}->detach();
286         $self->{contact}->save();
287         SL::Helper::Flash::flash('info', $::locale->text('Contact is in use and was flagged invalid.'));
288       } else {
289         $self->{contact}->delete(cascade => 1);
290         SL::Helper::Flash::flash('info', $::locale->text('Contact deleted.'));
291       }
292     }) || die($db->error);
293
294     $self->{contact} = SL::DB::Contact->new();
295   }
296
297   $self->action_edit();
298 }
299
300 sub action_delete_shipto {
301   my ($self) = @_;
302
303   my $db = $self->{shipto}->db;
304
305   if ( !$self->{shipto}->shipto_id ) {
306     SL::Helper::Flash::flash('error', $::locale->text('No shipto selected to delete'));
307   } else {
308
309     $db->do_transaction(sub {
310       if ( $self->{shipto}->used ) {
311         $self->{shipto}->detach();
312         $self->{shipto}->save(cascade => 1);
313         SL::Helper::Flash::flash('info', $::locale->text('Shipto is in use and was flagged invalid.'));
314       } else {
315         $self->{shipto}->delete(cascade => 1);
316         SL::Helper::Flash::flash('info', $::locale->text('Shipto deleted.'));
317       }
318     }) || die($db->error);
319
320     $self->{shipto} = SL::DB::Shipto->new();
321   }
322
323   $self->action_edit();
324 }
325
326
327 sub action_search {
328   my ($self) = @_;
329
330   my $url = 'ct.pl?action=search&db='. ($self->is_vendor() ? 'vendor' : 'customer');
331
332   if ( $::form->{callback} ) {
333     $url .= '&callback='. $::from->escape($::form->{callback});
334   }
335
336   print $::form->redirect_header($url);
337 }
338
339
340 sub action_search_contact {
341   my ($self) = @_;
342
343   my $url = 'ct.pl?action=search_contact&db=customer';
344
345   if ( $::form->{callback} ) {
346     $url .= '&callback='. $::from->escape($::form->{callback});
347   }
348
349   print $::form->redirect_header($url);
350 }
351
352
353 sub action_get_delivery {
354   my ($self) = @_;
355
356   my $dbh = $::form->get_standard_dbh();
357
358   my ($arap, $db, $qty_sign);
359   if ( $self->is_vendor() ) {
360     $arap = 'ap';
361     $db = 'vendor';
362     $qty_sign = ' * -1 AS qty';
363   }
364   else {
365     $arap = 'ar';
366     $db = 'customer';
367     $qty_sign = '';
368   }
369
370   my $where = ' WHERE 1=1 ';
371   my @values;
372
373   if ( !$self->is_vendor() && $::form->{shipto_id} && $::form->{shipto_id} ne 'all' ) {
374     $where .= "AND ${arap}.shipto_id = ?";
375     push(@values, $::form->{shipto_id});
376   }
377
378   if ( $::form->{delivery_from} ) {
379     $where .= "AND ${arap}.transdate >= ?";
380     push(@values, conv_date($::form->{delivery_from}));
381   }
382
383   if ( $::form->{delivery_to} ) {
384     $where .= "AND ${arap}.transdate <= ?";
385     push(@values, conv_date($::form->{delivery_to}));
386   }
387
388   my $query =
389     "SELECT
390        s.shiptoname,
391        i.qty ${qty_sign},
392        ${arap}.id,
393        ${arap}.transdate,
394        ${arap}.invnumber,
395        ${arap}.ordnumber,
396        i.description,
397        i.unit,
398        i.sellprice,
399        oe.id AS oe_id,
400        invoice
401      FROM ${arap}
402
403      LEFT JOIN shipto s
404       ON ". ($arap eq 'ar' ? '(ar.shipto_id = s.shipto_id) ' : '(ap.id = s.trans_id) ') ."
405
406      LEFT JOIN invoice i
407        ON ${arap}.id = i.trans_id
408
409      LEFT JOIN parts p
410        ON p.id = i.parts_id
411
412      LEFT JOIN oe
413        ON (oe.ordnumber = ${arap}.ordnumber AND NOT ${arap}.ordnumber = '')
414
415      ${where}
416      ORDER BY ${arap}.transdate DESC LIMIT 15";
417
418   $self->{delivery} = selectall_hashref_query($::form, $dbh, $query, @values);
419
420   $self->render('customer_vendor/get_delivery', { layout => 0 });
421 }
422
423 sub action_ajaj_get_shipto {
424   my ($self) = @_;
425
426   my $data = {
427     map(
428       {
429         my $name = 'shipto'. $_;
430         $name => $self->{shipto}->$name;
431       }
432       qw(_id name department_1 department_2 street zipcode city country contact phone fax email)
433     )
434   };
435
436   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
437 }
438
439 sub action_ajaj_get_contact {
440   my ($self) = @_;
441
442   my $data;
443
444   $data->{contact} = {
445     map(
446       {
447         my $name = 'cp_'. $_;
448
449         if ( $_ eq 'birthday' && $self->{contact}->$name ) {
450           $name => $self->{contact}->$name->to_lxoffice;
451         }
452         else {
453           $name => $self->{contact}->$name;
454         }
455       }
456       qw(
457         id gender abteilung title position givenname name email phone1 phone2 fax mobile1 mobile2
458         satphone satfax project street zipcode city privatphone privatemail birthday
459       )
460     )
461   };
462
463   $data->{contact_cvars} = {
464     map(
465       {
466         if ( $_->config->type eq 'number' ) {
467           $_->config->name => $::form->format_amount(\%::myconfig, $_->value, -2);
468         }
469         else {
470           $_->config->name => $_->value;
471         }
472       }
473       grep(
474         { $_->is_valid; }
475         @{$self->{contact}->cvars_by_config}
476       )
477     )
478   };
479
480   $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
481 }
482
483 sub action_ajaj_customer_autocomplete {
484   my ($self, %params) = @_;
485
486   my $limit = $::form->{limit} || 20;
487   my $type  = $::form->{type}  || {};
488   my $query = { ilike => '%'. $::form->{term} .'%' };
489
490   my @filter;
491   push(
492     @filter,
493     $::form->{column} ? ($::form->{column} => $query) : (or => [ customernumber => $query, name => $query ])
494   );
495
496   my $customers = SL::DB::Manager::Customer->get_all(query => [ @filter ], limit => $limit);
497   my $value_col = $::form->{column} || 'name';
498
499   my $data = [
500     map(
501       {
502         {
503           value => $_->can($value_col)->($_),
504           label => $_->displayable_name,
505           id    => $_->id,
506           customernumber => $_->customernumber,
507           name  => $_->name,
508         }
509       }
510       @{$customers}
511     )
512   ];
513
514   $self->render(\SL::JSON::to_json($data), { layout => 0, type => 'json' });
515 }
516
517 sub is_vendor {
518   return $::form->{db} eq 'vendor';
519 }
520
521 sub is_customer {
522   return $::form->{db} eq 'customer';
523 }
524
525 sub is_orphaned {
526   my ($self) = @_;
527
528   if ( defined($self->{_is_orphaned}) ) {
529     return $self->{_is_orphaned};
530   }
531
532   my $arap      = $self->is_vendor ? 'ap' : 'ar';
533   my $num_args  = 2;
534
535   my $cv = $self->is_vendor ? 'vendor' : 'customer';
536
537   my $query =
538    'SELECT a.id
539     FROM '. $arap .' AS a
540     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
541     WHERE ct.id = ?
542
543     UNION
544
545     SELECT a.id
546     FROM oe a
547     JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
548     WHERE ct.id = ?';
549
550
551   if ( $self->is_vendor ) {
552     $query .=
553      ' UNION
554       SELECT 1 FROM makemodel mm WHERE mm.make = ?';
555     $num_args++;
556   }
557
558   my ($dummy) = selectrow_query($::form, $::form->get_standard_dbh(), $query, (conv_i($self->{cv}->id)) x $num_args);
559
560   return $self->{_is_orphaned} = !$dummy;
561 }
562
563 sub _instantiate_args {
564   my ($self) = @_;
565
566   my $curr_employee = SL::DB::Manager::Employee->current;
567
568   if ( $::form->{cv}->{id} ) {
569     if ( $self->is_vendor() ) {
570       $self->{cv} = SL::DB::Vendor->new(id => $::form->{cv}->{id})->load();
571     }
572     else {
573       $self->{cv} = SL::DB::Customer->new(id => $::form->{cv}->{id})->load();
574     }
575   }
576   else {
577     if ( $self->is_vendor() ) {
578       $self->{cv} = SL::DB::Vendor->new();
579     }
580     else {
581       $self->{cv} = SL::DB::Customer->new();
582     }
583   }
584   $self->{cv}->assign_attributes(%{$::form->{cv}});
585
586   foreach my $cvar (@{$self->{cv}->cvars_by_config()}) {
587     my $value = $::form->{cv_cvars}->{$cvar->config->name};
588
589     if ( $cvar->config->type eq 'number' ) {
590       $value = $::form->parse_amount(\%::myconfig, $value);
591     }
592
593     $cvar->value($value);
594   }
595
596 #  foreach my $cvar_key (keys(%{$::form->{cv_cvars}})) {
597 #    my $cvar_value = $::form->{cv_cvars}->{$cvar_key};
598 #    my $cvar = $self->{cv}->cvar_by_name($cvar_key);
599 #    $cvar->value($cvar_value);
600 #  }
601
602   if ( $::form->{note}->{id} ) {
603     $self->{note} = SL::DB::Note->new(id => $::form->{note}->{id})->load();
604   }
605   else {
606     $self->{note} = SL::DB::Note->new();
607   }
608   $self->{note}->assign_attributes(%{$::form->{note}});
609   $self->{note}->created_by($curr_employee->id);
610   $self->{note}->trans_module('ct');
611   #  if ( $self->{note}->trans_id != $self->{cv}->id ) {
612   #    die($::locale->text('Error'));
613   #  }
614
615
616   $self->{note_followup} = SL::DB::FollowUp->new();
617   $self->{note_followup}->assign_attributes(%{$::form->{note_followup}});
618   $self->{note_followup}->note($self->{note});
619   $self->{note_followup}->created_by($curr_employee->id);
620
621   if ( $::form->{shipto}->{shipto_id} ) {
622     $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto}->{shipto_id})->load();
623   }
624   else {
625     $self->{shipto} = SL::DB::Shipto->new();
626   }
627   $self->{shipto}->assign_attributes(%{$::form->{shipto}});
628   $self->{shipto}->module('CT');
629 #  if ( $self->{shipto}->trans_id != $self->{cv}->id ) {
630 #    die($::locale->text('Error'));
631 #  }
632
633   if ( $::form->{contact}->{cp_id} ) {
634     $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact}->{cp_id})->load();
635   }
636   else {
637     $self->{contact} = SL::DB::Contact->new();
638   }
639   $self->{contact}->assign_attributes(%{$::form->{contact}});
640 #  if ( $self->{contact}->cp_cv_id != $self->{cv}->id ) {
641 #    die($::locale->text('Error'));
642 #  }
643
644   foreach my $cvar (@{$self->{contact}->cvars_by_config()}) {
645     my $value = $::form->{contact_cvars}->{$cvar->config->name};
646
647     if ( $cvar->config->type eq 'number' ) {
648       $value = $::form->parse_amount(\%::myconfig, $value);
649     }
650
651     $cvar->value($value);
652   }
653 }
654
655 sub _load_customer_vendor {
656   my ($self) = @_;
657
658   if ( $self->is_vendor() ) {
659     $self->{cv} = SL::DB::Vendor->new(id => $::form->{id})->load();
660   }
661   else {
662     $self->{cv} = SL::DB::Customer->new(id => $::form->{id})->load();
663   }
664
665   $self->{note} = SL::DB::Note->new();
666   $self->{note_followup} = SL::DB::FollowUp->new();
667
668   if ( $::form->{shipto_id} ) {
669     $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto_id})->load();
670
671     if ( $self->{shipto}->trans_id != $self->{cv}->id ) {
672       die($::locale->text('Error'));
673     }
674   }
675   else {
676     $self->{shipto} = SL::DB::Shipto->new();
677   }
678
679   if ( $::form->{contact_id} ) {
680     $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact_id})->load();
681
682     if ( $self->{contact}->cp_cv_id != $self->{cv}->id ) {
683       die($::locale->text('Error'));
684     }
685   }
686   else {
687     $self->{contact} = SL::DB::Contact->new();
688   }
689 }
690
691 sub _create_customer_vendor {
692   my ($self) = @_;
693
694   if ( $self->is_vendor() ) {
695     $self->{cv} = SL::DB::Vendor->new();
696   }
697   else {
698     $self->{cv} = SL::DB::Customer->new();
699   }
700
701   $self->{note} = SL::DB::Note->new();
702
703   $self->{note_followup} = SL::DB::FollowUp->new();
704
705   $self->{shipto} = SL::DB::Shipto->new();
706
707   $self->{contact} = SL::DB::Contact->new();
708 }
709
710 sub _pre_render {
711   my ($self) = @_;
712
713   my $dbh = $::form->get_standard_dbh();
714
715   my $query;
716
717   $self->{all_business} = SL::DB::Manager::Business->get_all();
718
719   $self->{all_employees} = SL::DB::Manager::Employee->get_all();
720
721   $query =
722     'SELECT DISTINCT(greeting)
723      FROM customer
724      WHERE greeting IS NOT NULL AND greeting != \'\'
725      UNION
726        SELECT DISTINCT(greeting)
727        FROM vendor
728        WHERE greeting IS NOT NULL AND greeting != \'\'
729      ORDER BY greeting';
730   $self->{all_greetings} = [
731     map(
732       { $_->{greeting}; }
733       selectall_hashref_query($::form, $dbh, $query)
734     )
735   ];
736
737   $query =
738     'SELECT DISTINCT(cp_title) AS title
739      FROM contacts
740      WHERE cp_title IS NOT NULL AND cp_title != \'\'
741      ORDER BY cp_title';
742   $self->{all_titles} = [
743     map(
744       { $_->{title}; }
745       selectall_hashref_query($::form, $dbh, $query)
746     )
747   ];
748
749   $self->{all_currencies} = SL::DB::Manager::Currency->get_all();
750
751   $self->{all_languages} = SL::DB::Manager::Language->get_all();
752
753   $self->{all_taxzones} = SL::DB::Manager::TaxZone->get_all();
754
755   #Employee:
756   #TODO: ALL_SALESMAN
757   #TODO: ALL_SALESMAN_CUSTOMERS
758
759   $self->{all_payment_terms} = SL::DB::Manager::PaymentTerm->get_all();
760
761   $self->{all_pricegroups} = SL::DB::Manager::Pricegroup->get_all();
762
763   $query =
764     'SELECT DISTINCT(cp_abteilung) AS department
765      FROM contacts
766      WHERE cp_abteilung IS NOT NULL AND cp_abteilung != \'\'
767      ORDER BY cp_abteilung';
768   $self->{all_departments} = [
769     map(
770       { $_->{department}; }
771       selectall_hashref_query($::form, $dbh, $query)
772     )
773   ];
774
775   $self->{contacts} = $self->{cv}->contacts;
776   $self->{contacts} ||= [];
777
778   $self->{shiptos} = $self->{cv}->shipto;
779   $self->{shiptos} ||= [];
780
781   $self->{template_args} = {};
782
783   $::request->{layout}->add_javascripts('autocomplete_customer.js');
784 }
785
786 1;