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