Merge branch 'master' of ssh://lx-office/~/lx-office-erp
[kivitendo-erp.git] / SL / CT.pm
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 2001
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #  Contributors:
16 #
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
21 #
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
30 #
31 # backend code for customers and vendors
32 #
33 # CHANGE LOG:
34 #   DS. 2000-07-04  Created
35 #
36 #======================================================================
37
38 package CT;
39
40 use Data::Dumper;
41
42 use SL::Common;
43 use SL::CVar;
44 use SL::DBUtils;
45 use SL::FU;
46 use SL::Notes;
47
48 sub get_tuple {
49   $main::lxdebug->enter_sub();
50
51   my ( $self, $myconfig, $form ) = @_;
52
53   my $cv = $form->{db} eq "customer" ? "customer" : "vendor";
54
55   my $dbh   = $form->dbconnect($myconfig);
56   my $query =
57     qq|SELECT ct.*, b.id AS business, cp.* | .
58     qq|FROM $cv ct | .
59     qq|LEFT JOIN business b ON (ct.business_id = b.id) | .
60     qq|LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id) | .
61     qq|WHERE (ct.id = ?) | .
62     qq|ORDER BY cp.cp_id LIMIT 1|;
63   my $sth = prepare_execute_query($form, $dbh, $query, $form->{id});
64
65   my $ref = $sth->fetchrow_hashref(NAME_lc);
66
67   map { $form->{$_} = $ref->{$_} } keys %$ref;
68
69   $sth->finish;
70   if ( $form->{salesman_id} ) {
71     my $query =
72       qq|SELECT ct.name AS salesman | .
73       qq|FROM $cv ct | .
74       qq|WHERE ct.id = ?|;
75     ($form->{salesman}) =
76       selectrow_query($form, $dbh, $query, $form->{salesman_id});
77   }
78
79   my ($employee_id) = selectrow_query($form, $dbh, qq|SELECT id FROM employee WHERE login = ?|, $form->{login});
80   $query =
81     qq|SELECT n.*, n.itime::DATE AS created_on,
82          e.name AS created_by_name, e.login AS created_by_login
83        FROM notes n
84        LEFT JOIN employee e ON (n.created_by = e.id)
85        WHERE (n.trans_id = ?) AND (n.trans_module = 'ct')|;
86   $form->{NOTES} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
87
88   $query =
89     qq|SELECT fu.follow_up_date, fu.done AS follow_up_done, e.name AS created_for_name, e.name AS created_for_login
90        FROM follow_ups fu
91        LEFT JOIN employee e ON (fu.created_for_user = e.id)
92        WHERE (fu.note_id = ?)
93          AND NOT COALESCE(fu.done, FALSE)
94          AND (   (fu.created_by = ?)
95               OR (fu.created_by IN (SELECT DISTINCT what FROM follow_up_access WHERE who = ?)))|;
96   $sth = prepare_query($form, $dbh, $query);
97
98   foreach my $note (@{ $form->{NOTES} }) {
99     do_statement($form, $sth, $query, conv_i($note->{id}), conv_i($note->{created_by}), conv_i($employee_id));
100     $ref = $sth->fetchrow_hashref();
101
102     map { $note->{$_} = $ref->{$_} } keys %{ $ref } if ($ref);
103   }
104
105   $sth->finish();
106
107   if ($form->{edit_note_id}) {
108     $query =
109       qq|SELECT n.id AS NOTE_id, n.subject AS NOTE_subject, n.body AS NOTE_body,
110            fu.id AS FU_id, fu.follow_up_date AS FU_date, fu.done AS FU_done, fu.created_for_user AS FU_created_for_user
111          FROM notes n
112          LEFT JOIN follow_ups fu ON ((n.id = fu.note_id) AND NOT COALESCE(fu.done, FALSE))
113          WHERE n.id = ?|;
114     $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{edit_note_id}));
115
116     if ($ref) {
117       foreach my $key (keys %{ $ref }) {
118         my $new_key       =  $key;
119         $new_key          =~ s/^([^_]+)/\U\1\E/;
120         $form->{$new_key} =  $ref->{$key};
121       }
122     }
123   }
124
125   # check if it is orphaned
126   my $arap      = ( $form->{db} eq 'customer' ) ? "ar" : "ap";
127   my $num_args  = 2;
128   my $makemodel = '';
129   if ($form->{db} eq 'vendor') {
130     $makemodel = qq| UNION SELECT 1 FROM makemodel mm WHERE mm.make = ?|;
131     $num_args++;
132   }
133
134   $query =
135     qq|SELECT a.id | .
136     qq|FROM $arap a | .
137     qq|JOIN $cv ct ON (a.${cv}_id = ct.id) | .
138     qq|WHERE ct.id = ? | .
139     qq|UNION | .
140     qq|SELECT a.id | .
141     qq|FROM oe a | .
142     qq|JOIN $cv ct ON (a.${cv}_id = ct.id) | .
143     qq|WHERE ct.id = ?|
144     . $makemodel;
145   my ($dummy) = selectrow_query($form, $dbh, $query, (conv_i($form->{id})) x $num_args);
146
147   $form->{status} = "orphaned" unless ($dummy);
148
149   $dbh->disconnect;
150
151   $main::lxdebug->leave_sub();
152 }
153
154 sub populate_drop_down_boxes {
155   $main::lxdebug->enter_sub();
156
157   my ($self, $myconfig, $form, $provided_dbh) = @_;
158
159   my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect($myconfig);
160
161   # get business types
162   $query = qq|SELECT id, description FROM business ORDER BY id|;
163   $form->{all_business} = selectall_hashref_query($form, $dbh, $query);
164
165   # get shipto address
166   $query =
167     qq|SELECT shipto_id, shiptoname, shiptodepartment_1, shiptostreet, shiptocity
168        FROM shipto
169        WHERE (trans_id = ?) AND (module = 'CT')|;
170   $form->{SHIPTO} = selectall_hashref_query($form, $dbh, $query, $form->{id});
171
172   # get contacts
173   $query  = qq|SELECT cp_id, cp_name, cp_givenname FROM contacts WHERE cp_cv_id = ? ORDER BY cp_name|;
174   $form->{CONTACTS} = selectall_hashref_query($form, $dbh, $query, $form->{id});
175
176   # get languages
177   $query = qq|SELECT id, description FROM language ORDER BY id|;
178   $form->{languages} = selectall_hashref_query($form, $dbh, $query);
179
180   # get payment terms
181   $query = qq|SELECT id, description FROM payment_terms ORDER BY sortkey|;
182   $form->{payment_terms} = selectall_hashref_query($form, $dbh, $query);
183
184   $dbh->disconnect() unless ($provided_dbh);
185
186   $main::lxdebug->leave_sub();
187 }
188
189 sub query_titles_and_greetings {
190   $main::lxdebug->enter_sub();
191
192   my ( $self, $myconfig, $form ) = @_;
193   my ( %tmp,  $ref );
194
195   my $dbh = $form->dbconnect($myconfig);
196
197   $query =
198     qq|SELECT DISTINCT(greeting) | .
199     qq|FROM customer | .
200     qq|WHERE greeting ~ '[a-zA-Z]' | .
201     qq|UNION | .
202     qq|SELECT DISTINCT(greeting) | .
203     qq|FROM vendor | .
204     qq|WHERE greeting ~ '[a-zA-Z]' | .
205     qq|ORDER BY greeting|;
206   my %tmp;
207   map({ $tmp{$_} = 1; } selectall_array_query($form, $dbh, $query));
208   $form->{COMPANY_GREETINGS} = [ sort(keys(%tmp)) ];
209
210   $query =
211     qq|SELECT DISTINCT(cp_title) | .
212     qq|FROM contacts | .
213     qq|WHERE cp_title ~ '[a-zA-Z]'|;
214   $form->{TITLES} = [ selectall_array_query($form, $dbh, $query) ];
215
216   $query =
217     qq|SELECT DISTINCT(cp_abteilung) | .
218     qq|FROM contacts | .
219     qq|WHERE cp_abteilung ~ '[a-zA-Z]'|;
220   $form->{DEPARTMENT} = [ selectall_array_query($form, $dbh, $query) ];
221
222   $dbh->disconnect();
223   $main::lxdebug->leave_sub();
224 }
225
226 sub save_customer {
227   $main::lxdebug->enter_sub();
228
229   my ( $self, $myconfig, $form ) = @_;
230
231   # set pricegroup to default
232   $form->{klass} = 0 unless ($form->{klass});
233
234   # connect to database
235   my $dbh = $form->dbconnect_noauto($myconfig);
236
237   map( {
238     $form->{"cp_${_}"} = $form->{"selected_cp_${_}"}
239     if ( $form->{"selected_cp_${_}"} );
240        } qw(title greeting abteilung) );
241   $form->{"greeting"} = $form->{"selected_company_greeting"}
242   if ( $form->{"selected_company_greeting"} );
243
244   # assign value discount, terms, creditlimit
245   $form->{discount} = $form->parse_amount( $myconfig, $form->{discount} );
246   $form->{discount} /= 100;
247   $form->{creditlimit} = $form->parse_amount( $myconfig, $form->{creditlimit} );
248
249   my ( $query, $sth, $f_id );
250
251   if ( $form->{id} ) {
252     $query = qq|SELECT id FROM customer WHERE customernumber = ?|;
253     ($f_id) = selectrow_query($form, $dbh, $query, $form->{customernumber});
254
255     if (($f_id ne $form->{id}) && ($f_id ne "")) {
256       $main::lxdebug->leave_sub();
257       return 3;
258     }
259
260   } else {
261     if (!$form->{customernumber} && $form->{business}) {
262       $form->{customernumber} =
263         $form->update_business($myconfig, $form->{business}, $dbh);
264     }
265     if (!$form->{customernumber}) {
266       $form->{customernumber} =
267         $form->update_defaults($myconfig, "customernumber", $dbh);
268     }
269
270     $query  = qq|SELECT c.id FROM customer c WHERE c.customernumber = ?|;
271     ($f_id) = selectrow_query($form, $dbh, $query, $form->{customernumber});
272     if ($f_id ne "") {
273       $main::lxdebug->leave_sub();
274       return 3;
275     }
276
277     $query = qq|SELECT nextval('id')|;
278     ($form->{id}) = selectrow_query($form, $dbh, $query);
279
280     $query = qq|INSERT INTO customer (id, name) VALUES (?, '')|;
281     do_query($form, $dbh, $query, $form->{id});
282   }
283
284   $query = qq|UPDATE customer SET | .
285     qq|customernumber = ?, | .
286     qq|name = ?, | .
287     qq|greeting = ?, | .
288     qq|department_1 = ?, | .
289     qq|department_2 = ?, | .
290     qq|street = ?, | .
291     qq|zipcode = ?, | .
292     qq|city = ?, | .
293     qq|country = ?, | .
294     qq|homepage = ?, | .
295     qq|contact = ?, | .
296     qq|phone = ?, | .
297     qq|fax = ?, | .
298     qq|email = ?, | .
299     qq|cc = ?, | .
300     qq|bcc = ?, | .
301     qq|notes = ?, | .
302     qq|discount = ?, | .
303     qq|creditlimit = ?, | .
304     qq|terms = ?, | .
305     qq|business_id = ?, | .
306     qq|taxnumber = ?, | .
307     qq|language = ?, | .
308     qq|account_number = ?, | .
309     qq|bank_code = ?, | .
310     qq|bank = ?, | .
311     qq|iban = ?, | .
312     qq|bic = ?, | .
313     qq|obsolete = ?, | .
314     qq|direct_debit = ?, | .
315     qq|ustid = ?, | .
316     qq|username = ?, | .
317     qq|salesman_id = ?, | .
318     qq|language_id = ?, | .
319     qq|payment_id = ?, | .
320     qq|taxzone_id = ?, | .
321     qq|user_password = ?, | .
322     qq|c_vendor_id = ?, | .
323     qq|klass = ? | .
324     qq|WHERE id = ?|;
325   my @values = (
326     $form->{customernumber},
327     $form->{name},
328     $form->{greeting},
329     $form->{department_1},
330     $form->{department_2},
331     $form->{street},
332     $form->{zipcode},
333     $form->{city},
334     $form->{country},
335     $form->{homepage},
336     $form->{contact},
337     $form->{phone},
338     $form->{fax},
339     $form->{email},
340     $form->{cc},
341     $form->{bcc},
342     $form->{notes},
343     $form->{discount},
344     $form->{creditlimit},
345     conv_i($form->{terms}),
346     conv_i($form->{business}),
347     $form->{taxnumber},
348     $form->{language},
349     $form->{account_number},
350     $form->{bank_code},
351     $form->{bank},
352     $form->{iban},
353     $form->{bic},
354     $form->{obsolete} ? 't' : 'f',
355     $form->{direct_debit} ? 't' : 'f',
356     $form->{ustid},
357     $form->{username},
358     conv_i($form->{salesman_id}),
359     conv_i($form->{language_id}),
360     conv_i($form->{payment_id}),
361     conv_i($form->{taxzone_id}, 0),
362     $form->{user_password},
363     $form->{c_vendor_id},
364     conv_i($form->{klass}),
365     $form->{id}
366     );
367   do_query( $form, $dbh, $query, @values );
368
369   $query = undef;
370   if ( $form->{cp_id} ) {
371     $query = qq|UPDATE contacts SET | .
372       qq|cp_title = ?,  | .
373       qq|cp_givenname = ?, | .
374       qq|cp_name = ?, | .
375       qq|cp_email = ?, | .
376       qq|cp_phone1 = ?, | .
377       qq|cp_phone2 = ?, | .
378       qq|cp_abteilung = ?, | .
379       qq|cp_fax = ?, | .
380       qq|cp_mobile1 = ?, | .
381       qq|cp_mobile2 = ?, | .
382       qq|cp_satphone = ?, | .
383       qq|cp_satfax = ?, | .
384       qq|cp_project = ?, | .
385       qq|cp_privatphone = ?, | .
386       qq|cp_privatemail = ?, | .
387       qq|cp_birthday = ?, | .
388       qq|cp_gender = ? | .
389       qq|WHERE cp_id = ?|;
390     @values = (
391       $form->{cp_title},
392       $form->{cp_givenname},
393       $form->{cp_name},
394       $form->{cp_email},
395       $form->{cp_phone1},
396       $form->{cp_phone2},
397       $form->{cp_abteilung},
398       $form->{cp_fax},
399       $form->{cp_mobile1},
400       $form->{cp_mobile2},
401       $form->{cp_satphone},
402       $form->{cp_satfax},
403       $form->{cp_project},
404       $form->{cp_privatphone},
405       $form->{cp_privatemail},
406       $form->{cp_birthday},
407       $form->{cp_gender} eq 'f' ? 'f' : 'm',
408       $form->{cp_id}
409       );
410   } elsif ( $form->{cp_name} || $form->{cp_givenname} ) {
411     $query =
412       qq|INSERT INTO contacts ( cp_cv_id, cp_title, cp_givenname,  | .
413       qq|  cp_name, cp_email, cp_phone1, cp_phone2, cp_abteilung, cp_fax, cp_mobile1, | .
414       qq|  cp_mobile2, cp_satphone, cp_satfax, cp_project, cp_privatphone, cp_privatemail, | .
415       qq|  cp_birthday, cp_gender) | .
416       qq|VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
417     @values = (
418       $form->{id},
419       $form->{cp_title},
420       $form->{cp_givenname},
421       $form->{cp_name},
422       $form->{cp_email},
423       $form->{cp_phone1},
424       $form->{cp_phone2},
425       $form->{cp_abteilung},
426       $form->{cp_fax},
427       $form->{cp_mobile1},
428       $form->{cp_mobile2},
429       $form->{cp_satphone},
430       $form->{cp_satfax},
431       $form->{cp_project},
432       $form->{cp_privatphone},
433       $form->{cp_privatemail},
434       $form->{cp_birthday},
435       $form->{cp_gender} eq 'f' ? 'f' : 'm',
436       );
437   }
438   do_query( $form, $dbh, $query, @values ) if ($query);
439
440   # add shipto
441   $form->add_shipto( $dbh, $form->{id}, "CT" );
442
443   $self->_save_note('dbh' => $dbh);
444   $self->_delete_selected_notes('dbh' => $dbh);
445
446   CVar->save_custom_variables('dbh'       => $dbh,
447                               'module'    => 'CT',
448                               'trans_id'  => $form->{id},
449                               'variables' => $form);
450
451   $rc = $dbh->commit();
452   $dbh->disconnect();
453
454   $main::lxdebug->leave_sub();
455   return $rc;
456 }
457
458 sub save_vendor {
459   $main::lxdebug->enter_sub();
460
461   my ( $self, $myconfig, $form ) = @_;
462
463   $form->{taxzone_id} *= 1;
464   # connect to database
465   my $dbh = $form->dbconnect_noauto($myconfig);
466
467   map( {
468     $form->{"cp_${_}"} = $form->{"selected_cp_${_}"}
469     if ( $form->{"selected_cp_${_}"} );
470        } qw(title greeting abteilung) );
471   $form->{"greeting"} = $form->{"selected_company_greeting"}
472   if ( $form->{"selected_company_greeting"} );
473
474   $form->{discount} = $form->parse_amount( $myconfig, $form->{discount} );
475   $form->{discount} /= 100;
476   $form->{creditlimit} = $form->parse_amount( $myconfig, $form->{creditlimit} );
477
478   my $query;
479
480   if (!$form->{id}) {
481     $query = qq|SELECT nextval('id')|;
482     ($form->{id}) = selectrow_query($form, $dbh, $query);
483
484     $query = qq|INSERT INTO vendor (id, name) VALUES (?, '')|;
485     do_query($form, $dbh, $query, $form->{id});
486
487     if ( !$form->{vendornumber} ) {
488       $form->{vendornumber} = $form->update_defaults( $myconfig, "vendornumber", $dbh );
489     }
490   }
491
492   $query =
493     qq|UPDATE vendor SET | .
494     qq|  vendornumber = ?, | .
495     qq|  name = ?, | .
496     qq|  greeting = ?, | .
497     qq|  department_1 = ?, | .
498     qq|  department_2 = ?, | .
499     qq|  street = ?, | .
500     qq|  zipcode = ?, | .
501     qq|  city = ?, | .
502     qq|  country = ?, | .
503     qq|  homepage = ?, | .
504     qq|  contact = ?, | .
505     qq|  phone = ?, | .
506     qq|  fax = ?, | .
507     qq|  email = ?, | .
508     qq|  cc = ?, | .
509     qq|  bcc = ?, | .
510     qq|  notes = ?, | .
511     qq|  terms = ?, | .
512     qq|  discount = ?, | .
513     qq|  creditlimit = ?, | .
514     qq|  business_id = ?, | .
515     qq|  taxnumber = ?, | .
516     qq|  language = ?, | .
517     qq|  account_number = ?, | .
518     qq|  bank_code = ?, | .
519     qq|  bank = ?, | .
520     qq|  iban = ?, | .
521     qq|  bic = ?, | .
522     qq|  obsolete = ?, | .
523     qq|  direct_debit = ?, | .
524     qq|  ustid = ?, | .
525     qq|  payment_id = ?, | .
526     qq|  taxzone_id = ?, | .
527     qq|  language_id = ?, | .
528     qq|  username = ?, | .
529     qq|  user_password = ?, | .
530     qq|  v_customer_id = ? | .
531     qq|WHERE id = ?|;
532   @values = (
533     $form->{vendornumber},
534     $form->{name},
535     $form->{greeting},
536     $form->{department_1},
537     $form->{department_2},
538     $form->{street},
539     $form->{zipcode},
540     $form->{city},
541     $form->{country},
542     $form->{homepage},
543     $form->{contact},
544     $form->{phone},
545     $form->{fax},
546     $form->{email},
547     $form->{cc},
548     $form->{bcc},
549     $form->{notes},
550     conv_i($form->{terms}),
551     $form->{discount},
552     $form->{creditlimit},
553     conv_i($form->{business}),
554     $form->{taxnumber},
555     $form->{language},
556     $form->{account_number},
557     $form->{bank_code},
558     $form->{bank},
559     $form->{iban},
560     $form->{bic},
561     $form->{obsolete} ? 't' : 'f',
562     $form->{direct_debit} ? 't' : 'f',
563     $form->{ustid},
564     conv_i($form->{payment_id}),
565     conv_i($form->{taxzone_id}, 0),
566     conv_i( $form->{language_id}),
567     $form->{username},
568     $form->{user_password},
569     $form->{v_customer_id},
570     $form->{id}
571     );
572   do_query($form, $dbh, $query, @values);
573
574   $query = undef;
575   if ( $form->{cp_id} ) {
576     $query = qq|UPDATE contacts SET | .
577       qq|cp_title = ?,  | .
578       qq|cp_givenname = ?, | .
579       qq|cp_name = ?, | .
580       qq|cp_email = ?, | .
581       qq|cp_phone1 = ?, | .
582       qq|cp_phone2 = ?, | .
583       qq|cp_abteilung = ?, | .
584       qq|cp_fax = ?, | .
585       qq|cp_mobile1 = ?, | .
586       qq|cp_mobile2 = ?, | .
587       qq|cp_satphone = ?, | .
588       qq|cp_satfax = ?, | .
589       qq|cp_project = ?, | .
590       qq|cp_privatphone = ?, | .
591       qq|cp_privatemail = ?, | .
592       qq|cp_birthday = ?, | .
593       qq|cp_gender = ? | .
594       qq|WHERE cp_id = ?|;
595     @values = (
596       $form->{cp_title},
597       $form->{cp_givenname},
598       $form->{cp_name},
599       $form->{cp_email},
600       $form->{cp_phone1},
601       $form->{cp_phone2},
602       $form->{cp_abteilung},
603       $form->{cp_fax},
604       $form->{cp_mobile1},
605       $form->{cp_mobile2},
606       $form->{cp_satphone},
607       $form->{cp_satfax},
608       $form->{cp_project},
609       $form->{cp_privatphone},
610       $form->{cp_privatemail},
611       $form->{cp_birthday},
612       $form->{cp_gender} eq 'f' ? 'f' : 'm',
613       $form->{cp_id}
614       );
615   } elsif ( $form->{cp_name} || $form->{cp_givenname} ) {
616     $query =
617       qq|INSERT INTO contacts ( cp_cv_id, cp_title, cp_givenname,  | .
618       qq|  cp_name, cp_email, cp_phone1, cp_phone2, cp_abteilung, cp_fax, cp_mobile1, | .
619       qq|  cp_mobile2, cp_satphone, cp_satfax, cp_project, cp_privatphone, cp_privatemail, | .
620       qq|  cp_birthday, cp_gender) | .
621       qq|VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
622     @values = (
623       $form->{id},
624       $form->{cp_title},
625       $form->{cp_givenname},
626       $form->{cp_name},
627       $form->{cp_email},
628       $form->{cp_phone1},
629       $form->{cp_phone2},
630       $form->{cp_abteilung},
631       $form->{cp_fax},
632       $form->{cp_mobile1},
633       $form->{cp_mobile2},
634       $form->{cp_satphone},
635       $form->{cp_satfax},
636       $form->{cp_project},
637       $form->{cp_privatphone},
638       $form->{cp_privatemail},
639       $form->{cp_birthday},
640       $form->{cp_gender}
641       );
642   }
643   do_query($form, $dbh, $query, @values) if ($query);
644
645   # add shipto
646   $form->add_shipto( $dbh, $form->{id}, "CT" );
647
648   $self->_save_note('dbh' => $dbh);
649   $self->_delete_selected_notes('dbh' => $dbh);
650
651   CVar->save_custom_variables('dbh'       => $dbh,
652                               'module'    => 'CT',
653                               'trans_id'  => $form->{id},
654                               'variables' => $form);
655
656   $rc = $dbh->commit();
657   $dbh->disconnect();
658
659   $main::lxdebug->leave_sub();
660   return $rc;
661 }
662
663 sub delete {
664   $main::lxdebug->enter_sub();
665
666   my ( $self, $myconfig, $form ) = @_;
667   # connect to database
668   my $dbh = $form->dbconnect($myconfig);
669
670   # delete vendor
671   my $cv = $form->{db} eq "customer" ? "customer" : "vendor";
672   my $query = qq|DELETE FROM $cv WHERE id = ?|;
673   do_query($form, $dbh, $query, $form->{id});
674
675   $dbh->disconnect;
676
677   $main::lxdebug->leave_sub();
678 }
679
680 sub search {
681   $main::lxdebug->enter_sub();
682
683   my ( $self, $myconfig, $form ) = @_;
684
685   # connect to database
686   my $dbh = $form->dbconnect($myconfig);
687
688   my $cv = $form->{db} eq "customer" ? "customer" : "vendor";
689
690   my $where = "1 = 1";
691   my @values;
692
693   my %allowed_sort_columns =
694     map({ $_, 1 } qw(id customernumber vendornumber name contact phone fax email
695                      taxnumber business invnumber ordnumber quonumber));
696   $sortorder    = $form->{sort} && $allowed_sort_columns{$form->{sort}} ? $form->{sort} : "name";
697   $form->{sort} = $sortorder;
698   my $sortdir   = !defined $form->{sortdir} ? 'ASC' : $form->{sortdir} ? 'ASC' : 'DESC';
699
700   if ($sortorder ne 'id' && 1 >= scalar grep { $form->{$_} } qw(l_ordnumber l_quonumber l_invnumber)) {
701     $sortorder  = "lower($sortorder) ${sortdir}";
702   } else {
703     $sortorder .= " ${sortdir}";
704   }
705
706   if ($form->{"${cv}number"}) {
707     $where .= " AND ct.${cv}number ILIKE ?";
708     push(@values, '%' . $form->{"${cv}number"} . '%');
709   }
710
711   foreach my $key (qw(name contact email)) {
712     if ($form->{$key}) {
713       $where .= " AND ct.$key ILIKE ?";
714       push(@values, '%' . $form->{$key} . '%');
715     }
716   }
717
718   if ($form->{cp_name}) {
719     $where .= " AND ct.id IN (SELECT cp_cv_id FROM contacts WHERE lower(cp_name) LIKE lower(?))";
720     push @values, '%' . $form->{cp_name} . '%';
721   }
722
723   if ($form->{addr_city}) {
724     $where .= " AND ((lower(ct.city) LIKE lower(?))
725                      OR
726                      (ct.id IN (
727                         SELECT trans_id
728                         FROM shipto
729                         WHERE (module = 'CT')
730                           AND (lower(shiptocity) LIKE lower(?))
731                       ))
732                      )";
733     push @values, ('%' . $form->{addr_city} . '%') x 2;
734   }
735
736   if ( $form->{status} eq 'orphaned' ) {
737     $where .=
738       qq| AND ct.id NOT IN | .
739       qq|   (SELECT o.${cv}_id FROM oe o, $cv cv WHERE cv.id = o.${cv}_id)|;
740     if ($cv eq 'customer') {
741       $where .=
742         qq| AND ct.id NOT IN | .
743         qq| (SELECT a.customer_id FROM ar a, customer cv | .
744         qq|  WHERE cv.id = a.customer_id)|;
745     }
746     if ($cv eq 'vendor') {
747       $where .=
748         qq| AND ct.id NOT IN | .
749         qq| (SELECT a.vendor_id FROM ap a, vendor cv | .
750         qq|  WHERE cv.id = a.vendor_id)|;
751     }
752     $form->{l_invnumber} = $form->{l_ordnumber} = $form->{l_quonumber} = "";
753   }
754
755   if ($form->{obsolete} eq "Y") {
756     $where .= qq| AND obsolete|;
757   } elsif ($form->{obsolete} eq "N") {
758     $where .= qq| AND NOT obsolete|;
759   }
760
761   if ($form->{business_id}) {
762     $where .= qq| AND (business_id = ?)|;
763     push(@values, conv_i($form->{business_id}));
764   }
765
766   my ($cvar_where, @cvar_values) = CVar->build_filter_query('module'         => 'CT',
767                                                             'trans_id_field' => 'ct.id',
768                                                             'filter'         => $form);
769
770   if ($cvar_where) {
771     $where .= qq| AND ($cvar_where)|;
772     push @values, @cvar_values;
773   }
774
775   if ($form->{addr_street}) {
776     $where .= qq| AND (street ILIKE ?)|;
777     push @values, '%' . $form->{addr_street} . '%';
778   }
779
780   if ($form->{addr_zipcode}) {
781     $where .= qq| AND (zipcode ILIKE ?)|;
782     push @values, $form->{addr_zipcode} . '%';
783   }
784
785   my $query =
786     qq|SELECT ct.*, b.description AS business | .
787     qq|FROM $cv ct | .
788     qq|LEFT JOIN business b ON (ct.business_id = b.id) | .
789     qq|WHERE $where|;
790
791   my @saved_values = @values;
792   # redo for invoices, orders and quotations
793   if ($form->{l_invnumber} || $form->{l_ordnumber} || $form->{l_quonumber}) {
794     my ($ar, $union, $module);
795     $query = "";
796
797     if ($form->{l_invnumber}) {
798       my $ar = $cv eq 'customer' ? 'ar' : 'ap';
799       my $module = $ar eq 'ar' ? 'is' : 'ir';
800
801       $query =
802         qq|SELECT ct.*, b.description AS business, | .
803         qq|  a.invnumber, a.ordnumber, a.quonumber, a.id AS invid, | .
804         qq|  '$module' AS module, 'invoice' AS formtype, | .
805         qq|  (a.amount = a.paid) AS closed | .
806         qq|FROM $cv ct | .
807         qq|JOIN $ar a ON (a.${cv}_id = ct.id) | .
808         qq|LEFT JOIN business b ON (ct.business_id = b.id) | .
809         qq|WHERE $where AND (a.invoice = '1')|;
810
811       $union = qq|UNION|;
812     }
813
814     if ( $form->{l_ordnumber} ) {
815       if ($union eq "UNION") {
816         push(@values, @saved_values);
817       }
818       $query .=
819         qq| $union | .
820         qq|SELECT ct.*, b.description AS business,| .
821         qq|  ' ' AS invnumber, o.ordnumber, o.quonumber, o.id AS invid, | .
822         qq|  'oe' AS module, 'order' AS formtype, o.closed | .
823         qq|FROM $cv ct | .
824         qq|JOIN oe o ON (o.${cv}_id = ct.id) | .
825         qq|LEFT JOIN business b ON (ct.business_id = b.id) | .
826         qq|WHERE $where AND (o.quotation = '0')|;
827
828       $union = qq|UNION|;
829     }
830
831     if ( $form->{l_quonumber} ) {
832       if ($union eq "UNION") {
833         push(@values, @saved_values);
834       }
835       $query .=
836         qq| $union | .
837         qq|SELECT ct.*, b.description AS business, | .
838         qq|  ' ' AS invnumber, o.ordnumber, o.quonumber, o.id AS invid, | .
839         qq|  'oe' AS module, 'quotation' AS formtype, o.closed | .
840         qq|FROM $cv ct | .
841         qq|JOIN oe o ON (o.${cv}_id = ct.id) | .
842         qq|LEFT JOIN business b ON (ct.business_id = b.id) | .
843         qq|WHERE $where AND (o.quotation = '1')|;
844     }
845   }
846
847   $query .= qq| ORDER BY $sortorder|;
848
849   $form->{CT} = selectall_hashref_query($form, $dbh, $query, @values);
850
851   $main::lxdebug->leave_sub();
852 }
853
854 sub get_contact {
855   $main::lxdebug->enter_sub();
856
857   my ( $self, $myconfig, $form ) = @_;
858   my $dbh   = $form->dbconnect($myconfig);
859   my $query =
860     qq|SELECT * FROM contacts c | .
861     qq|WHERE cp_id = ? ORDER BY cp_id limit 1|;
862   my $sth = prepare_execute_query($form, $dbh, $query, $form->{cp_id});
863   my $ref = $sth->fetchrow_hashref(NAME_lc);
864
865   map { $form->{$_} = $ref->{$_} } keys %$ref;
866
867   $query = qq|SELECT COUNT(cp_id) AS used FROM (
868     SELECT cp_id FROM oe UNION
869     SELECT cp_id FROM ar UNION
870     SELECT cp_id FROM ap UNION
871     SELECT cp_id FROM delivery_orders
872   ) AS cpid WHERE cp_id = ? OR ? = 0|;
873   ($form->{cp_used}) = selectfirst_array_query($form, $dbh, $query, ($form->{cp_id})x2);
874
875   $sth->finish;
876   $dbh->disconnect;
877
878   $main::lxdebug->leave_sub();
879 }
880
881 sub get_shipto {
882   $main::lxdebug->enter_sub();
883
884   my ( $self, $myconfig, $form ) = @_;
885   my $dbh   = $form->dbconnect($myconfig);
886   my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
887   my $sth = prepare_execute_query($form, $dbh, $query, $form->{shipto_id});
888
889   my $ref = $sth->fetchrow_hashref(NAME_lc);
890
891   map { $form->{$_} = $ref->{$_} } keys %$ref;
892
893   $query = qq|SELECT COUNT(shipto_id) AS used FROM (
894     SELECT shipto_id FROM oe UNION
895     SELECT shipto_id FROM ar UNION
896     SELECT shipto_id FROM delivery_orders
897   ) AS stid WHERE shipto_id = ? OR ? = 0|;
898   ($form->{shiptoused}) = selectfirst_array_query($form, $dbh, $query, ($form->{shipto_id})x2);
899
900   $sth->finish;
901   $dbh->disconnect;
902
903   $main::lxdebug->leave_sub();
904 }
905
906 sub get_delivery {
907   $main::lxdebug->enter_sub();
908
909   my ( $self, $myconfig, $form ) = @_;
910   my $dbh = $form->dbconnect($myconfig);
911
912   my $arap = $form->{db} eq "vendor" ? "ap" : "ar";
913   my $db = $form->{db} eq "customer" ? "customer" : "vendor";
914   my $qty_sign = $form->{db} eq 'vendor' ? ' * -1 AS qty' : '';
915
916   my $where = " WHERE 1=1 ";
917   my @values;
918
919   if ($form->{shipto_id} && ($arap eq "ar")) {
920     $where .= "AND ${arap}.shipto_id = ?";
921     push(@values, $form->{shipto_id});
922   } else {
923     $where .= "AND ${arap}.${db}_id = ?";
924     push(@values, $form->{id});
925   }
926
927   if ($form->{from}) {
928     $where .= "AND ${arap}.transdate >= ?";
929     push(@values, conv_date($form->{from}));
930   }
931   if ($form->{to}) {
932     $where .= "AND ${arap}.transdate <= ?";
933     push(@values, conv_date($form->{to}));
934   }
935   my $query =
936     qq|SELECT s.shiptoname, i.qty $qty_sign, | .
937     qq|  ${arap}.id, ${arap}.transdate, ${arap}.invnumber, ${arap}.ordnumber, | .
938     qq|  i.description, i.unit, i.sellprice, | .
939     qq|  oe.id AS oe_id | .
940     qq|FROM $arap | .
941     qq|LEFT JOIN shipto s ON | .
942     ($arap eq "ar"
943      ? qq|(ar.shipto_id = s.shipto_id) |
944      : qq|(ap.id = s.trans_id) |) .
945     qq|LEFT JOIN invoice i ON (${arap}.id = i.trans_id) | .
946     qq|LEFT join parts p ON (p.id = i.parts_id) | .
947     qq|LEFT JOIN oe ON (oe.ordnumber = ${arap}.ordnumber AND NOT ${arap}.ordnumber = '') | .
948     $where .
949     qq|ORDER BY ${arap}.transdate DESC LIMIT 15|;
950
951   $form->{DELIVERY} = selectall_hashref_query($form, $dbh, $query, @values);
952
953   $dbh->disconnect;
954
955   $main::lxdebug->leave_sub();
956 }
957
958 sub _save_note {
959   $main::lxdebug->enter_sub();
960
961   my $self   = shift;
962   my %params = @_;
963
964   my $form   = $main::form;
965
966   Common::check_params(\%params, 'dbh');
967
968   if (!$form->{NOTE_subject}) {
969     $main::lxdebug->leave_sub();
970     return;
971   }
972
973   my $dbh = $params{dbh};
974
975   my %follow_up;
976   my %note = (
977     'id'           => $form->{NOTE_id},
978     'subject'      => $form->{NOTE_subject},
979     'body'         => $form->{NOTE_body},
980     'trans_id'     => $form->{id},
981     'trans_module' => 'ct',
982   );
983
984   $note{id} = Notes->save(%note);
985
986   if ($form->{FU_date}) {
987     %follow_up = (
988       'id'               => $form->{FU_id},
989       'note_id'          => $note{id},
990       'follow_up_date'   => $form->{FU_date},
991       'created_for_user' => $form->{FU_created_for_user},
992       'done'             => $form->{FU_done} ? 1 : 0,
993       'subject'          => $form->{NOTE_subject},
994       'body'             => $form->{NOTE_body},
995       'LINKS'            => [
996         {
997           'trans_id'     => $form->{id},
998           'trans_type'   => $form->{db} eq 'customer' ? 'customer' : 'vendor',
999           'trans_info'   => $form->{name},
1000         },
1001       ],
1002     );
1003
1004     $follow_up{id} = FU->save(%follow_up);
1005
1006   } elsif ($form->{FU_id}) {
1007     do_query($form, $dbh, qq|DELETE FROM follow_up_links WHERE follow_up_id = ?|, conv_i($form->{FU_id}));
1008     do_query($form, $dbh, qq|DELETE FROM follow_ups      WHERE id = ?|,           conv_i($form->{FU_id}));
1009   }
1010
1011   delete @{$form}{grep { /^NOTE_|^FU_/ } keys %{ $form }};
1012
1013   $main::lxdebug->leave_sub();
1014 }
1015
1016 sub _delete_selected_notes {
1017   $main::lxdebug->enter_sub();
1018
1019   my $self   = shift;
1020   my %params = @_;
1021
1022   Common::check_params(\%params, 'dbh');
1023
1024   my $form = $main::form;
1025   my $dbh  = $params{dbh};
1026
1027   foreach my $i (1 .. $form->{NOTES_rowcount}) {
1028     next unless ($form->{"NOTE_delete_$i"} && $form->{"NOTE_id_$i"});
1029
1030     Notes->delete('dbh' => $params{dbh},
1031                   'id'  => $form->{"NOTE_id_$i"});
1032   }
1033
1034   $main::lxdebug->leave_sub();
1035 }
1036
1037 sub delete_shipto {
1038   $main::lxdebug->enter_sub();
1039
1040   my $self      = shift;
1041   my $shipto_id = shift;
1042
1043   my $form      = $main::form;
1044   my %myconfig  = %main::myconfig;
1045   my $dbh       = $form->get_standard_dbh(\%myconfig);
1046
1047   do_query($form, $dbh, qq|UPDATE shipto SET trans_id = NULL WHERE shipto_id = ?|, $shipto_id);
1048
1049   $dbh->commit();
1050
1051   $main::lxdebug->leave_sub();
1052 }
1053
1054 sub delete_shipto {
1055   $main::lxdebug->enter_sub();
1056
1057   my $self      = shift;
1058   my $shipto_id = shift;
1059
1060   my $form      = $main::form;
1061   my %myconfig  = %main::myconfig;
1062   my $dbh       = $form->get_standard_dbh(\%myconfig);
1063
1064   do_query($form, $dbh, qq|UPDATE contacts SET cp_cv_id = NULL WHERE cp_id = ?|, $shipto_id);
1065
1066   $dbh->commit();
1067
1068   $main::lxdebug->leave_sub();
1069 }
1070
1071 sub get_bank_info {
1072   $main::lxdebug->enter_sub();
1073
1074   my $self     = shift;
1075   my %params   = @_;
1076
1077   Common::check_params(\%params, qw(vc id));
1078
1079   my $myconfig = \%main::myconfig;
1080   my $form     = $main::form;
1081
1082   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1083
1084   my $table        = $params{vc} eq 'customer' ? 'customer' : 'vendor';
1085   my @ids          = ref $params{id} eq 'ARRAY' ? @{ $params{id} } : ($params{id});
1086   my $placeholders = ('?') x scalar @ids;
1087   my $query        = qq|SELECT id, name, account_number, bank, bank_code, iban, bic
1088                         FROM ${table}
1089                         WHERE id IN (${placeholders})|;
1090
1091   my $result       = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1092
1093   if (ref $params{id} eq 'ARRAY') {
1094     $result = { map { $_->{id} => $_ } @{ $result } };
1095   } else {
1096     $result = $result->[0] || { 'id' => $params{id} };
1097   }
1098
1099   $main::lxdebug->leave_sub();
1100
1101   return $result;
1102 }
1103
1104 1;