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