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