a8ea84e36b3827808e334e42d9a132a4feebb11d
[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(cp_greeting) | .
199     qq|FROM contacts | .
200     qq|WHERE cp_greeting ~ '[a-zA-Z]' | .
201     qq|ORDER BY cp_greeting|;
202   $form->{GREETINGS} = [ selectall_array_query($form, $dbh, $query) ];
203
204   $query =
205     qq|SELECT DISTINCT(greeting) | .
206     qq|FROM customer | .
207     qq|WHERE greeting ~ '[a-zA-Z]' | .
208     qq|UNION | .
209     qq|SELECT DISTINCT(greeting) | .
210     qq|FROM vendor | .
211     qq|WHERE greeting ~ '[a-zA-Z]' | .
212     qq|ORDER BY greeting|;
213   my %tmp;
214   map({ $tmp{$_} = 1; } selectall_array_query($form, $dbh, $query));
215   $form->{COMPANY_GREETINGS} = [ sort(keys(%tmp)) ];
216
217   $query =
218     qq|SELECT DISTINCT(cp_title) | .
219     qq|FROM contacts | .
220     qq|WHERE cp_title ~ '[a-zA-Z]'|;
221   $form->{TITLES} = [ selectall_array_query($form, $dbh, $query) ];
222
223   $query =
224     qq|SELECT DISTINCT(cp_abteilung) | .
225     qq|FROM contacts | .
226     qq|WHERE cp_abteilung ~ '[a-zA-Z]'|;
227   $form->{DEPARTMENT} = [ selectall_array_query($form, $dbh, $query) ];
228
229   $dbh->disconnect();
230   $main::lxdebug->leave_sub();
231 }
232
233 sub save_customer {
234   $main::lxdebug->enter_sub();
235
236   my ( $self, $myconfig, $form ) = @_;
237
238   # set pricegroup to default
239   $form->{klass} = 0 unless ($form->{klass});
240
241   # connect to database
242   my $dbh = $form->dbconnect_noauto($myconfig);
243
244   map( {
245     $form->{"cp_${_}"} = $form->{"selected_cp_${_}"}
246     if ( $form->{"selected_cp_${_}"} );
247        } qw(title greeting abteilung) );
248   $form->{"greeting"} = $form->{"selected_company_greeting"}
249   if ( $form->{"selected_company_greeting"} );
250
251   # assign value discount, terms, creditlimit
252   $form->{discount} = $form->parse_amount( $myconfig, $form->{discount} );
253   $form->{discount} /= 100;
254   $form->{creditlimit} = $form->parse_amount( $myconfig, $form->{creditlimit} );
255
256   my ( $query, $sth, $f_id );
257
258   if ( $form->{id} ) {
259     $query = qq|SELECT id FROM customer WHERE customernumber = ?|;
260     ($f_id) = selectrow_query($form, $dbh, $query, $form->{customernumber});
261
262     if (($f_id ne $form->{id}) && ($f_id ne "")) {
263       $main::lxdebug->leave_sub();
264       return 3;
265     }
266
267   } else {
268     if (!$form->{customernumber} && $form->{business}) {
269       $form->{customernumber} =
270         $form->update_business($myconfig, $form->{business}, $dbh);
271     }
272     if (!$form->{customernumber}) {
273       $form->{customernumber} =
274         $form->update_defaults($myconfig, "customernumber", $dbh);
275     }
276
277     $query  = qq|SELECT c.id FROM customer c WHERE c.customernumber = ?|;
278     ($f_id) = selectrow_query($form, $dbh, $query, $form->{customernumber});
279     if ($f_id ne "") {
280       $main::lxdebug->leave_sub();
281       return 3;
282     }
283
284     $query = qq|SELECT nextval('id')|;
285     ($form->{id}) = selectrow_query($form, $dbh, $query);
286
287     $query = qq|INSERT INTO customer (id, name) VALUES (?, '')|;
288     do_query($form, $dbh, $query, $form->{id});
289   }
290
291   $query = qq|UPDATE customer SET | .
292     qq|customernumber = ?, | .
293     qq|name = ?, | .
294     qq|greeting = ?, | .
295     qq|department_1 = ?, | .
296     qq|department_2 = ?, | .
297     qq|street = ?, | .
298     qq|zipcode = ?, | .
299     qq|city = ?, | .
300     qq|country = ?, | .
301     qq|homepage = ?, | .
302     qq|contact = ?, | .
303     qq|phone = ?, | .
304     qq|fax = ?, | .
305     qq|email = ?, | .
306     qq|cc = ?, | .
307     qq|bcc = ?, | .
308     qq|notes = ?, | .
309     qq|discount = ?, | .
310     qq|creditlimit = ?, | .
311     qq|terms = ?, | .
312     qq|business_id = ?, | .
313     qq|taxnumber = ?, | .
314     qq|language = ?, | .
315     qq|account_number = ?, | .
316     qq|bank_code = ?, | .
317     qq|bank = ?, | .
318     qq|iban = ?, | .
319     qq|bic = ?, | .
320     qq|obsolete = ?, | .
321     qq|direct_debit = ?, | .
322     qq|ustid = ?, | .
323     qq|username = ?, | .
324     qq|salesman_id = ?, | .
325     qq|language_id = ?, | .
326     qq|payment_id = ?, | .
327     qq|taxzone_id = ?, | .
328     qq|user_password = ?, | .
329     qq|c_vendor_id = ?, | .
330     qq|klass = ? | .
331     qq|WHERE id = ?|;
332   my @values = (
333     $form->{customernumber},
334     $form->{name},
335     $form->{greeting},
336     $form->{department_1},
337     $form->{department_2},
338     $form->{street},
339     $form->{zipcode},
340     $form->{city},
341     $form->{country},
342     $form->{homepage},
343     $form->{contact},
344     $form->{phone},
345     $form->{fax},
346     $form->{email},
347     $form->{cc},
348     $form->{bcc},
349     $form->{notes},
350     $form->{discount},
351     $form->{creditlimit},
352     conv_i($form->{terms}),
353     conv_i($form->{business}),
354     $form->{taxnumber},
355     $form->{language},
356     $form->{account_number},
357     $form->{bank_code},
358     $form->{bank},
359     $form->{iban},
360     $form->{bic},
361     $form->{obsolete} ? 't' : 'f',
362     $form->{direct_debit} ? 't' : 'f',
363     $form->{ustid},
364     $form->{username},
365     conv_i($form->{salesman_id}),
366     conv_i($form->{language_id}),
367     conv_i($form->{payment_id}),
368     conv_i($form->{taxzone_id}, 0),
369     $form->{user_password},
370     $form->{c_vendor_id},
371     conv_i($form->{klass}),
372     $form->{id}
373     );
374   do_query( $form, $dbh, $query, @values );
375
376   $query = undef;
377   if ( $form->{cp_id} ) {
378     $query = qq|UPDATE contacts SET | .
379       qq|cp_greeting = ?, | .
380       qq|cp_title = ?,  | .
381       qq|cp_givenname = ?, | .
382       qq|cp_name = ?, | .
383       qq|cp_email = ?, | .
384       qq|cp_phone1 = ?, | .
385       qq|cp_phone2 = ?, | .
386       qq|cp_abteilung = ?, | .
387       qq|cp_fax = ?, | .
388       qq|cp_mobile1 = ?, | .
389       qq|cp_mobile2 = ?, | .
390       qq|cp_satphone = ?, | .
391       qq|cp_satfax = ?, | .
392       qq|cp_project = ?, | .
393       qq|cp_privatphone = ?, | .
394       qq|cp_privatemail = ?, | .
395       qq|cp_birthday = ? | .
396       qq|WHERE cp_id = ?|;
397     @values = (
398       $form->{cp_greeting},
399       $form->{cp_title},
400       $form->{cp_givenname},
401       $form->{cp_name},
402       $form->{cp_email},
403       $form->{cp_phone1},
404       $form->{cp_phone2},
405       $form->{cp_abteilung},
406       $form->{cp_fax},
407       $form->{cp_mobile1},
408       $form->{cp_mobile2},
409       $form->{cp_satphone},
410       $form->{cp_satfax},
411       $form->{cp_project},
412       $form->{cp_privatphone},
413       $form->{cp_privatemail},
414       $form->{cp_birthday},
415       $form->{cp_id}
416       );
417   } elsif ( $form->{cp_name} || $form->{cp_givenname} ) {
418     $query =
419       qq|INSERT INTO contacts ( cp_cv_id, cp_greeting, cp_title, cp_givenname,  | .
420       qq|  cp_name, cp_email, cp_phone1, cp_phone2, cp_abteilung, cp_fax, cp_mobile1, | .
421       qq|  cp_mobile2, cp_satphone, cp_satfax, cp_project, cp_privatphone, cp_privatemail, | .
422       qq|  cp_birthday) | .
423       qq|VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
424     @values = (
425       $form->{id},
426       $form->{cp_greeting},
427       $form->{cp_title},
428       $form->{cp_givenname},
429       $form->{cp_name},
430       $form->{cp_email},
431       $form->{cp_phone1},
432       $form->{cp_phone2},
433       $form->{cp_abteilung},
434       $form->{cp_fax},
435       $form->{cp_mobile1},
436       $form->{cp_mobile2},
437       $form->{cp_satphone},
438       $form->{cp_satfax},
439       $form->{cp_project},
440       $form->{cp_privatphone},
441       $form->{cp_privatemail},
442       $form->{cp_birthday}
443       );
444   }
445   do_query( $form, $dbh, $query, @values ) if ($query);
446
447   # add shipto
448   $form->add_shipto( $dbh, $form->{id}, "CT" );
449
450   $self->_save_note('dbh' => $dbh);
451   $self->_delete_selected_notes('dbh' => $dbh);
452
453   CVar->save_custom_variables('dbh'       => $dbh,
454                               'module'    => 'CT',
455                               'trans_id'  => $form->{id},
456                               'variables' => $form);
457
458   $rc = $dbh->commit();
459   $dbh->disconnect();
460
461   $main::lxdebug->leave_sub();
462   return $rc;
463 }
464
465 sub save_vendor {
466   $main::lxdebug->enter_sub();
467
468   my ( $self, $myconfig, $form ) = @_;
469
470   $form->{taxzone_id} *= 1;
471   # connect to database
472   my $dbh = $form->dbconnect_noauto($myconfig);
473
474   map( {
475     $form->{"cp_${_}"} = $form->{"selected_cp_${_}"}
476     if ( $form->{"selected_cp_${_}"} );
477        } qw(title greeting abteilung) );
478   $form->{"greeting"} = $form->{"selected_company_greeting"}
479   if ( $form->{"selected_company_greeting"} );
480
481   $form->{discount} = $form->parse_amount( $myconfig, $form->{discount} );
482   $form->{discount} /= 100;
483   $form->{creditlimit} = $form->parse_amount( $myconfig, $form->{creditlimit} );
484
485   my $query;
486
487   if (!$form->{id}) {
488     $query = qq|SELECT nextval('id')|;
489     ($form->{id}) = selectrow_query($form, $dbh, $query);
490
491     $query = qq|INSERT INTO vendor (id, name) VALUES (?, '')|;
492     do_query($form, $dbh, $query, $form->{id});
493
494     if ( !$form->{vendornumber} ) {
495       $form->{vendornumber} = $form->update_defaults( $myconfig, "vendornumber", $dbh );
496     }
497   }
498
499   $query =
500     qq|UPDATE vendor SET | .
501     qq|  vendornumber = ?, | .
502     qq|  name = ?, | .
503     qq|  greeting = ?, | .
504     qq|  department_1 = ?, | .
505     qq|  department_2 = ?, | .
506     qq|  street = ?, | .
507     qq|  zipcode = ?, | .
508     qq|  city = ?, | .
509     qq|  country = ?, | .
510     qq|  homepage = ?, | .
511     qq|  contact = ?, | .
512     qq|  phone = ?, | .
513     qq|  fax = ?, | .
514     qq|  email = ?, | .
515     qq|  cc = ?, | .
516     qq|  bcc = ?, | .
517     qq|  notes = ?, | .
518     qq|  terms = ?, | .
519     qq|  discount = ?, | .
520     qq|  creditlimit = ?, | .
521     qq|  business_id = ?, | .
522     qq|  taxnumber = ?, | .
523     qq|  language = ?, | .
524     qq|  account_number = ?, | .
525     qq|  bank_code = ?, | .
526     qq|  bank = ?, | .
527     qq|  iban = ?, | .
528     qq|  bic = ?, | .
529     qq|  obsolete = ?, | .
530     qq|  direct_debit = ?, | .
531     qq|  ustid = ?, | .
532     qq|  payment_id = ?, | .
533     qq|  taxzone_id = ?, | .
534     qq|  language_id = ?, | .
535     qq|  username = ?, | .
536     qq|  user_password = ?, | .
537     qq|  v_customer_id = ? | .
538     qq|WHERE id = ?|;
539   @values = (
540     $form->{vendornumber},
541     $form->{name},
542     $form->{greeting},
543     $form->{department_1},
544     $form->{department_2},
545     $form->{street},
546     $form->{zipcode},
547     $form->{city},
548     $form->{country},
549     $form->{homepage},
550     $form->{contact},
551     $form->{phone},
552     $form->{fax},
553     $form->{email},
554     $form->{cc},
555     $form->{bcc},
556     $form->{notes},
557     conv_i($form->{terms}),
558     $form->{discount},
559     $form->{creditlimit},
560     conv_i($form->{business}),
561     $form->{taxnumber},
562     $form->{language},
563     $form->{account_number},
564     $form->{bank_code},
565     $form->{bank},
566     $form->{iban},
567     $form->{bic},
568     $form->{obsolete} ? 't' : 'f',
569     $form->{direct_debit} ? 't' : 'f',
570     $form->{ustid},
571     conv_i($form->{payment_id}),
572     conv_i($form->{taxzone_id}, 0),
573     conv_i( $form->{language_id}),
574     $form->{username},
575     $form->{user_password},
576     $form->{v_customer_id},
577     $form->{id}
578     );
579   do_query($form, $dbh, $query, @values);
580
581   $query = undef;
582   if ( $form->{cp_id} ) {
583     $query = qq|UPDATE contacts SET | .
584       qq|cp_greeting = ?, | .
585       qq|cp_title = ?,  | .
586       qq|cp_givenname = ?, | .
587       qq|cp_name = ?, | .
588       qq|cp_email = ?, | .
589       qq|cp_phone1 = ?, | .
590       qq|cp_phone2 = ?, | .
591       qq|cp_abteilung = ?, | .
592       qq|cp_fax = ?, | .
593       qq|cp_mobile1 = ?, | .
594       qq|cp_mobile2 = ?, | .
595       qq|cp_satphone = ?, | .
596       qq|cp_satfax = ?, | .
597       qq|cp_project = ?, | .
598       qq|cp_privatphone = ?, | .
599       qq|cp_privatemail = ?, | .
600       qq|cp_birthday = ? | .
601       qq|WHERE cp_id = ?|;
602     @values = (
603       $form->{cp_greeting},
604       $form->{cp_title},
605       $form->{cp_givenname},
606       $form->{cp_name},
607       $form->{cp_email},
608       $form->{cp_phone1},
609       $form->{cp_phone2},
610       $form->{cp_abteilung},
611       $form->{cp_fax},
612       $form->{cp_mobile1},
613       $form->{cp_mobile2},
614       $form->{cp_satphone},
615       $form->{cp_satfax},
616       $form->{cp_project},
617       $form->{cp_privatphone},
618       $form->{cp_privatemail},
619       $form->{cp_birthday},
620       $form->{cp_id}
621       );
622   } elsif ( $form->{cp_name} || $form->{cp_givenname} ) {
623     $query =
624       qq|INSERT INTO contacts ( cp_cv_id, cp_greeting, cp_title, cp_givenname,  | .
625       qq|  cp_name, cp_email, cp_phone1, cp_phone2, cp_abteilung, cp_fax, cp_mobile1, | .
626       qq|  cp_mobile2, cp_satphone, cp_satfax, cp_project, cp_privatphone, cp_privatemail, | .
627       qq|  cp_birthday) | .
628       qq|VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
629     @values = (
630       $form->{id},
631       $form->{cp_greeting},
632       $form->{cp_title},
633       $form->{cp_givenname},
634       $form->{cp_name},
635       $form->{cp_email},
636       $form->{cp_phone1},
637       $form->{cp_phone2},
638       $form->{cp_abteilung},
639       $form->{cp_fax},
640       $form->{cp_mobile1},
641       $form->{cp_mobile2},
642       $form->{cp_satphone},
643       $form->{cp_satfax},
644       $form->{cp_project},
645       $form->{cp_privatphone},
646       $form->{cp_privatemail},
647       $form->{cp_birthday}
648       );
649   }
650   do_query($form, $dbh, $query, @values) if ($query);
651
652   # add shipto
653   $form->add_shipto( $dbh, $form->{id}, "CT" );
654
655   $self->_save_note('dbh' => $dbh);
656   $self->_delete_selected_notes('dbh' => $dbh);
657
658   CVar->save_custom_variables('dbh'       => $dbh,
659                               'module'    => 'CT',
660                               'trans_id'  => $form->{id},
661                               'variables' => $form);
662
663   $rc = $dbh->commit();
664   $dbh->disconnect();
665
666   $main::lxdebug->leave_sub();
667   return $rc;
668 }
669
670 sub delete {
671   $main::lxdebug->enter_sub();
672
673   my ( $self, $myconfig, $form ) = @_;
674   # connect to database
675   my $dbh = $form->dbconnect($myconfig);
676
677   # delete vendor
678   my $cv = $form->{db} eq "customer" ? "customer" : "vendor";
679   my $query = qq|DELETE FROM $cv WHERE id = ?|;
680   do_query($form, $dbh, $query, $form->{id});
681
682   $dbh->disconnect;
683
684   $main::lxdebug->leave_sub();
685 }
686
687 sub search {
688   $main::lxdebug->enter_sub();
689
690   my ( $self, $myconfig, $form ) = @_;
691
692   # connect to database
693   my $dbh = $form->dbconnect($myconfig);
694
695   my $cv = $form->{db} eq "customer" ? "customer" : "vendor";
696
697   my $where = "1 = 1";
698   my @values;
699
700   my %allowed_sort_columns =
701     map({ $_, 1 } qw(id customernumber vendornumber name contact phone fax email
702                      taxnumber business invnumber ordnumber quonumber));
703   $sortorder    = $form->{sort} && $allowed_sort_columns{$form->{sort}} ? $form->{sort} : "name";
704   $form->{sort} = $sortorder;
705   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
706
707   if ($sortorder ne 'id' && 1 >= scalar grep { $form->{$_} } qw(l_ordnumber l_quonumber l_invnumber)) {
708     $sortorder  = "lower($sortorder) ${sortdir}";
709   } else {
710     $sortorder .= " ${sortdir}";
711   }
712
713   if ($form->{"${cv}number"}) {
714     $where .= " AND ct.${cv}number ILIKE ?";
715     push(@values, '%' . $form->{"${cv}number"} . '%');
716   }
717
718   foreach my $key (qw(name contact email)) {
719     if ($form->{$key}) {
720       $where .= " AND ct.$key ILIKE ?";
721       push(@values, '%' . $form->{$key} . '%');
722     }
723   }
724
725   if ($form->{cp_name}) {
726     $where .= " AND ct.id IN (SELECT cp_cv_id FROM contacts WHERE lower(cp_name) LIKE lower(?))";
727     push @values, '%' . $form->{cp_name} . '%';
728   }
729
730   if ($form->{addr_city}) {
731     $where .= " AND ((lower(ct.city) LIKE lower(?))
732                      OR
733                      (ct.id IN (
734                         SELECT trans_id
735                         FROM shipto
736                         WHERE (module = 'CT')
737                           AND (lower(shiptocity) LIKE lower(?))
738                       ))
739                      )";
740     push @values, ('%' . $form->{addr_city} . '%') x 2;
741   }
742
743   if ( $form->{status} eq 'orphaned' ) {
744     $where .=
745       qq| AND ct.id NOT IN | .
746       qq|   (SELECT o.${cv}_id FROM oe o, $cv cv WHERE cv.id = o.${cv}_id)|;
747     if ($cv eq 'customer') {
748       $where .=
749         qq| AND ct.id NOT IN | .
750         qq| (SELECT a.customer_id FROM ar a, customer cv | .
751         qq|  WHERE cv.id = a.customer_id)|;
752     }
753     if ($cv eq 'vendor') {
754       $where .=
755         qq| AND ct.id NOT IN | .
756         qq| (SELECT a.vendor_id FROM ap a, vendor cv | .
757         qq|  WHERE cv.id = a.vendor_id)|;
758     }
759     $form->{l_invnumber} = $form->{l_ordnumber} = $form->{l_quonumber} = "";
760   }
761
762   if ($form->{obsolete} eq "Y") {
763     $where .= qq| AND obsolete|;
764   } elsif ($form->{obsolete} eq "N") {
765     $where .= qq| AND NOT obsolete|;
766   }
767
768   if ($form->{business_id}) {
769     $where .= qq| AND (business_id = ?)|;
770     push(@values, conv_i($form->{business_id}));
771   }
772
773   my ($cvar_where, @cvar_values) = CVar->build_filter_query('module'         => 'CT',
774                                                             'trans_id_field' => 'ct.id',
775                                                             'filter'         => $form);
776
777   if ($cvar_where) {
778     $where .= qq| AND ($cvar_where)|;
779     push @values, @cvar_values;
780   }
781
782   if ($form->{addr_street}) {
783     $where .= qq| AND (street ILIKE ?)|;
784     push @values, '%' . $form->{addr_street} . '%';
785   }
786
787   if ($form->{addr_zipcode}) {
788     $where .= qq| AND (zipcode ILIKE ?)|;
789     push @values, $form->{addr_zipcode} . '%';
790   }
791
792   my $query =
793     qq|SELECT ct.*, b.description AS business | .
794     qq|FROM $cv ct | .
795     qq|LEFT JOIN business b ON (ct.business_id = b.id) | .
796     qq|WHERE $where|;
797
798   my @saved_values = @values;
799   # redo for invoices, orders and quotations
800   if ($form->{l_invnumber} || $form->{l_ordnumber} || $form->{l_quonumber}) {
801     my ($ar, $union, $module);
802     $query = "";
803
804     if ($form->{l_invnumber}) {
805       my $ar = $cv eq 'customer' ? 'ar' : 'ap';
806       my $module = $ar eq 'ar' ? 'is' : 'ir';
807
808       $query =
809         qq|SELECT ct.*, b.description AS business, | .
810         qq|  a.invnumber, a.ordnumber, a.quonumber, a.id AS invid, | .
811         qq|  '$module' AS module, 'invoice' AS formtype, | .
812         qq|  (a.amount = a.paid) AS closed | .
813         qq|FROM $cv ct | .
814         qq|JOIN $ar a ON (a.${cv}_id = ct.id) | .
815         qq|LEFT JOIN business b ON (ct.business_id = b.id) | .
816         qq|WHERE $where AND (a.invoice = '1')|;
817
818       $union = qq|UNION|;
819     }
820
821     if ( $form->{l_ordnumber} ) {
822       if ($union eq "UNION") {
823         push(@values, @saved_values);
824       }
825       $query .=
826         qq| $union | .
827         qq|SELECT ct.*, b.description AS business,| .
828         qq|  ' ' AS invnumber, o.ordnumber, o.quonumber, o.id AS invid, | .
829         qq|  'oe' AS module, 'order' AS formtype, o.closed | .
830         qq|FROM $cv ct | .
831         qq|JOIN oe o ON (o.${cv}_id = ct.id) | .
832         qq|LEFT JOIN business b ON (ct.business_id = b.id) | .
833         qq|WHERE $where AND (o.quotation = '0')|;
834
835       $union = qq|UNION|;
836     }
837
838     if ( $form->{l_quonumber} ) {
839       if ($union eq "UNION") {
840         push(@values, @saved_values);
841       }
842       $query .=
843         qq| $union | .
844         qq|SELECT ct.*, b.description AS business, | .
845         qq|  ' ' AS invnumber, o.ordnumber, o.quonumber, o.id AS invid, | .
846         qq|  'oe' AS module, 'quotation' AS formtype, o.closed | .
847         qq|FROM $cv ct | .
848         qq|JOIN oe o ON (o.${cv}_id = ct.id) | .
849         qq|LEFT JOIN business b ON (ct.business_id = b.id) | .
850         qq|WHERE $where AND (o.quotation = '1')|;
851     }
852   }
853
854   $query .= qq| ORDER BY $sortorder|;
855
856   $form->{CT} = selectall_hashref_query($form, $dbh, $query, @values);
857
858   $main::lxdebug->leave_sub();
859 }
860
861 sub get_contact {
862   $main::lxdebug->enter_sub();
863
864   my ( $self, $myconfig, $form ) = @_;
865   my $dbh   = $form->dbconnect($myconfig);
866   my $query =
867     qq|SELECT * FROM contacts c | .
868     qq|WHERE cp_id = ? ORDER BY cp_id limit 1|;
869   my $sth = prepare_execute_query($form, $dbh, $query, $form->{cp_id});
870   my $ref = $sth->fetchrow_hashref(NAME_lc);
871
872   map { $form->{$_} = $ref->{$_} } keys %$ref;
873
874   $query = qq|SELECT COUNT(cp_id) AS used FROM (
875     SELECT cp_id FROM oe UNION
876     SELECT cp_id FROM ar UNION
877     SELECT cp_id FROM ap UNION
878     SELECT cp_id FROM delivery_orders
879   ) AS cpid WHERE cp_id = ? OR ? = 0|;
880   ($form->{cp_used}) = selectfirst_array_query($form, $dbh, $query, ($form->{cp_id})x2);
881
882   $sth->finish;
883   $dbh->disconnect;
884
885   $main::lxdebug->leave_sub();
886 }
887
888 sub get_shipto {
889   $main::lxdebug->enter_sub();
890
891   my ( $self, $myconfig, $form ) = @_;
892   my $dbh   = $form->dbconnect($myconfig);
893   my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
894   my $sth = prepare_execute_query($form, $dbh, $query, $form->{shipto_id});
895
896   my $ref = $sth->fetchrow_hashref(NAME_lc);
897
898   map { $form->{$_} = $ref->{$_} } keys %$ref;
899
900   $query = qq|SELECT COUNT(shipto_id) AS used FROM (
901     SELECT shipto_id FROM oe UNION
902     SELECT shipto_id FROM ar UNION
903     SELECT shipto_id FROM delivery_orders
904   ) AS stid WHERE shipto_id = ? OR ? = 0|;
905   ($form->{shiptoused}) = selectfirst_array_query($form, $dbh, $query, ($form->{shipto_id})x2);
906
907   $sth->finish;
908   $dbh->disconnect;
909
910   $main::lxdebug->leave_sub();
911 }
912
913 sub get_delivery {
914   $main::lxdebug->enter_sub();
915
916   my ( $self, $myconfig, $form ) = @_;
917   my $dbh = $form->dbconnect($myconfig);
918
919   my $arap = $form->{db} eq "vendor" ? "ap" : "ar";
920   my $db = $form->{db} eq "customer" ? "customer" : "vendor";
921   my $qty_sign = $form->{db} eq 'vendor' ? ' * -1 AS qty' : '';
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 $qty_sign, | .
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;