Ansprechpartner: cp_greeting durch cp_gender ersetzt
[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 #  edit: cp_greeting wurde entfernt, wird durch cp_gender ersetzt
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|cp_gender = ? | .
398       qq|WHERE cp_id = ?|;
399     @values = (
400       $form->{cp_greeting},
401       $form->{cp_title},
402       $form->{cp_givenname},
403       $form->{cp_name},
404       $form->{cp_email},
405       $form->{cp_phone1},
406       $form->{cp_phone2},
407       $form->{cp_abteilung},
408       $form->{cp_fax},
409       $form->{cp_mobile1},
410       $form->{cp_mobile2},
411       $form->{cp_satphone},
412       $form->{cp_satfax},
413       $form->{cp_project},
414       $form->{cp_privatphone},
415       $form->{cp_privatemail},
416       $form->{cp_birthday},
417       $form->{cp_gender} eq 'f' ? 'f' : 'm',
418       $form->{cp_id}
419       );
420   } elsif ( $form->{cp_name} || $form->{cp_givenname} ) {
421     $query =
422       qq|INSERT INTO contacts ( cp_cv_id, cp_greeting, cp_title, cp_givenname,  | .
423       qq|  cp_name, cp_email, cp_phone1, cp_phone2, cp_abteilung, cp_fax, cp_mobile1, | .
424       qq|  cp_mobile2, cp_satphone, cp_satfax, cp_project, cp_privatphone, cp_privatemail, | .
425       qq|  cp_birthday, cp_gender) | .
426       qq|VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
427     @values = (
428       $form->{id},
429       $form->{cp_greeting},
430       $form->{cp_title},
431       $form->{cp_givenname},
432       $form->{cp_name},
433       $form->{cp_email},
434       $form->{cp_phone1},
435       $form->{cp_phone2},
436       $form->{cp_abteilung},
437       $form->{cp_fax},
438       $form->{cp_mobile1},
439       $form->{cp_mobile2},
440       $form->{cp_satphone},
441       $form->{cp_satfax},
442       $form->{cp_project},
443       $form->{cp_privatphone},
444       $form->{cp_privatemail},
445       $form->{cp_birthday},
446       $form->{cp_gender} eq 'f' ? 'f' : 'm',
447       );
448   }
449   do_query( $form, $dbh, $query, @values ) if ($query);
450
451   # add shipto
452   $form->add_shipto( $dbh, $form->{id}, "CT" );
453
454   $self->_save_note('dbh' => $dbh);
455   $self->_delete_selected_notes('dbh' => $dbh);
456
457   CVar->save_custom_variables('dbh'       => $dbh,
458                               'module'    => 'CT',
459                               'trans_id'  => $form->{id},
460                               'variables' => $form);
461
462   $rc = $dbh->commit();
463   $dbh->disconnect();
464
465   $main::lxdebug->leave_sub();
466   return $rc;
467 }
468
469 sub save_vendor {
470   $main::lxdebug->enter_sub();
471
472   my ( $self, $myconfig, $form ) = @_;
473
474   $form->{taxzone_id} *= 1;
475   # connect to database
476   my $dbh = $form->dbconnect_noauto($myconfig);
477
478   map( {
479     $form->{"cp_${_}"} = $form->{"selected_cp_${_}"}
480     if ( $form->{"selected_cp_${_}"} );
481        } qw(title greeting abteilung) );
482   $form->{"greeting"} = $form->{"selected_company_greeting"}
483   if ( $form->{"selected_company_greeting"} );
484
485   $form->{discount} = $form->parse_amount( $myconfig, $form->{discount} );
486   $form->{discount} /= 100;
487   $form->{creditlimit} = $form->parse_amount( $myconfig, $form->{creditlimit} );
488
489   my $query;
490
491   if (!$form->{id}) {
492     $query = qq|SELECT nextval('id')|;
493     ($form->{id}) = selectrow_query($form, $dbh, $query);
494
495     $query = qq|INSERT INTO vendor (id, name) VALUES (?, '')|;
496     do_query($form, $dbh, $query, $form->{id});
497
498     if ( !$form->{vendornumber} ) {
499       $form->{vendornumber} = $form->update_defaults( $myconfig, "vendornumber", $dbh );
500     }
501   }
502
503   $query =
504     qq|UPDATE vendor SET | .
505     qq|  vendornumber = ?, | .
506     qq|  name = ?, | .
507     qq|  greeting = ?, | .
508     qq|  department_1 = ?, | .
509     qq|  department_2 = ?, | .
510     qq|  street = ?, | .
511     qq|  zipcode = ?, | .
512     qq|  city = ?, | .
513     qq|  country = ?, | .
514     qq|  homepage = ?, | .
515     qq|  contact = ?, | .
516     qq|  phone = ?, | .
517     qq|  fax = ?, | .
518     qq|  email = ?, | .
519     qq|  cc = ?, | .
520     qq|  bcc = ?, | .
521     qq|  notes = ?, | .
522     qq|  terms = ?, | .
523     qq|  discount = ?, | .
524     qq|  creditlimit = ?, | .
525     qq|  business_id = ?, | .
526     qq|  taxnumber = ?, | .
527     qq|  language = ?, | .
528     qq|  account_number = ?, | .
529     qq|  bank_code = ?, | .
530     qq|  bank = ?, | .
531     qq|  iban = ?, | .
532     qq|  bic = ?, | .
533     qq|  obsolete = ?, | .
534     qq|  direct_debit = ?, | .
535     qq|  ustid = ?, | .
536     qq|  payment_id = ?, | .
537     qq|  taxzone_id = ?, | .
538     qq|  language_id = ?, | .
539     qq|  username = ?, | .
540     qq|  user_password = ?, | .
541     qq|  v_customer_id = ? | .
542     qq|WHERE id = ?|;
543   @values = (
544     $form->{vendornumber},
545     $form->{name},
546     $form->{greeting},
547     $form->{department_1},
548     $form->{department_2},
549     $form->{street},
550     $form->{zipcode},
551     $form->{city},
552     $form->{country},
553     $form->{homepage},
554     $form->{contact},
555     $form->{phone},
556     $form->{fax},
557     $form->{email},
558     $form->{cc},
559     $form->{bcc},
560     $form->{notes},
561     conv_i($form->{terms}),
562     $form->{discount},
563     $form->{creditlimit},
564     conv_i($form->{business}),
565     $form->{taxnumber},
566     $form->{language},
567     $form->{account_number},
568     $form->{bank_code},
569     $form->{bank},
570     $form->{iban},
571     $form->{bic},
572     $form->{obsolete} ? 't' : 'f',
573     $form->{direct_debit} ? 't' : 'f',
574     $form->{ustid},
575     conv_i($form->{payment_id}),
576     conv_i($form->{taxzone_id}, 0),
577     conv_i( $form->{language_id}),
578     $form->{username},
579     $form->{user_password},
580     $form->{v_customer_id},
581     $form->{id}
582     );
583   do_query($form, $dbh, $query, @values);
584
585   $query = undef;
586   if ( $form->{cp_id} ) {
587     $query = qq|UPDATE contacts SET | .
588       qq|cp_greeting = ?, | .
589       qq|cp_title = ?,  | .
590       qq|cp_givenname = ?, | .
591       qq|cp_name = ?, | .
592       qq|cp_email = ?, | .
593       qq|cp_phone1 = ?, | .
594       qq|cp_phone2 = ?, | .
595       qq|cp_abteilung = ?, | .
596       qq|cp_fax = ?, | .
597       qq|cp_mobile1 = ?, | .
598       qq|cp_mobile2 = ?, | .
599       qq|cp_satphone = ?, | .
600       qq|cp_satfax = ?, | .
601       qq|cp_project = ?, | .
602       qq|cp_privatphone = ?, | .
603       qq|cp_privatemail = ?, | .
604       qq|cp_birthday = ? | .
605       qq|cp_gender = ? | .
606       qq|WHERE cp_id = ?|;
607     @values = (
608       $form->{cp_greeting},
609       $form->{cp_title},
610       $form->{cp_givenname},
611       $form->{cp_name},
612       $form->{cp_email},
613       $form->{cp_phone1},
614       $form->{cp_phone2},
615       $form->{cp_abteilung},
616       $form->{cp_fax},
617       $form->{cp_mobile1},
618       $form->{cp_mobile2},
619       $form->{cp_satphone},
620       $form->{cp_satfax},
621       $form->{cp_project},
622       $form->{cp_privatphone},
623       $form->{cp_privatemail},
624       $form->{cp_birthday},
625       $form->{cp_gender} eq 'f' ? 'f' : 'm',
626       $form->{cp_id}
627       );
628   } elsif ( $form->{cp_name} || $form->{cp_givenname} ) {
629     $query =
630       qq|INSERT INTO contacts ( cp_cv_id, cp_greeting, cp_title, cp_givenname,  | .
631       qq|  cp_name, cp_email, cp_phone1, cp_phone2, cp_abteilung, cp_fax, cp_mobile1, | .
632       qq|  cp_mobile2, cp_satphone, cp_satfax, cp_project, cp_privatphone, cp_privatemail, | .
633       qq|  cp_birthday, cp_gender) | .
634       qq|VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
635     @values = (
636       $form->{id},
637       $form->{cp_greeting},
638       $form->{cp_title},
639       $form->{cp_givenname},
640       $form->{cp_name},
641       $form->{cp_email},
642       $form->{cp_phone1},
643       $form->{cp_phone2},
644       $form->{cp_abteilung},
645       $form->{cp_fax},
646       $form->{cp_mobile1},
647       $form->{cp_mobile2},
648       $form->{cp_satphone},
649       $form->{cp_satfax},
650       $form->{cp_project},
651       $form->{cp_privatphone},
652       $form->{cp_privatemail},
653       $form->{cp_birthday}
654       );
655   }
656   do_query($form, $dbh, $query, @values) if ($query);
657
658   # add shipto
659   $form->add_shipto( $dbh, $form->{id}, "CT" );
660
661   $self->_save_note('dbh' => $dbh);
662   $self->_delete_selected_notes('dbh' => $dbh);
663
664   CVar->save_custom_variables('dbh'       => $dbh,
665                               'module'    => 'CT',
666                               'trans_id'  => $form->{id},
667                               'variables' => $form);
668
669   $rc = $dbh->commit();
670   $dbh->disconnect();
671
672   $main::lxdebug->leave_sub();
673   return $rc;
674 }
675
676 sub delete {
677   $main::lxdebug->enter_sub();
678
679   my ( $self, $myconfig, $form ) = @_;
680   # connect to database
681   my $dbh = $form->dbconnect($myconfig);
682
683   # delete vendor
684   my $cv = $form->{db} eq "customer" ? "customer" : "vendor";
685   my $query = qq|DELETE FROM $cv WHERE id = ?|;
686   do_query($form, $dbh, $query, $form->{id});
687
688   $dbh->disconnect;
689
690   $main::lxdebug->leave_sub();
691 }
692
693 sub search {
694   $main::lxdebug->enter_sub();
695
696   my ( $self, $myconfig, $form ) = @_;
697
698   # connect to database
699   my $dbh = $form->dbconnect($myconfig);
700
701   my $cv = $form->{db} eq "customer" ? "customer" : "vendor";
702
703   my $where = "1 = 1";
704   my @values;
705
706   my %allowed_sort_columns =
707     map({ $_, 1 } qw(id customernumber vendornumber name contact phone fax email
708                      taxnumber business invnumber ordnumber quonumber));
709   $sortorder    = $form->{sort} && $allowed_sort_columns{$form->{sort}} ? $form->{sort} : "name";
710   $form->{sort} = $sortorder;
711   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
712
713   if ($sortorder ne 'id' && 1 >= scalar grep { $form->{$_} } qw(l_ordnumber l_quonumber l_invnumber)) {
714     $sortorder  = "lower($sortorder) ${sortdir}";
715   } else {
716     $sortorder .= " ${sortdir}";
717   }
718
719   if ($form->{"${cv}number"}) {
720     $where .= " AND ct.${cv}number ILIKE ?";
721     push(@values, '%' . $form->{"${cv}number"} . '%');
722   }
723
724   foreach my $key (qw(name contact email)) {
725     if ($form->{$key}) {
726       $where .= " AND ct.$key ILIKE ?";
727       push(@values, '%' . $form->{$key} . '%');
728     }
729   }
730
731   if ($form->{cp_name}) {
732     $where .= " AND ct.id IN (SELECT cp_cv_id FROM contacts WHERE lower(cp_name) LIKE lower(?))";
733     push @values, '%' . $form->{cp_name} . '%';
734   }
735
736   if ($form->{addr_city}) {
737     $where .= " AND ((lower(ct.city) LIKE lower(?))
738                      OR
739                      (ct.id IN (
740                         SELECT trans_id
741                         FROM shipto
742                         WHERE (module = 'CT')
743                           AND (lower(shiptocity) LIKE lower(?))
744                       ))
745                      )";
746     push @values, ('%' . $form->{addr_city} . '%') x 2;
747   }
748
749   if ( $form->{status} eq 'orphaned' ) {
750     $where .=
751       qq| AND ct.id NOT IN | .
752       qq|   (SELECT o.${cv}_id FROM oe o, $cv cv WHERE cv.id = o.${cv}_id)|;
753     if ($cv eq 'customer') {
754       $where .=
755         qq| AND ct.id NOT IN | .
756         qq| (SELECT a.customer_id FROM ar a, customer cv | .
757         qq|  WHERE cv.id = a.customer_id)|;
758     }
759     if ($cv eq 'vendor') {
760       $where .=
761         qq| AND ct.id NOT IN | .
762         qq| (SELECT a.vendor_id FROM ap a, vendor cv | .
763         qq|  WHERE cv.id = a.vendor_id)|;
764     }
765     $form->{l_invnumber} = $form->{l_ordnumber} = $form->{l_quonumber} = "";
766   }
767
768   if ($form->{obsolete} eq "Y") {
769     $where .= qq| AND obsolete|;
770   } elsif ($form->{obsolete} eq "N") {
771     $where .= qq| AND NOT obsolete|;
772   }
773
774   if ($form->{business_id}) {
775     $where .= qq| AND (business_id = ?)|;
776     push(@values, conv_i($form->{business_id}));
777   }
778
779   my ($cvar_where, @cvar_values) = CVar->build_filter_query('module'         => 'CT',
780                                                             'trans_id_field' => 'ct.id',
781                                                             'filter'         => $form);
782
783   if ($cvar_where) {
784     $where .= qq| AND ($cvar_where)|;
785     push @values, @cvar_values;
786   }
787
788   if ($form->{addr_street}) {
789     $where .= qq| AND (street ILIKE ?)|;
790     push @values, '%' . $form->{addr_street} . '%';
791   }
792
793   if ($form->{addr_zipcode}) {
794     $where .= qq| AND (zipcode ILIKE ?)|;
795     push @values, $form->{addr_zipcode} . '%';
796   }
797
798   my $query =
799     qq|SELECT ct.*, b.description AS business | .
800     qq|FROM $cv ct | .
801     qq|LEFT JOIN business b ON (ct.business_id = b.id) | .
802     qq|WHERE $where|;
803
804   my @saved_values = @values;
805   # redo for invoices, orders and quotations
806   if ($form->{l_invnumber} || $form->{l_ordnumber} || $form->{l_quonumber}) {
807     my ($ar, $union, $module);
808     $query = "";
809
810     if ($form->{l_invnumber}) {
811       my $ar = $cv eq 'customer' ? 'ar' : 'ap';
812       my $module = $ar eq 'ar' ? 'is' : 'ir';
813
814       $query =
815         qq|SELECT ct.*, b.description AS business, | .
816         qq|  a.invnumber, a.ordnumber, a.quonumber, a.id AS invid, | .
817         qq|  '$module' AS module, 'invoice' AS formtype, | .
818         qq|  (a.amount = a.paid) AS closed | .
819         qq|FROM $cv ct | .
820         qq|JOIN $ar a ON (a.${cv}_id = ct.id) | .
821         qq|LEFT JOIN business b ON (ct.business_id = b.id) | .
822         qq|WHERE $where AND (a.invoice = '1')|;
823
824       $union = qq|UNION|;
825     }
826
827     if ( $form->{l_ordnumber} ) {
828       if ($union eq "UNION") {
829         push(@values, @saved_values);
830       }
831       $query .=
832         qq| $union | .
833         qq|SELECT ct.*, b.description AS business,| .
834         qq|  ' ' AS invnumber, o.ordnumber, o.quonumber, o.id AS invid, | .
835         qq|  'oe' AS module, 'order' AS formtype, o.closed | .
836         qq|FROM $cv ct | .
837         qq|JOIN oe o ON (o.${cv}_id = ct.id) | .
838         qq|LEFT JOIN business b ON (ct.business_id = b.id) | .
839         qq|WHERE $where AND (o.quotation = '0')|;
840
841       $union = qq|UNION|;
842     }
843
844     if ( $form->{l_quonumber} ) {
845       if ($union eq "UNION") {
846         push(@values, @saved_values);
847       }
848       $query .=
849         qq| $union | .
850         qq|SELECT ct.*, b.description AS business, | .
851         qq|  ' ' AS invnumber, o.ordnumber, o.quonumber, o.id AS invid, | .
852         qq|  'oe' AS module, 'quotation' AS formtype, o.closed | .
853         qq|FROM $cv ct | .
854         qq|JOIN oe o ON (o.${cv}_id = ct.id) | .
855         qq|LEFT JOIN business b ON (ct.business_id = b.id) | .
856         qq|WHERE $where AND (o.quotation = '1')|;
857     }
858   }
859
860   $query .= qq| ORDER BY $sortorder|;
861
862   $form->{CT} = selectall_hashref_query($form, $dbh, $query, @values);
863
864   $main::lxdebug->leave_sub();
865 }
866
867 sub get_contact {
868   $main::lxdebug->enter_sub();
869
870   my ( $self, $myconfig, $form ) = @_;
871   my $dbh   = $form->dbconnect($myconfig);
872   my $query =
873     qq|SELECT * FROM contacts c | .
874     qq|WHERE cp_id = ? ORDER BY cp_id limit 1|;
875   my $sth = prepare_execute_query($form, $dbh, $query, $form->{cp_id});
876   my $ref = $sth->fetchrow_hashref(NAME_lc);
877
878   map { $form->{$_} = $ref->{$_} } keys %$ref;
879
880   $query = qq|SELECT COUNT(cp_id) AS used FROM (
881     SELECT cp_id FROM oe UNION
882     SELECT cp_id FROM ar UNION
883     SELECT cp_id FROM ap UNION
884     SELECT cp_id FROM delivery_orders
885   ) AS cpid WHERE cp_id = ? OR ? = 0|;
886   ($form->{cp_used}) = selectfirst_array_query($form, $dbh, $query, ($form->{cp_id})x2);
887
888   $sth->finish;
889   $dbh->disconnect;
890
891   $main::lxdebug->leave_sub();
892 }
893
894 sub get_shipto {
895   $main::lxdebug->enter_sub();
896
897   my ( $self, $myconfig, $form ) = @_;
898   my $dbh   = $form->dbconnect($myconfig);
899   my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
900   my $sth = prepare_execute_query($form, $dbh, $query, $form->{shipto_id});
901
902   my $ref = $sth->fetchrow_hashref(NAME_lc);
903
904   map { $form->{$_} = $ref->{$_} } keys %$ref;
905
906   $query = qq|SELECT COUNT(shipto_id) AS used FROM (
907     SELECT shipto_id FROM oe UNION
908     SELECT shipto_id FROM ar UNION
909     SELECT shipto_id FROM delivery_orders
910   ) AS stid WHERE shipto_id = ? OR ? = 0|;
911   ($form->{shiptoused}) = selectfirst_array_query($form, $dbh, $query, ($form->{shipto_id})x2);
912
913   $sth->finish;
914   $dbh->disconnect;
915
916   $main::lxdebug->leave_sub();
917 }
918
919 sub get_delivery {
920   $main::lxdebug->enter_sub();
921
922   my ( $self, $myconfig, $form ) = @_;
923   my $dbh = $form->dbconnect($myconfig);
924
925   my $arap = $form->{db} eq "vendor" ? "ap" : "ar";
926   my $db = $form->{db} eq "customer" ? "customer" : "vendor";
927   my $qty_sign = $form->{db} eq 'vendor' ? ' * -1 AS qty' : '';
928
929   my $where = " WHERE 1=1 ";
930   my @values;
931
932   if ($form->{shipto_id} && ($arap eq "ar")) {
933     $where .= "AND ${arap}.shipto_id = ?";
934     push(@values, $form->{shipto_id});
935   } else {
936     $where .= "AND ${arap}.${db}_id = ?";
937     push(@values, $form->{id});
938   }
939
940   if ($form->{from}) {
941     $where .= "AND ${arap}.transdate >= ?";
942     push(@values, conv_date($form->{from}));
943   }
944   if ($form->{to}) {
945     $where .= "AND ${arap}.transdate <= ?";
946     push(@values, conv_date($form->{to}));
947   }
948   my $query =
949     qq|SELECT s.shiptoname, i.qty $qty_sign, | .
950     qq|  ${arap}.id, ${arap}.transdate, ${arap}.invnumber, ${arap}.ordnumber, | .
951     qq|  i.description, i.unit, i.sellprice, | .
952     qq|  oe.id AS oe_id | .
953     qq|FROM $arap | .
954     qq|LEFT JOIN shipto s ON | .
955     ($arap eq "ar"
956      ? qq|(ar.shipto_id = s.shipto_id) |
957      : qq|(ap.id = s.trans_id) |) .
958     qq|LEFT JOIN invoice i ON (${arap}.id = i.trans_id) | .
959     qq|LEFT join parts p ON (p.id = i.parts_id) | .
960     qq|LEFT JOIN oe ON (oe.ordnumber = ${arap}.ordnumber AND NOT ${arap}.ordnumber = '') | .
961     $where .
962     qq|ORDER BY ${arap}.transdate DESC LIMIT 15|;
963
964   $form->{DELIVERY} = selectall_hashref_query($form, $dbh, $query, @values);
965
966   $dbh->disconnect;
967
968   $main::lxdebug->leave_sub();
969 }
970
971 sub _save_note {
972   $main::lxdebug->enter_sub();
973
974   my $self   = shift;
975   my %params = @_;
976
977   my $form   = $main::form;
978
979   Common::check_params(\%params, 'dbh');
980
981   if (!$form->{NOTE_subject}) {
982     $main::lxdebug->leave_sub();
983     return;
984   }
985
986   my $dbh = $params{dbh};
987
988   my %follow_up;
989   my %note = (
990     'id'           => $form->{NOTE_id},
991     'subject'      => $form->{NOTE_subject},
992     'body'         => $form->{NOTE_body},
993     'trans_id'     => $form->{id},
994     'trans_module' => 'ct',
995   );
996
997   $note{id} = Notes->save(%note);
998
999   if ($form->{FU_date}) {
1000     %follow_up = (
1001       'id'               => $form->{FU_id},
1002       'note_id'          => $note{id},
1003       'follow_up_date'   => $form->{FU_date},
1004       'created_for_user' => $form->{FU_created_for_user},
1005       'done'             => $form->{FU_done} ? 1 : 0,
1006       'subject'          => $form->{NOTE_subject},
1007       'body'             => $form->{NOTE_body},
1008       'LINKS'            => [
1009         {
1010           'trans_id'     => $form->{id},
1011           'trans_type'   => $form->{db} eq 'customer' ? 'customer' : 'vendor',
1012           'trans_info'   => $form->{name},
1013         },
1014       ],
1015     );
1016
1017     $follow_up{id} = FU->save(%follow_up);
1018
1019   } elsif ($form->{FU_id}) {
1020     do_query($form, $dbh, qq|DELETE FROM follow_up_links WHERE follow_up_id = ?|, conv_i($form->{FU_id}));
1021     do_query($form, $dbh, qq|DELETE FROM follow_ups      WHERE id = ?|,           conv_i($form->{FU_id}));
1022   }
1023
1024   delete @{$form}{grep { /^NOTE_|^FU_/ } keys %{ $form }};
1025
1026   $main::lxdebug->leave_sub();
1027 }
1028
1029 sub _delete_selected_notes {
1030   $main::lxdebug->enter_sub();
1031
1032   my $self   = shift;
1033   my %params = @_;
1034
1035   Common::check_params(\%params, 'dbh');
1036
1037   my $form = $main::form;
1038   my $dbh  = $params{dbh};
1039
1040   foreach my $i (1 .. $form->{NOTES_rowcount}) {
1041     next unless ($form->{"NOTE_delete_$i"} && $form->{"NOTE_id_$i"});
1042
1043     Notes->delete('dbh' => $params{dbh},
1044                   'id'  => $form->{"NOTE_id_$i"});
1045   }
1046
1047   $main::lxdebug->leave_sub();
1048 }
1049
1050 sub delete_shipto {
1051   $main::lxdebug->enter_sub();
1052
1053   my $self      = shift;
1054   my $shipto_id = shift;
1055
1056   my $form      = $main::form;
1057   my %myconfig  = %main::myconfig;
1058   my $dbh       = $form->get_standard_dbh(\%myconfig);
1059
1060   do_query($form, $dbh, qq|UPDATE shipto SET trans_id = NULL WHERE shipto_id = ?|, $shipto_id);
1061
1062   $dbh->commit();
1063
1064   $main::lxdebug->leave_sub();
1065 }
1066
1067 sub delete_shipto {
1068   $main::lxdebug->enter_sub();
1069
1070   my $self      = shift;
1071   my $shipto_id = shift;
1072
1073   my $form      = $main::form;
1074   my %myconfig  = %main::myconfig;
1075   my $dbh       = $form->get_standard_dbh(\%myconfig);
1076
1077   do_query($form, $dbh, qq|UPDATE contacts SET cp_cv_id = NULL WHERE cp_id = ?|, $shipto_id);
1078
1079   $dbh->commit();
1080
1081   $main::lxdebug->leave_sub();
1082 }
1083
1084 sub get_bank_info {
1085   $main::lxdebug->enter_sub();
1086
1087   my $self     = shift;
1088   my %params   = @_;
1089
1090   Common::check_params(\%params, qw(vc id));
1091
1092   my $myconfig = \%main::myconfig;
1093   my $form     = $main::form;
1094
1095   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1096
1097   my $table        = $params{vc} eq 'customer' ? 'customer' : 'vendor';
1098   my @ids          = ref $params{id} eq 'ARRAY' ? @{ $params{id} } : ($params{id});
1099   my $placeholders = ('?') x scalar @ids;
1100   my $query        = qq|SELECT id, name, account_number, bank, bank_code, iban, bic
1101                         FROM ${table}
1102                         WHERE id IN (${placeholders})|;
1103
1104   my $result       = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1105
1106   if (ref $params{id} eq 'ARRAY') {
1107     $result = { map { $_->{id} => $_ } @{ $result } };
1108   } else {
1109     $result = $result->[0] || { 'id' => $params{id} };
1110   }
1111
1112   $main::lxdebug->leave_sub();
1113
1114   return $result;
1115 }
1116
1117 1;