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