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