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