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