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