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