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