Bei Kunden die Validität nicht speichern.
[kivitendo-erp.git] / SL / CT.pm
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 2001
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #  Contributors:
16 #
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
21 #
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
30 #
31 # backend code for customers and vendors
32 #
33 # CHANGE LOG:
34 #   DS. 2000-07-04  Created
35 #
36 #======================================================================
37
38 package CT;
39
40 use Data::Dumper;
41
42 use SL::Common;
43 use SL::CVar;
44 use SL::DBUtils;
45 use SL::FU;
46 use SL::Notes;
47
48 sub get_tuple {
49   $main::lxdebug->enter_sub();
50
51   my ( $self, $myconfig, $form ) = @_;
52
53   my $cv = $form->{db} eq "customer" ? "customer" : "vendor";
54
55   my $dbh   = $form->dbconnect($myconfig);
56   my $query =
57     qq|SELECT ct.*, b.id AS business, cp.* | .
58     qq|FROM $cv ct | .
59     qq|LEFT JOIN business b ON (ct.business_id = b.id) | .
60     qq|LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id) | .
61     qq|WHERE (ct.id = ?) | .
62     qq|ORDER BY cp.cp_id LIMIT 1|;
63   my $sth = prepare_execute_query($form, $dbh, $query, $form->{id});
64
65   my $ref = $sth->fetchrow_hashref(NAME_lc);
66
67   map { $form->{$_} = $ref->{$_} } keys %$ref;
68
69   $sth->finish;
70   if ( $form->{salesman_id} ) {
71     my $query =
72       qq|SELECT ct.name AS salesman | .
73       qq|FROM $cv ct | .
74       qq|WHERE ct.id = ?|;
75     ($form->{salesman}) =
76       selectrow_query($form, $dbh, $query, $form->{salesman_id});
77   }
78
79   my ($employee_id) = selectrow_query($form, $dbh, qq|SELECT id FROM employee WHERE login = ?|, $form->{login});
80   $query =
81     qq|SELECT n.*, n.itime::DATE AS created_on,
82          e.name AS created_by_name, e.login AS created_by_login
83        FROM notes n
84        LEFT JOIN employee e ON (n.created_by = e.id)
85        WHERE (n.trans_id = ?) AND (n.trans_module = 'ct')|;
86   $form->{NOTES} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
87
88   $query =
89     qq|SELECT fu.follow_up_date, fu.done AS follow_up_done, e.name AS created_for_name, e.name AS created_for_login
90        FROM follow_ups fu
91        LEFT JOIN employee e ON (fu.created_for_user = e.id)
92        WHERE (fu.note_id = ?)
93          AND NOT COALESCE(fu.done, FALSE)
94          AND (   (fu.created_by = ?)
95               OR (fu.created_by IN (SELECT DISTINCT what FROM follow_up_access WHERE who = ?)))|;
96   $sth = prepare_query($form, $dbh, $query);
97
98   foreach my $note (@{ $form->{NOTES} }) {
99     do_statement($form, $sth, $query, conv_i($note->{id}), conv_i($note->{created_by}), conv_i($employee_id));
100     $ref = $sth->fetchrow_hashref();
101
102     map { $note->{$_} = $ref->{$_} } keys %{ $ref } if ($ref);
103   }
104
105   $sth->finish();
106
107   if ($form->{edit_note_id}) {
108     $query =
109       qq|SELECT n.id AS NOTE_id, n.subject AS NOTE_subject, n.body AS NOTE_body,
110            fu.id AS FU_id, fu.follow_up_date AS FU_date, fu.done AS FU_done, fu.created_for_user AS FU_created_for_user
111          FROM notes n
112          LEFT JOIN follow_ups fu ON ((n.id = fu.note_id) AND NOT COALESCE(fu.done, FALSE))
113          WHERE n.id = ?|;
114     $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{edit_note_id}));
115
116     if ($ref) {
117       foreach my $key (keys %{ $ref }) {
118         my $new_key       =  $key;
119         $new_key          =~ s/^([^_]+)/\U\1\E/;
120         $form->{$new_key} =  $ref->{$key};
121       }
122     }
123   }
124
125   # check if it is orphaned
126   my $arap      = ( $form->{db} eq 'customer' ) ? "ar" : "ap";
127   my $num_args  = 2;
128   my $makemodel = '';
129   if ($form->{db} eq 'vendor') {
130     $makemodel = qq| UNION SELECT 1 FROM makemodel mm WHERE mm.make = ?|;
131     $num_args++;
132   }
133
134   $query =
135     qq|SELECT a.id | .
136     qq|FROM $arap a | .
137     qq|JOIN $cv ct ON (a.${cv}_id = ct.id) | .
138     qq|WHERE ct.id = ? | .
139     qq|UNION | .
140     qq|SELECT a.id | .
141     qq|FROM oe a | .
142     qq|JOIN $cv ct ON (a.${cv}_id = ct.id) | .
143     qq|WHERE ct.id = ?|
144     . $makemodel;
145   my ($dummy) = selectrow_query($form, $dbh, $query, (conv_i($form->{id})) x $num_args);
146
147   $form->{status} = "orphaned" unless ($dummy);
148
149   $dbh->disconnect;
150
151   $main::lxdebug->leave_sub();
152 }
153
154 sub populate_drop_down_boxes {
155   $main::lxdebug->enter_sub();
156
157   my ($self, $myconfig, $form, $provided_dbh) = @_;
158
159   my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect($myconfig);
160
161   # get business types
162   $query = qq|SELECT id, description FROM business ORDER BY id|;
163   $form->{all_business} = selectall_hashref_query($form, $dbh, $query);
164
165   # get shipto address
166   $query =
167     qq|SELECT shipto_id, shiptoname, shiptodepartment_1, shiptostreet, shiptocity
168        FROM shipto
169        WHERE (trans_id = ?) AND (module = 'CT')|;
170   $form->{SHIPTO} = selectall_hashref_query($form, $dbh, $query, $form->{id});
171
172   # get contacts
173   $query  = qq|SELECT cp_id, cp_name, cp_givenname FROM contacts WHERE cp_cv_id = ? ORDER BY cp_name|;
174   $form->{CONTACTS} = selectall_hashref_query($form, $dbh, $query, $form->{id});
175
176   # get languages
177   $query = qq|SELECT id, description FROM language ORDER BY id|;
178   $form->{languages} = selectall_hashref_query($form, $dbh, $query);
179
180   # get payment terms
181   $query = qq|SELECT id, description FROM payment_terms ORDER BY sortkey|;
182   $form->{payment_terms} = selectall_hashref_query($form, $dbh, $query);
183
184   $dbh->disconnect() unless ($provided_dbh);
185
186   $main::lxdebug->leave_sub();
187 }
188
189 sub query_titles_and_greetings {
190   $main::lxdebug->enter_sub();
191
192   my ( $self, $myconfig, $form ) = @_;
193   my ( %tmp,  $ref );
194
195   my $dbh = $form->dbconnect($myconfig);
196
197   $query =
198     qq|SELECT DISTINCT(greeting) | .
199     qq|FROM customer | .
200     qq|WHERE greeting ~ '[a-zA-Z]' | .
201     qq|UNION | .
202     qq|SELECT DISTINCT(greeting) | .
203     qq|FROM vendor | .
204     qq|WHERE greeting ~ '[a-zA-Z]' | .
205     qq|ORDER BY greeting|;
206   my %tmp;
207   map({ $tmp{$_} = 1; } selectall_array_query($form, $dbh, $query));
208   $form->{COMPANY_GREETINGS} = [ sort(keys(%tmp)) ];
209
210   $query =
211     qq|SELECT DISTINCT(cp_title) | .
212     qq|FROM contacts | .
213     qq|WHERE cp_title ~ '[a-zA-Z]'|;
214   $form->{TITLES} = [ selectall_array_query($form, $dbh, $query) ];
215
216   $query =
217     qq|SELECT DISTINCT(cp_abteilung) | .
218     qq|FROM contacts | .
219     qq|WHERE cp_abteilung ~ '[a-zA-Z]'|;
220   $form->{DEPARTMENT} = [ selectall_array_query($form, $dbh, $query) ];
221
222   $dbh->disconnect();
223   $main::lxdebug->leave_sub();
224 }
225
226 sub save_customer {
227   $main::lxdebug->enter_sub();
228
229   my ( $self, $myconfig, $form ) = @_;
230
231   # set pricegroup to default
232   $form->{klass} = 0 unless ($form->{klass});
233
234   # connect to database
235   my $dbh = $form->dbconnect_noauto($myconfig);
236
237   map( {
238     $form->{"cp_${_}"} = $form->{"selected_cp_${_}"}
239     if ( $form->{"selected_cp_${_}"} );
240        } qw(title greeting abteilung) );
241   $form->{"greeting"} = $form->{"selected_company_greeting"}
242   if ( $form->{"selected_company_greeting"} );
243
244   # assign value discount, terms, creditlimit
245   $form->{discount} = $form->parse_amount( $myconfig, $form->{discount} );
246   $form->{discount} /= 100;
247   $form->{creditlimit} = $form->parse_amount( $myconfig, $form->{creditlimit} );
248
249   my ( $query, $sth, $f_id );
250
251   if ( $form->{id} ) {
252     $query = qq|SELECT id FROM customer WHERE customernumber = ?|;
253     ($f_id) = selectrow_query($form, $dbh, $query, $form->{customernumber});
254
255     if (($f_id ne $form->{id}) && ($f_id ne "")) {
256       $main::lxdebug->leave_sub();
257       return 3;
258     }
259
260   } else {
261     if (!$form->{customernumber} && $form->{business}) {
262       $form->{customernumber} =
263         $form->update_business($myconfig, $form->{business}, $dbh);
264     }
265     if (!$form->{customernumber}) {
266       $form->{customernumber} =
267         $form->update_defaults($myconfig, "customernumber", $dbh);
268     }
269
270     $query  = qq|SELECT c.id FROM customer c WHERE c.customernumber = ?|;
271     ($f_id) = selectrow_query($form, $dbh, $query, $form->{customernumber});
272     if ($f_id ne "") {
273       $main::lxdebug->leave_sub();
274       return 3;
275     }
276
277     $query = qq|SELECT nextval('id')|;
278     ($form->{id}) = selectrow_query($form, $dbh, $query);
279
280     $query = qq|INSERT INTO customer (id, name) VALUES (?, '')|;
281     do_query($form, $dbh, $query, $form->{id});
282   }
283
284   $query = qq|UPDATE customer SET | .
285     qq|customernumber = ?, | .
286     qq|name = ?, | .
287     qq|greeting = ?, | .
288     qq|department_1 = ?, | .
289     qq|department_2 = ?, | .
290     qq|street = ?, | .
291     qq|zipcode = ?, | .
292     qq|city = ?, | .
293     qq|country = ?, | .
294     qq|homepage = ?, | .
295     qq|contact = ?, | .
296     qq|phone = ?, | .
297     qq|fax = ?, | .
298     qq|email = ?, | .
299     qq|cc = ?, | .
300     qq|bcc = ?, | .
301     qq|notes = ?, | .
302     qq|discount = ?, | .
303     qq|creditlimit = ?, | .
304     qq|terms = ?, | .
305     qq|business_id = ?, | .
306     qq|taxnumber = ?, | .
307     qq|language = ?, | .
308     qq|account_number = ?, | .
309     qq|bank_code = ?, | .
310     qq|bank = ?, | .
311     qq|iban = ?, | .
312     qq|bic = ?, | .
313     qq|obsolete = ?, | .
314     qq|direct_debit = ?, | .
315     qq|ustid = ?, | .
316     qq|username = ?, | .
317     qq|salesman_id = ?, | .
318     qq|language_id = ?, | .
319     qq|payment_id = ?, | .
320     qq|taxzone_id = ?, | .
321     qq|user_password = ?, | .
322     qq|c_vendor_id = ?, | .
323     qq|klass = ? | .
324     qq|WHERE id = ?|;
325   my @values = (
326     $form->{customernumber},
327     $form->{name},
328     $form->{greeting},
329     $form->{department_1},
330     $form->{department_2},
331     $form->{street},
332     $form->{zipcode},
333     $form->{city},
334     $form->{country},
335     $form->{homepage},
336     $form->{contact},
337     $form->{phone},
338     $form->{fax},
339     $form->{email},
340     $form->{cc},
341     $form->{bcc},
342     $form->{notes},
343     $form->{discount},
344     $form->{creditlimit},
345     conv_i($form->{terms}),
346     conv_i($form->{business}),
347     $form->{taxnumber},
348     $form->{language},
349     $form->{account_number},
350     $form->{bank_code},
351     $form->{bank},
352     $form->{iban},
353     $form->{bic},
354     $form->{obsolete} ? 't' : 'f',
355     $form->{direct_debit} ? 't' : 'f',
356     $form->{ustid},
357     $form->{username},
358     conv_i($form->{salesman_id}),
359     conv_i($form->{language_id}),
360     conv_i($form->{payment_id}),
361     conv_i($form->{taxzone_id}, 0),
362     $form->{user_password},
363     $form->{c_vendor_id},
364     conv_i($form->{klass}),
365     $form->{id}
366     );
367   do_query( $form, $dbh, $query, @values );
368
369   $query = undef;
370   if ( $form->{cp_id} ) {
371     $query = qq|UPDATE contacts SET | .
372       qq|cp_title = ?,  | .
373       qq|cp_givenname = ?, | .
374       qq|cp_name = ?, | .
375       qq|cp_email = ?, | .
376       qq|cp_phone1 = ?, | .
377       qq|cp_phone2 = ?, | .
378       qq|cp_abteilung = ?, | .
379       qq|cp_fax = ?, | .
380       qq|cp_mobile1 = ?, | .
381       qq|cp_mobile2 = ?, | .
382       qq|cp_satphone = ?, | .
383       qq|cp_satfax = ?, | .
384       qq|cp_project = ?, | .
385       qq|cp_privatphone = ?, | .
386       qq|cp_privatemail = ?, | .
387       qq|cp_birthday = ?, | .
388       qq|cp_gender = ? | .
389       qq|WHERE cp_id = ?|;
390     @values = (
391       $form->{cp_title},
392       $form->{cp_givenname},
393       $form->{cp_name},
394       $form->{cp_email},
395       $form->{cp_phone1},
396       $form->{cp_phone2},
397       $form->{cp_abteilung},
398       $form->{cp_fax},
399       $form->{cp_mobile1},
400       $form->{cp_mobile2},
401       $form->{cp_satphone},
402       $form->{cp_satfax},
403       $form->{cp_project},
404       $form->{cp_privatphone},
405       $form->{cp_privatemail},
406       $form->{cp_birthday},
407       $form->{cp_gender} eq 'f' ? 'f' : 'm',
408       $form->{cp_id}
409       );
410   } elsif ( $form->{cp_name} || $form->{cp_givenname} ) {
411     $query =
412       qq|INSERT INTO contacts ( cp_cv_id, cp_title, cp_givenname,  | .
413       qq|  cp_name, cp_email, cp_phone1, cp_phone2, cp_abteilung, cp_fax, cp_mobile1, | .
414       qq|  cp_mobile2, cp_satphone, cp_satfax, cp_project, cp_privatphone, cp_privatemail, | .
415       qq|  cp_birthday, cp_gender) | .
416       qq|VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
417     @values = (
418       $form->{id},
419       $form->{cp_title},
420       $form->{cp_givenname},
421       $form->{cp_name},
422       $form->{cp_email},
423       $form->{cp_phone1},
424       $form->{cp_phone2},
425       $form->{cp_abteilung},
426       $form->{cp_fax},
427       $form->{cp_mobile1},
428       $form->{cp_mobile2},
429       $form->{cp_satphone},
430       $form->{cp_satfax},
431       $form->{cp_project},
432       $form->{cp_privatphone},
433       $form->{cp_privatemail},
434       $form->{cp_birthday},
435       $form->{cp_gender} eq 'f' ? 'f' : 'm',
436       );
437   }
438   do_query( $form, $dbh, $query, @values ) if ($query);
439
440   # add shipto
441   $form->add_shipto( $dbh, $form->{id}, "CT" );
442
443   $self->_save_note('dbh' => $dbh);
444   $self->_delete_selected_notes('dbh' => $dbh);
445
446   CVar->save_custom_variables('dbh'       => $dbh,
447                               'module'    => 'CT',
448                               'trans_id'  => $form->{id},
449                               'variables' => $form,
450                               'always_valid' => 1);
451
452   $rc = $dbh->commit();
453   $dbh->disconnect();
454
455   $main::lxdebug->leave_sub();
456   return $rc;
457 }
458
459 sub save_vendor {
460   $main::lxdebug->enter_sub();
461
462   my ( $self, $myconfig, $form ) = @_;
463
464   $form->{taxzone_id} *= 1;
465   # connect to database
466   my $dbh = $form->dbconnect_noauto($myconfig);
467
468   map( {
469     $form->{"cp_${_}"} = $form->{"selected_cp_${_}"}
470     if ( $form->{"selected_cp_${_}"} );
471        } qw(title greeting abteilung) );
472   $form->{"greeting"} = $form->{"selected_company_greeting"}
473   if ( $form->{"selected_company_greeting"} );
474
475   $form->{discount} = $form->parse_amount( $myconfig, $form->{discount} );
476   $form->{discount} /= 100;
477   $form->{creditlimit} = $form->parse_amount( $myconfig, $form->{creditlimit} );
478
479   my $query;
480
481   if (!$form->{id}) {
482     $query = qq|SELECT nextval('id')|;
483     ($form->{id}) = selectrow_query($form, $dbh, $query);
484
485     $query = qq|INSERT INTO vendor (id, name) VALUES (?, '')|;
486     do_query($form, $dbh, $query, $form->{id});
487
488     if ( !$form->{vendornumber} ) {
489       $form->{vendornumber} = $form->update_defaults( $myconfig, "vendornumber", $dbh );
490     }
491   }
492
493   $query =
494     qq|UPDATE vendor SET | .
495     qq|  vendornumber = ?, | .
496     qq|  name = ?, | .
497     qq|  greeting = ?, | .
498     qq|  department_1 = ?, | .
499     qq|  department_2 = ?, | .
500     qq|  street = ?, | .
501     qq|  zipcode = ?, | .
502     qq|  city = ?, | .
503     qq|  country = ?, | .
504     qq|  homepage = ?, | .
505     qq|  contact = ?, | .
506     qq|  phone = ?, | .
507     qq|  fax = ?, | .
508     qq|  email = ?, | .
509     qq|  cc = ?, | .
510     qq|  bcc = ?, | .
511     qq|  notes = ?, | .
512     qq|  terms = ?, | .
513     qq|  discount = ?, | .
514     qq|  creditlimit = ?, | .
515     qq|  business_id = ?, | .
516     qq|  taxnumber = ?, | .
517     qq|  language = ?, | .
518     qq|  account_number = ?, | .
519     qq|  bank_code = ?, | .
520     qq|  bank = ?, | .
521     qq|  iban = ?, | .
522     qq|  bic = ?, | .
523     qq|  obsolete = ?, | .
524     qq|  direct_debit = ?, | .
525     qq|  ustid = ?, | .
526     qq|  payment_id = ?, | .
527     qq|  taxzone_id = ?, | .
528     qq|  language_id = ?, | .
529     qq|  username = ?, | .
530     qq|  user_password = ?, | .
531     qq|  v_customer_id = ? | .
532     qq|WHERE id = ?|;
533   @values = (
534     $form->{vendornumber},
535     $form->{name},
536     $form->{greeting},
537     $form->{department_1},
538     $form->{department_2},
539     $form->{street},
540     $form->{zipcode},
541     $form->{city},
542     $form->{country},
543     $form->{homepage},
544     $form->{contact},
545     $form->{phone},
546     $form->{fax},
547     $form->{email},
548     $form->{cc},
549     $form->{bcc},
550     $form->{notes},
551     conv_i($form->{terms}),
552     $form->{discount},
553     $form->{creditlimit},
554     conv_i($form->{business}),
555     $form->{taxnumber},
556     $form->{language},
557     $form->{account_number},
558     $form->{bank_code},
559     $form->{bank},
560     $form->{iban},
561     $form->{bic},
562     $form->{obsolete} ? 't' : 'f',
563     $form->{direct_debit} ? 't' : 'f',
564     $form->{ustid},
565     conv_i($form->{payment_id}),
566     conv_i($form->{taxzone_id}, 0),
567     conv_i( $form->{language_id}),
568     $form->{username},
569     $form->{user_password},
570     $form->{v_customer_id},
571     $form->{id}
572     );
573   do_query($form, $dbh, $query, @values);
574
575   $query = undef;
576   if ( $form->{cp_id} ) {
577     $query = qq|UPDATE contacts SET | .
578       qq|cp_title = ?,  | .
579       qq|cp_givenname = ?, | .
580       qq|cp_name = ?, | .
581       qq|cp_email = ?, | .
582       qq|cp_phone1 = ?, | .
583       qq|cp_phone2 = ?, | .
584       qq|cp_abteilung = ?, | .
585       qq|cp_fax = ?, | .
586       qq|cp_mobile1 = ?, | .
587       qq|cp_mobile2 = ?, | .
588       qq|cp_satphone = ?, | .
589       qq|cp_satfax = ?, | .
590       qq|cp_project = ?, | .
591       qq|cp_privatphone = ?, | .
592       qq|cp_privatemail = ?, | .
593       qq|cp_birthday = ?, | .
594       qq|cp_gender = ? | .
595       qq|WHERE cp_id = ?|;
596     @values = (
597       $form->{cp_title},
598       $form->{cp_givenname},
599       $form->{cp_name},
600       $form->{cp_email},
601       $form->{cp_phone1},
602       $form->{cp_phone2},
603       $form->{cp_abteilung},
604       $form->{cp_fax},
605       $form->{cp_mobile1},
606       $form->{cp_mobile2},
607       $form->{cp_satphone},
608       $form->{cp_satfax},
609       $form->{cp_project},
610       $form->{cp_privatphone},
611       $form->{cp_privatemail},
612       $form->{cp_birthday},
613       $form->{cp_gender} eq 'f' ? 'f' : 'm',
614       $form->{cp_id}
615       );
616   } elsif ( $form->{cp_name} || $form->{cp_givenname} ) {
617     $query =
618       qq|INSERT INTO contacts ( cp_cv_id, cp_title, cp_givenname,  | .
619       qq|  cp_name, cp_email, cp_phone1, cp_phone2, cp_abteilung, cp_fax, cp_mobile1, | .
620       qq|  cp_mobile2, cp_satphone, cp_satfax, cp_project, cp_privatphone, cp_privatemail, | .
621       qq|  cp_birthday, cp_gender) | .
622       qq|VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
623     @values = (
624       $form->{id},
625       $form->{cp_title},
626       $form->{cp_givenname},
627       $form->{cp_name},
628       $form->{cp_email},
629       $form->{cp_phone1},
630       $form->{cp_phone2},
631       $form->{cp_abteilung},
632       $form->{cp_fax},
633       $form->{cp_mobile1},
634       $form->{cp_mobile2},
635       $form->{cp_satphone},
636       $form->{cp_satfax},
637       $form->{cp_project},
638       $form->{cp_privatphone},
639       $form->{cp_privatemail},
640       $form->{cp_birthday},
641       $form->{cp_gender}
642       );
643   }
644   do_query($form, $dbh, $query, @values) if ($query);
645
646   # add shipto
647   $form->add_shipto( $dbh, $form->{id}, "CT" );
648
649   $self->_save_note('dbh' => $dbh);
650   $self->_delete_selected_notes('dbh' => $dbh);
651
652   CVar->save_custom_variables('dbh'       => $dbh,
653                               'module'    => 'CT',
654                               'trans_id'  => $form->{id},
655                               'variables' => $form,
656                               'always_valid' => 1);
657
658   $rc = $dbh->commit();
659   $dbh->disconnect();
660
661   $main::lxdebug->leave_sub();
662   return $rc;
663 }
664
665 sub delete {
666   $main::lxdebug->enter_sub();
667
668   my ( $self, $myconfig, $form ) = @_;
669   # connect to database
670   my $dbh = $form->dbconnect($myconfig);
671
672   # delete vendor
673   my $cv = $form->{db} eq "customer" ? "customer" : "vendor";
674   my $query = qq|DELETE FROM $cv WHERE id = ?|;
675   do_query($form, $dbh, $query, $form->{id});
676
677   $dbh->disconnect;
678
679   $main::lxdebug->leave_sub();
680 }
681
682 sub search {
683   $main::lxdebug->enter_sub();
684
685   my ( $self, $myconfig, $form ) = @_;
686
687   # connect to database
688   my $dbh = $form->dbconnect($myconfig);
689
690   my $cv = $form->{db} eq "customer" ? "customer" : "vendor";
691
692   my $where = "1 = 1";
693   my @values;
694
695   my %allowed_sort_columns =
696     map({ $_, 1 } qw(id customernumber vendornumber name contact phone fax email
697                      taxnumber business invnumber ordnumber quonumber));
698   $sortorder    = $form->{sort} && $allowed_sort_columns{$form->{sort}} ? $form->{sort} : "name";
699   $form->{sort} = $sortorder;
700   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
701
702   if ($sortorder ne 'id' && 1 >= scalar grep { $form->{$_} } qw(l_ordnumber l_quonumber l_invnumber)) {
703     $sortorder  = "lower($sortorder) ${sortdir}";
704   } else {
705     $sortorder .= " ${sortdir}";
706   }
707
708   if ($form->{"${cv}number"}) {
709     $where .= " AND ct.${cv}number ILIKE ?";
710     push(@values, '%' . $form->{"${cv}number"} . '%');
711   }
712
713   foreach my $key (qw(name contact email)) {
714     if ($form->{$key}) {
715       $where .= " AND ct.$key ILIKE ?";
716       push(@values, '%' . $form->{$key} . '%');
717     }
718   }
719
720   if ($form->{cp_name}) {
721     $where .= " AND ct.id IN (SELECT cp_cv_id FROM contacts WHERE lower(cp_name) LIKE lower(?))";
722     push @values, '%' . $form->{cp_name} . '%';
723   }
724
725   if ($form->{addr_city}) {
726     $where .= " AND ((lower(ct.city) LIKE lower(?))
727                      OR
728                      (ct.id IN (
729                         SELECT trans_id
730                         FROM shipto
731                         WHERE (module = 'CT')
732                           AND (lower(shiptocity) LIKE lower(?))
733                       ))
734                      )";
735     push @values, ('%' . $form->{addr_city} . '%') x 2;
736   }
737
738   if ( $form->{status} eq 'orphaned' ) {
739     $where .=
740       qq| AND ct.id NOT IN | .
741       qq|   (SELECT o.${cv}_id FROM oe o, $cv cv WHERE cv.id = o.${cv}_id)|;
742     if ($cv eq 'customer') {
743       $where .=
744         qq| AND ct.id NOT IN | .
745         qq| (SELECT a.customer_id FROM ar a, customer cv | .
746         qq|  WHERE cv.id = a.customer_id)|;
747     }
748     if ($cv eq 'vendor') {
749       $where .=
750         qq| AND ct.id NOT IN | .
751         qq| (SELECT a.vendor_id FROM ap a, vendor cv | .
752         qq|  WHERE cv.id = a.vendor_id)|;
753     }
754     $form->{l_invnumber} = $form->{l_ordnumber} = $form->{l_quonumber} = "";
755   }
756
757   if ($form->{obsolete} eq "Y") {
758     $where .= qq| AND obsolete|;
759   } elsif ($form->{obsolete} eq "N") {
760     $where .= qq| AND NOT obsolete|;
761   }
762
763   if ($form->{business_id}) {
764     $where .= qq| AND (business_id = ?)|;
765     push(@values, conv_i($form->{business_id}));
766   }
767
768   my ($cvar_where, @cvar_values) = CVar->build_filter_query('module'         => 'CT',
769                                                             'trans_id_field' => 'ct.id',
770                                                             'filter'         => $form);
771
772   if ($cvar_where) {
773     $where .= qq| AND ($cvar_where)|;
774     push @values, @cvar_values;
775   }
776
777   if ($form->{addr_street}) {
778     $where .= qq| AND (street ILIKE ?)|;
779     push @values, '%' . $form->{addr_street} . '%';
780   }
781
782   if ($form->{addr_zipcode}) {
783     $where .= qq| AND (zipcode ILIKE ?)|;
784     push @values, $form->{addr_zipcode} . '%';
785   }
786
787   my $query =
788     qq|SELECT ct.*, b.description AS business | .
789     qq|FROM $cv ct | .
790     qq|LEFT JOIN business b ON (ct.business_id = b.id) | .
791     qq|WHERE $where|;
792
793   my @saved_values = @values;
794   # redo for invoices, orders and quotations
795   if ($form->{l_invnumber} || $form->{l_ordnumber} || $form->{l_quonumber}) {
796     my ($ar, $union, $module);
797     $query = "";
798
799     if ($form->{l_invnumber}) {
800       my $ar = $cv eq 'customer' ? 'ar' : 'ap';
801       my $module = $ar eq 'ar' ? 'is' : 'ir';
802
803       $query =
804         qq|SELECT ct.*, b.description AS business, | .
805         qq|  a.invnumber, a.ordnumber, a.quonumber, a.id AS invid, | .
806         qq|  '$module' AS module, 'invoice' AS formtype, | .
807         qq|  (a.amount = a.paid) AS closed | .
808         qq|FROM $cv ct | .
809         qq|JOIN $ar a ON (a.${cv}_id = ct.id) | .
810         qq|LEFT JOIN business b ON (ct.business_id = b.id) | .
811         qq|WHERE $where AND (a.invoice = '1')|;
812
813       $union = qq|UNION|;
814     }
815
816     if ( $form->{l_ordnumber} ) {
817       if ($union eq "UNION") {
818         push(@values, @saved_values);
819       }
820       $query .=
821         qq| $union | .
822         qq|SELECT ct.*, b.description AS business,| .
823         qq|  ' ' AS invnumber, o.ordnumber, o.quonumber, o.id AS invid, | .
824         qq|  'oe' AS module, 'order' AS formtype, o.closed | .
825         qq|FROM $cv ct | .
826         qq|JOIN oe o ON (o.${cv}_id = ct.id) | .
827         qq|LEFT JOIN business b ON (ct.business_id = b.id) | .
828         qq|WHERE $where AND (o.quotation = '0')|;
829
830       $union = qq|UNION|;
831     }
832
833     if ( $form->{l_quonumber} ) {
834       if ($union eq "UNION") {
835         push(@values, @saved_values);
836       }
837       $query .=
838         qq| $union | .
839         qq|SELECT ct.*, b.description AS business, | .
840         qq|  ' ' AS invnumber, o.ordnumber, o.quonumber, o.id AS invid, | .
841         qq|  'oe' AS module, 'quotation' AS formtype, o.closed | .
842         qq|FROM $cv ct | .
843         qq|JOIN oe o ON (o.${cv}_id = ct.id) | .
844         qq|LEFT JOIN business b ON (ct.business_id = b.id) | .
845         qq|WHERE $where AND (o.quotation = '1')|;
846     }
847   }
848
849   $query .= qq| ORDER BY $sortorder|;
850
851   $form->{CT} = selectall_hashref_query($form, $dbh, $query, @values);
852
853   $main::lxdebug->leave_sub();
854 }
855
856 sub get_contact {
857   $main::lxdebug->enter_sub();
858
859   my ( $self, $myconfig, $form ) = @_;
860   my $dbh   = $form->dbconnect($myconfig);
861   my $query =
862     qq|SELECT * FROM contacts c | .
863     qq|WHERE cp_id = ? ORDER BY cp_id limit 1|;
864   my $sth = prepare_execute_query($form, $dbh, $query, $form->{cp_id});
865   my $ref = $sth->fetchrow_hashref(NAME_lc);
866
867   map { $form->{$_} = $ref->{$_} } keys %$ref;
868
869   $query = qq|SELECT COUNT(cp_id) AS used FROM (
870     SELECT cp_id FROM oe UNION
871     SELECT cp_id FROM ar UNION
872     SELECT cp_id FROM ap UNION
873     SELECT cp_id FROM delivery_orders
874   ) AS cpid WHERE cp_id = ? OR ? = 0|;
875   ($form->{cp_used}) = selectfirst_array_query($form, $dbh, $query, ($form->{cp_id})x2);
876
877   $sth->finish;
878   $dbh->disconnect;
879
880   $main::lxdebug->leave_sub();
881 }
882
883 sub get_shipto {
884   $main::lxdebug->enter_sub();
885
886   my ( $self, $myconfig, $form ) = @_;
887   my $dbh   = $form->dbconnect($myconfig);
888   my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
889   my $sth = prepare_execute_query($form, $dbh, $query, $form->{shipto_id});
890
891   my $ref = $sth->fetchrow_hashref(NAME_lc);
892
893   map { $form->{$_} = $ref->{$_} } keys %$ref;
894
895   $query = qq|SELECT COUNT(shipto_id) AS used FROM (
896     SELECT shipto_id FROM oe UNION
897     SELECT shipto_id FROM ar UNION
898     SELECT shipto_id FROM delivery_orders
899   ) AS stid WHERE shipto_id = ? OR ? = 0|;
900   ($form->{shiptoused}) = selectfirst_array_query($form, $dbh, $query, ($form->{shipto_id})x2);
901
902   $sth->finish;
903   $dbh->disconnect;
904
905   $main::lxdebug->leave_sub();
906 }
907
908 sub get_delivery {
909   $main::lxdebug->enter_sub();
910
911   my ( $self, $myconfig, $form ) = @_;
912   my $dbh = $form->dbconnect($myconfig);
913
914   my $arap = $form->{db} eq "vendor" ? "ap" : "ar";
915   my $db = $form->{db} eq "customer" ? "customer" : "vendor";
916   my $qty_sign = $form->{db} eq 'vendor' ? ' * -1 AS qty' : '';
917
918   my $where = " WHERE 1=1 ";
919   my @values;
920
921   if ($form->{shipto_id} && ($arap eq "ar")) {
922     $where .= "AND ${arap}.shipto_id = ?";
923     push(@values, $form->{shipto_id});
924   } else {
925     $where .= "AND ${arap}.${db}_id = ?";
926     push(@values, $form->{id});
927   }
928
929   if ($form->{from}) {
930     $where .= "AND ${arap}.transdate >= ?";
931     push(@values, conv_date($form->{from}));
932   }
933   if ($form->{to}) {
934     $where .= "AND ${arap}.transdate <= ?";
935     push(@values, conv_date($form->{to}));
936   }
937   my $query =
938     qq|SELECT s.shiptoname, i.qty $qty_sign, | .
939     qq|  ${arap}.id, ${arap}.transdate, ${arap}.invnumber, ${arap}.ordnumber, | .
940     qq|  i.description, i.unit, i.sellprice, | .
941     qq|  oe.id AS oe_id | .
942     qq|FROM $arap | .
943     qq|LEFT JOIN shipto s ON | .
944     ($arap eq "ar"
945      ? qq|(ar.shipto_id = s.shipto_id) |
946      : qq|(ap.id = s.trans_id) |) .
947     qq|LEFT JOIN invoice i ON (${arap}.id = i.trans_id) | .
948     qq|LEFT join parts p ON (p.id = i.parts_id) | .
949     qq|LEFT JOIN oe ON (oe.ordnumber = ${arap}.ordnumber AND NOT ${arap}.ordnumber = '') | .
950     $where .
951     qq|ORDER BY ${arap}.transdate DESC LIMIT 15|;
952
953   $form->{DELIVERY} = selectall_hashref_query($form, $dbh, $query, @values);
954
955   $dbh->disconnect;
956
957   $main::lxdebug->leave_sub();
958 }
959
960 sub _save_note {
961   $main::lxdebug->enter_sub();
962
963   my $self   = shift;
964   my %params = @_;
965
966   my $form   = $main::form;
967
968   Common::check_params(\%params, 'dbh');
969
970   if (!$form->{NOTE_subject}) {
971     $main::lxdebug->leave_sub();
972     return;
973   }
974
975   my $dbh = $params{dbh};
976
977   my %follow_up;
978   my %note = (
979     'id'           => $form->{NOTE_id},
980     'subject'      => $form->{NOTE_subject},
981     'body'         => $form->{NOTE_body},
982     'trans_id'     => $form->{id},
983     'trans_module' => 'ct',
984   );
985
986   $note{id} = Notes->save(%note);
987
988   if ($form->{FU_date}) {
989     %follow_up = (
990       'id'               => $form->{FU_id},
991       'note_id'          => $note{id},
992       'follow_up_date'   => $form->{FU_date},
993       'created_for_user' => $form->{FU_created_for_user},
994       'done'             => $form->{FU_done} ? 1 : 0,
995       'subject'          => $form->{NOTE_subject},
996       'body'             => $form->{NOTE_body},
997       'LINKS'            => [
998         {
999           'trans_id'     => $form->{id},
1000           'trans_type'   => $form->{db} eq 'customer' ? 'customer' : 'vendor',
1001           'trans_info'   => $form->{name},
1002         },
1003       ],
1004     );
1005
1006     $follow_up{id} = FU->save(%follow_up);
1007
1008   } elsif ($form->{FU_id}) {
1009     do_query($form, $dbh, qq|DELETE FROM follow_up_links WHERE follow_up_id = ?|, conv_i($form->{FU_id}));
1010     do_query($form, $dbh, qq|DELETE FROM follow_ups      WHERE id = ?|,           conv_i($form->{FU_id}));
1011   }
1012
1013   delete @{$form}{grep { /^NOTE_|^FU_/ } keys %{ $form }};
1014
1015   $main::lxdebug->leave_sub();
1016 }
1017
1018 sub _delete_selected_notes {
1019   $main::lxdebug->enter_sub();
1020
1021   my $self   = shift;
1022   my %params = @_;
1023
1024   Common::check_params(\%params, 'dbh');
1025
1026   my $form = $main::form;
1027   my $dbh  = $params{dbh};
1028
1029   foreach my $i (1 .. $form->{NOTES_rowcount}) {
1030     next unless ($form->{"NOTE_delete_$i"} && $form->{"NOTE_id_$i"});
1031
1032     Notes->delete('dbh' => $params{dbh},
1033                   'id'  => $form->{"NOTE_id_$i"});
1034   }
1035
1036   $main::lxdebug->leave_sub();
1037 }
1038
1039 sub delete_shipto {
1040   $main::lxdebug->enter_sub();
1041
1042   my $self      = shift;
1043   my $shipto_id = shift;
1044
1045   my $form      = $main::form;
1046   my %myconfig  = %main::myconfig;
1047   my $dbh       = $form->get_standard_dbh(\%myconfig);
1048
1049   do_query($form, $dbh, qq|UPDATE shipto SET trans_id = NULL WHERE shipto_id = ?|, $shipto_id);
1050
1051   $dbh->commit();
1052
1053   $main::lxdebug->leave_sub();
1054 }
1055
1056 sub delete_shipto {
1057   $main::lxdebug->enter_sub();
1058
1059   my $self      = shift;
1060   my $shipto_id = shift;
1061
1062   my $form      = $main::form;
1063   my %myconfig  = %main::myconfig;
1064   my $dbh       = $form->get_standard_dbh(\%myconfig);
1065
1066   do_query($form, $dbh, qq|UPDATE contacts SET cp_cv_id = NULL WHERE cp_id = ?|, $shipto_id);
1067
1068   $dbh->commit();
1069
1070   $main::lxdebug->leave_sub();
1071 }
1072
1073 sub get_bank_info {
1074   $main::lxdebug->enter_sub();
1075
1076   my $self     = shift;
1077   my %params   = @_;
1078
1079   Common::check_params(\%params, qw(vc id));
1080
1081   my $myconfig = \%main::myconfig;
1082   my $form     = $main::form;
1083
1084   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1085
1086   my $table        = $params{vc} eq 'customer' ? 'customer' : 'vendor';
1087   my @ids          = ref $params{id} eq 'ARRAY' ? @{ $params{id} } : ($params{id});
1088   my $placeholders = ('?') x scalar @ids;
1089   my $query        = qq|SELECT id, name, account_number, bank, bank_code, iban, bic
1090                         FROM ${table}
1091                         WHERE id IN (${placeholders})|;
1092
1093   my $result       = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1094
1095   if (ref $params{id} eq 'ARRAY') {
1096     $result = { map { $_->{id} => $_ } @{ $result } };
1097   } else {
1098     $result = $result->[0] || { 'id' => $params{id} };
1099   }
1100
1101   $main::lxdebug->leave_sub();
1102
1103   return $result;
1104 }
1105
1106 1;