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