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