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