1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
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.
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 #======================================================================
31 # Inventory Control backend
33 #======================================================================
38 use List::MoreUtils qw(all any uniq);
43 use SL::HTML::Restrict;
49 $main::lxdebug->enter_sub();
51 my ($self, $myconfig, $form) = @_;
54 my $dbh = $form->get_standard_dbh;
60 c1.accno AS inventory_accno,
61 c2.accno AS income_accno,
62 c3.accno AS expense_accno,
65 LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
66 LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
67 LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
68 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
70 my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
72 # copy to $form variables
73 map { $form->{$_} = $ref->{$_} } (keys %{$ref});
77 # part or service item
78 $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
79 if ($form->{assembly}) {
80 $form->{item} = 'assembly';
82 # retrieve assembly items
84 qq|SELECT p.id, p.partnumber, p.description,
85 p.sellprice, p.lastcost, p.weight, a.qty, a.bom, p.unit,
86 pg.partsgroup, p.price_factor_id, pfac.factor AS price_factor
88 JOIN assembly a ON (a.parts_id = p.id)
89 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
90 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
93 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
95 $form->{assembly_rows} = 0;
96 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
97 $form->{assembly_rows}++;
98 foreach my $key (keys %{$ref}) {
99 $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
106 # setup accno hash for <option checked> {amount} is used in create_links
107 $form->{amount}{IC} = $form->{inventory_accno};
108 $form->{amount}{IC_income} = $form->{income_accno};
109 $form->{amount}{IC_sale} = $form->{income_accno};
110 $form->{amount}{IC_expense} = $form->{expense_accno};
111 $form->{amount}{IC_cogs} = $form->{expense_accno};
115 SELECT pg.pricegroup, pg.id AS pricegroup_id, COALESCE(pr.price, 0) AS price
117 LEFT JOIN prices pr ON (pr.pricegroup_id = pg.id) AND (pr.parts_id = ?)
118 ORDER BY lower(pg.pricegroup)
122 foreach $ref (selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}))) {
123 $form->{"${_}_${row}"} = $ref->{$_} for qw(pricegroup_id pricegroup price);
126 $form->{price_rows} = $row - 1;
129 if ($form->{makemodel}) {
131 $query = qq|SELECT m.make, m.model,m.lastcost,m.lastcost,m.lastupdate,m.sortorder FROM makemodel m | .
132 qq|WHERE m.parts_id = ? order by m.sortorder asc|;
133 my @values = ($form->{id});
134 $sth = $dbh->prepare($query);
135 $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
139 while (($form->{"make_$i"}, $form->{"model_$i"}, $form->{"old_lastcost_$i"},
140 $form->{"lastcost_$i"}, $form->{"lastupdate_$i"}, $form->{"sortorder_$i"}) = $sth->fetchrow_array)
145 $form->{makemodel_rows} = $i - 1;
150 $query = qq|SELECT language_id, translation, longdescription
153 $form->{translations} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
156 my @referencing_tables = qw(invoice orderitems inventory);
157 my %column_map = ( );
158 my $parts_id = conv_i($form->{id});
160 $form->{orphaned} = 1;
162 foreach my $table (@referencing_tables) {
163 my $column = $column_map{$table} || 'parts_id';
164 $query = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
165 my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
168 $form->{orphaned} = 0;
173 $form->{"unit_changeable"} = $form->{orphaned};
175 Common::webdav_folder($form) if $::lx_office_conf{features}{webdav};
177 $main::lxdebug->leave_sub();
180 sub get_pricegroups {
181 $main::lxdebug->enter_sub();
183 my ($self, $myconfig, $form) = @_;
185 my $dbh = $form->get_standard_dbh;
188 my $query = qq|SELECT id, pricegroup FROM pricegroup ORDER BY lower(pricegroup)|;
189 my $pricegroups = selectall_hashref_query($form, $dbh, $query);
192 foreach my $pg (@{ $pricegroups }) {
193 $form->{"klass_$i"} = "$pg->{id}";
194 $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
195 $form->{"pricegroup_id_$i"} = "$pg->{id}";
196 $form->{"pricegroup_$i"} = "$pg->{pricegroup}";
201 $form->{price_rows} = $i - 1;
203 $main::lxdebug->leave_sub();
208 sub retrieve_buchungsgruppen {
209 $main::lxdebug->enter_sub();
211 my ($self, $myconfig, $form) = @_;
215 my $dbh = $form->get_standard_dbh;
217 # get buchungsgruppen
218 $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
219 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
221 $main::lxdebug->leave_sub();
225 $main::lxdebug->enter_sub();
227 my ($self, $myconfig, $form) = @_;
229 # connect to database, turn off AutoCommit
230 my $dbh = $form->get_standard_dbh;
231 my $restricter = SL::HTML::Restrict->create;
234 # make up a unique handle and store in partnumber field
235 # then retrieve the record based on the unique handle to get the id
236 # replace the partnumber field with the actual variable
237 # add records for makemodel
239 # if there is a $form->{id} then replace the old entry
240 # delete all makemodel entries and add the new ones
242 # undo amount formatting
243 map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
244 qw(rop weight listprice sellprice gv lastcost);
246 my $makemodel = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
248 $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
252 my $priceupdate = ', priceupdate = current_date';
255 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
256 if (!$trans_number->is_unique) {
257 $::lxdebug->leave_sub;
262 $query = qq|SELECT sellprice, weight FROM parts WHERE id = ?|;
263 my ($sellprice, $weight) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
265 # if item is part of an assembly adjust all assemblies
266 $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
267 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
268 while (my ($id, $qty) = $sth->fetchrow_array) {
269 &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
273 # delete makemodel records
274 do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
276 if ($form->{item} eq 'assembly') {
277 # delete assembly records
278 do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
281 # delete translations
282 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
284 # Check whether or not the prices have changed. If they haven't
285 # then 'priceupdate' should not be updated.
286 my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
287 $priceupdate = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
290 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, save => 1);
292 if ($form->{partnumber} && !$trans_number->is_unique) {
293 $::lxdebug->leave_sub;
297 $form->{partnumber} ||= $trans_number->create_unique;
299 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
300 do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber, unit) VALUES (?, ?, ?)|, $form->{id}, $form->{partnumber}, $form->{unit});
302 $form->{orphaned} = 1;
304 my $partsgroup_id = undef;
306 if ($form->{partsgroup}) {
307 (my $partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
310 my ($subq_inventory, $subq_expense, $subq_income);
311 if ($form->{"item"} eq "part") {
313 qq|(SELECT bg.inventory_accno_id
314 FROM buchungsgruppen bg
315 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
317 $subq_inventory = "NULL";
320 if ($form->{"item"} ne "assembly") {
322 qq|(SELECT bg.expense_accno_id_0
323 FROM buchungsgruppen bg
324 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
326 $subq_expense = "NULL";
329 normalize_text_blocks();
348 buchungsgruppen_id = ?,
350 inventory_accno_id = $subq_inventory,
351 income_accno_id = (SELECT bg.income_accno_id_0 FROM buchungsgruppen bg WHERE bg.id = ?),
352 expense_accno_id = $subq_expense,
361 not_discountable = ?,
367 @values = ($form->{partnumber},
368 $form->{description},
369 $makemodel ? 't' : 'f',
370 $form->{assembly} ? 't' : 'f',
376 $restricter->process($form->{notes}),
379 conv_i($form->{warehouse_id}),
380 conv_i($form->{bin_id}),
381 conv_i($form->{buchungsgruppen_id}),
382 conv_i($form->{payment_id}),
383 conv_i($form->{buchungsgruppen_id}),
384 $form->{obsolete} ? 't' : 'f',
387 $form->{shop} ? 't' : 'f',
391 $form->{has_sernumber} ? 't' : 'f',
392 $form->{not_discountable} ? 't' : 'f',
394 conv_i($partsgroup_id),
395 conv_i($form->{price_factor_id}),
398 do_query($form, $dbh, $query, @values);
400 # delete translation records
401 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
403 my @translations = grep { $_->{language_id} && $_->{translation} } @{ $form->{translations} || [] };
405 $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
406 VALUES ( ?, ?, ?, ? )|;
407 $sth = $dbh->prepare($query);
409 foreach my $translation (@translations) {
410 do_statement($form, $sth, $query, conv_i($form->{id}), conv_i($translation->{language_id}), $translation->{translation}, $restricter->process($translation->{longdescription}));
416 # delete price records
417 do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
419 $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) VALUES(?, ?, ?)|;
420 $sth = prepare_query($form, $dbh, $query);
422 # insert price records only if different to sellprice
423 for my $i (1 .. $form->{price_rows}) {
424 my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
425 next unless $price && ($price != $form->{sellprice});
427 @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
428 do_statement($form, $sth, $query, @values);
433 # insert makemodel records
436 for my $i (1 .. $form->{makemodel_rows}) {
437 if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
439 $value = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
440 if ($value == $form->parse_amount($myconfig, $form->{"old_lastcost_$i"}))
442 if ($form->{"lastupdate_$i"} eq "") {
443 $lastupdate = 'now()';
445 $lastupdate = $dbh->quote($form->{"lastupdate_$i"});
448 $lastupdate = 'now()';
450 $query = qq|INSERT INTO makemodel (parts_id, make, model, lastcost, lastupdate, sortorder) | .
451 qq|VALUES (?, ?, ?, ?, ?, ?)|;
452 @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"}, $value, $lastupdate, conv_i($form->{"sortorder_$i"}) );
454 do_query($form, $dbh, $query, @values);
458 # add assembly records
459 if ($form->{item} eq 'assembly') {
460 # check additional assembly row
461 my $i = $form->{assembly_rows};
462 # if last row is not empty add them
463 if ($form->{"partnumber_$i"} ne "") {
464 $query = qq|SELECT id FROM parts WHERE partnumber = ?|;
465 my ($partid) = selectrow_query($form, $dbh, $query,$form->{"partnumber_$i"} );
467 $form->{"qty_$i"} = 1 unless ($form->{"qty_$i"});
468 $form->{"id_$i"} = $partid;
469 $form->{"bom_$i"} = 0;
470 $form->{assembly_rows}++;
473 $::form->error($::locale->text("uncorrect partnumber ").$form->{"partnumber_$i"});
477 for my $i (1 .. $form->{assembly_rows}) {
478 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
480 if ($form->{"qty_$i"} != 0) {
481 $form->{"bom_$i"} *= 1;
482 $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
483 qq|VALUES (?, ?, ?, ?)|;
484 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
485 do_query($form, $dbh, $query, @values);
491 my $shippingdate = "$a[5]-$a[4]-$a[3]";
493 $form->get_employee($dbh);
497 #set expense_accno=inventory_accno if they are different => bilanz
499 ($form->{expense_accno} != $form->{inventory_accno})
500 ? $form->{inventory_accno}
501 : $form->{expense_accno};
503 # get tax rates and description
505 ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
507 qq|SELECT c.accno, c.description, t.rate, t.taxnumber
509 WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
511 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
513 $form->{taxaccount} = "";
514 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
515 $form->{taxaccount} .= "$ptr->{accno} ";
516 if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
517 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
518 $form->{"$ptr->{accno}_description"} = $ptr->{description};
519 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
520 $form->{taxaccount2} .= " $ptr->{accno} ";
524 CVar->save_custom_variables(dbh => $dbh,
526 trans_id => $form->{id},
531 my $rc = $dbh->commit;
533 $main::lxdebug->leave_sub();
538 sub update_assembly {
539 $main::lxdebug->enter_sub();
541 my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
543 my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
544 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
546 while (my ($pid, $aqty) = $sth->fetchrow_array) {
547 &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
552 qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
554 my @values = ($qty * ($form->{sellprice} - $sellprice),
555 $qty * ($form->{weight} - $weight), conv_i($id));
556 do_query($form, $dbh, $query, @values);
558 $main::lxdebug->leave_sub();
561 sub retrieve_assemblies {
562 $main::lxdebug->enter_sub();
564 my ($self, $myconfig, $form) = @_;
566 # connect to database
567 my $dbh = $form->get_standard_dbh;
569 my $where = qq|NOT p.obsolete|;
572 if ($form->{partnumber}) {
573 $where .= qq| AND (p.partnumber ILIKE ?)|;
574 push(@values, '%' . $form->{partnumber} . '%');
577 if ($form->{description}) {
578 $where .= qq| AND (p.description ILIKE ?)|;
579 push(@values, '%' . $form->{description} . '%');
582 # retrieve assembly items
584 qq|SELECT p.id, p.partnumber, p.description,
586 (SELECT sum(p2.inventory_accno_id)
587 FROM parts p2, assembly a
588 WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
590 WHERE NOT p.obsolete AND p.assembly $where|;
592 $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
594 $main::lxdebug->leave_sub();
598 $main::lxdebug->enter_sub();
600 my ($self, $myconfig, $form) = @_;
601 my @values = (conv_i($form->{id}));
602 # connect to database, turn off AutoCommit
603 my $dbh = $form->get_standard_dbh;
605 my %columns = ( "assembly" => "id", "parts" => "id" );
607 for my $table (qw(prices makemodel inventory assembly translation parts)) {
608 my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
609 do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
613 my $rc = $dbh->commit;
615 $main::lxdebug->leave_sub();
621 $main::lxdebug->enter_sub();
623 my ($self, $myconfig, $form) = @_;
625 my $i = $form->{assembly_rows};
627 my $where = qq|1 = 1|;
630 my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
632 while (my ($column, $table) = each(%columns)) {
633 next unless ($form->{"${column}_$i"});
634 $where .= qq| AND ${table}.${column} ILIKE ?|;
635 push(@values, '%' . $form->{"${column}_$i"} . '%');
639 $where .= qq| AND NOT (p.id = ?)|;
640 push(@values, conv_i($form->{id}));
643 # Search for part ID overrides all other criteria.
644 if ($form->{"id_${i}"}) {
645 $where = qq|p.id = ?|;
646 @values = ($form->{"id_${i}"});
649 if ($form->{partnumber}) {
650 $where .= qq| ORDER BY p.partnumber|;
652 $where .= qq| ORDER BY p.description|;
655 # connect to database
656 my $dbh = $form->get_standard_dbh;
659 qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
660 p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
661 p.price_factor_id, pfac.factor AS price_factor
663 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
664 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
666 $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
668 $main::lxdebug->leave_sub();
673 # Warning, deep magic ahead.
674 # This function gets all parts from the database according to the filters specified
677 # sort revers - sorting field + direction
680 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
681 # partnumber ean description partsgroup microfiche drawing
684 # l_partnumber l_description l_listprice l_sellprice l_lastcost l_priceupdate l_weight l_unit l_rop l_image l_drawing l_microfiche l_partsgroup
687 # itemstatus = active | onhand | short | obsolete | orphaned
688 # searchitems = part | assembly | service
691 # make model - makemodel
692 # serialnumber transdatefrom transdateto - invoice/orderitems
695 # bought sold onorder ordered rfq quoted - aggreg joins with invoices/orders
696 # l_linetotal l_subtotal - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
697 # l_soldtotal - aggreg join to display total of sold quantity
698 # onhand - as above, but masking the simple itemstatus results (doh!)
699 # short - NOT IMPLEMENTED as form filter, only as itemstatus option
700 # l_serialnumber - belonges to serialnumber filter
701 # l_deliverydate - displays deliverydate is sold etc. flags are active
702 # l_soldtotal - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
705 # onhand - as above, but masking the simple itemstatus results (doh!)
707 # search by overrides of description
709 # disabled sanity checks and changes:
710 # - searchitems = assembly will no longer disable bought
711 # - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
712 # - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
713 # - itemstatus = obsolete will no longer disable onhand, short
714 # - allow sorting by ean
715 # - serialnumber filter also works if l_serialnumber isn't ticked
716 # - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
719 $main::lxdebug->enter_sub();
721 my ($self, $myconfig, $form) = @_;
722 my $dbh = $form->get_standard_dbh($myconfig);
724 $form->{parts} = +{ };
725 $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
727 my @simple_filters = qw(partnumber ean description partsgroup microfiche drawing onhand);
728 my @project_filters = qw(projectnumber projectdescription);
729 my @makemodel_filters = qw(make model);
730 my @invoice_oi_filters = qw(serialnumber soldtotal);
731 my @apoe_filters = qw(transdate);
732 my @like_filters = (@simple_filters, @invoice_oi_filters);
733 my @all_columns = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
734 my @simple_l_switches = (@all_columns, qw(notes listprice sellprice lastcost priceupdate weight unit rop image));
735 my @oe_flags = qw(bought sold onorder ordered rfq quoted);
736 my @qsooqr_flags = qw(invnumber ordnumber quonumber trans_id name module qty);
737 my @deliverydate_flags = qw(deliverydate);
738 # my @other_flags = qw(onhand); # ToDO: implement these
739 # my @inactive_flags = qw(l_subtotal short l_linetotal);
741 my @select_tokens = qw(id factor);
742 my @where_tokens = qw(1=1);
743 my @group_tokens = ();
745 my %joins_needed = ();
748 partsgroup => 'LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)',
749 makemodel => 'LEFT JOIN makemodel mm ON (mm.parts_id = p.id)',
750 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
753 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, project_id, id FROM invoice UNION
754 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
755 ) AS ioi ON ioi.parts_id = p.id|,
758 SELECT id, transdate, 'ir' AS module, ordnumber, quonumber, invnumber, FALSE AS quotation, NULL AS customer_id, vendor_id, NULL AS deliverydate, globalproject_id, 'invoice' AS ioi FROM ap UNION
759 SELECT id, transdate, 'is' AS module, ordnumber, quonumber, invnumber, FALSE AS quotation, customer_id, NULL AS vendor_id, deliverydate, globalproject_id, 'invoice' AS ioi FROM ar UNION
760 SELECT id, transdate, 'oe' AS module, ordnumber, quonumber, NULL AS invnumber, quotation, customer_id, vendor_id, reqdate AS deliverydate, globalproject_id, 'orderitems' AS ioi FROM oe
761 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
764 SELECT id, name, 'customer' AS cv FROM customer UNION
765 SELECT id, name, 'vendor' AS cv FROM vendor
766 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
767 mv => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
768 project => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
770 my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project);
773 deliverydate => 'apoe.', serialnumber => 'ioi.',
774 transdate => 'apoe.', trans_id => 'ioi.',
775 module => 'apoe.', name => 'cv.',
776 ordnumber => 'apoe.', make => 'mm.',
777 quonumber => 'apoe.', model => 'mm.',
778 invnumber => 'apoe.', partsgroup => 'pg.',
779 lastcost => 'p.', , soldtotal => ' ',
780 factor => 'pfac.', projectnumber => 'pj.',
781 'SUM(ioi.qty)' => ' ', projectdescription => 'pj.',
784 serialnumber => 'ioi.',
785 quotation => 'apoe.',
791 # if the join condition in these blocks are met, the column
792 # of the scecified table will gently override (coalesce actually) the original value
793 # use it to conditionally coalesce values from subtables
794 my @column_override = (
795 # column name, prefix, joins_needed, nick name (in case column is named like another)
796 [ 'description', 'ioi.', 'invoice_oi' ],
797 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
798 [ 'transdate', 'apoe.', 'apoe' ],
799 [ 'unit', 'ioi.', 'invoice_oi' ],
800 [ 'sellprice', 'ioi.', 'invoice_oi' ],
803 # careful with renames. these are HARD, and any filters done on the original column will break
804 my %renamed_columns = (
805 'factor' => 'price_factor',
806 'SUM(ioi.qty)' => 'soldtotal',
807 'ioi.id' => 'ioi_id',
809 'projectdescription' => 'projectdescription',
813 projectdescription => 'description',
816 if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
817 @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
820 my $make_token_builder = sub {
821 my $joins_needed = shift;
823 my ($nick, $alias) = @_;
824 my ($col) = $real_column{$nick} || $nick;
825 my @coalesce_tokens =
826 map { ($_->[1] || 'p.') . $_->[0] }
827 grep { !$_->[2] || $joins_needed->{$_->[2]} }
828 grep { ($_->[3] || $_->[0]) eq $nick }
829 @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
831 my $coalesce = scalar @coalesce_tokens > 1;
833 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
834 : shift @coalesce_tokens)
835 . ($alias && ($coalesce || $renamed_columns{$nick})
836 ? " AS " . ($renamed_columns{$nick} || $nick)
841 #===== switches and simple filters ========#
843 # special case transdate
844 if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
845 $form->{"l_transdate"} = 1;
846 push @select_tokens, 'transdate';
847 for (qw(transdatefrom transdateto)) {
848 next unless $form->{$_};
849 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
850 push @bind_vars, $form->{$_};
854 if ($form->{"partsgroup_id"}) {
855 $form->{"l_partsgroup"} = '1'; # show the column
856 push @where_tokens, "pg.id = ?";
857 push @bind_vars, $form->{"partsgroup_id"};
860 foreach (@like_filters) {
861 next unless $form->{$_};
862 $form->{"l_$_"} = '1'; # show the column
863 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
864 push @bind_vars, "%$form->{$_}%";
867 foreach (@simple_l_switches) {
868 next unless $form->{"l_$_"};
869 push @select_tokens, $_;
872 for ($form->{searchitems}) {
873 push @where_tokens, 'p.inventory_accno_id > 0' if /part/;
874 push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
875 push @where_tokens, 'NOT p.assembly' if /service/;
876 push @where_tokens, ' p.assembly' if /assembly/;
879 for ($form->{itemstatus}) {
880 push @where_tokens, 'p.id NOT IN
881 (SELECT DISTINCT parts_id FROM invoice UNION
882 SELECT DISTINCT parts_id FROM assembly UNION
883 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
884 push @where_tokens, 'p.onhand = 0' if /orphaned/;
885 push @where_tokens, 'NOT p.obsolete' if /active/;
886 push @where_tokens, ' p.obsolete', if /obsolete/;
887 push @where_tokens, 'p.onhand > 0', if /onhand/;
888 push @where_tokens, 'p.onhand < p.rop', if /short/;
891 my $q_assembly_lastcost =
892 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
894 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
895 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
896 WHERE (a_lc.id = p.id)) AS lastcost|;
897 $table_prefix{$q_assembly_lastcost} = ' ';
899 # special case makemodel search
900 # all_parts is based upon the assumption that every parameter is named like the column it represents
901 # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
902 # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
904 push @where_tokens, 'mv.name ILIKE ?';
905 push @bind_vars, "%$form->{make}%";
907 if ($form->{model}) {
908 push @where_tokens, 'mm.model ILIKE ?';
909 push @bind_vars, "%$form->{model}%";
912 # special case: sorting by partnumber
913 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
914 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
915 # ToDO: implement proper functional sorting
916 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
917 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
918 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
919 # if $form->{sort} eq 'partnumber';
921 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
924 $limit_clause = " LIMIT 100" if $form->{top100};
925 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
927 #=== joins and complicated filters ========#
929 my $bsooqr = any { $form->{$_} } @oe_flags;
930 my @bsooqr_tokens = ();
932 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
933 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
934 push @select_tokens, $q_assembly_lastcost if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
935 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
936 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
937 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
938 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
939 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
940 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
941 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
943 $joins_needed{partsgroup} = 1;
944 $joins_needed{pfac} = 1;
945 $joins_needed{project} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
946 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
947 $joins_needed{mv} = 1 if $joins_needed{makemodel};
948 $joins_needed{cv} = 1 if $bsooqr;
949 $joins_needed{apoe} = 1 if $joins_needed{project} || $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
950 $joins_needed{invoice_oi} = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
952 # special case for description search.
953 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
954 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
955 # find the old entries in of @where_tokens and @bind_vars, and adjust them
956 if ($joins_needed{invoice_oi}) {
957 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
958 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
959 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
960 splice @bind_vars, $bi, 0, $bind_vars[$bi];
965 # now the master trick: soldtotal.
966 if ($form->{l_soldtotal}) {
967 push @where_tokens, 'NOT ioi.qty = 0';
968 push @group_tokens, @select_tokens;
969 map { s/.*\sAS\s+//si } @group_tokens;
970 push @select_tokens, 'SUM(ioi.qty)';
973 #============= build query ================#
975 my $token_builder = $make_token_builder->(\%joins_needed);
977 my @sort_cols = (@simple_filters, qw(id priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
978 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
979 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
980 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
982 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
983 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
984 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
985 my $group_clause = @group_tokens ? ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens : '';
987 my %oe_flag_to_cvar = (
990 onorder => 'orderitems',
991 ordered => 'orderitems',
993 quoted => 'orderitems',
996 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
998 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
1000 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
1004 $where_clause .= qq| AND ($cvar_where)|;
1005 push @bind_vars, @cvar_values;
1008 my $query = <<" SQL";
1009 SELECT DISTINCT $select_clause
1018 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1020 map { $_->{onhand} *= 1 } @{ $form->{parts} };
1022 # fix qty sign in ap. those are saved negative
1023 if ($bsooqr && $form->{bought}) {
1024 for my $row (@{ $form->{parts} }) {
1025 $row->{qty} *= -1 if $row->{module} eq 'ir';
1029 # post processing for assembly parts lists (bom)
1030 # for each part get the assembly parts and add them into the partlist.
1032 if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1034 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1036 p.sellprice, p.listprice, p.lastcost,
1037 p.rop, p.weight, p.priceupdate,
1038 p.image, p.drawing, p.microfiche,
1041 INNER JOIN assembly a ON (p.id = a.parts_id)
1044 my $sth = prepare_query($form, $dbh, $query);
1046 foreach my $item (@{ $form->{parts} }) {
1047 push(@assemblies, $item);
1048 do_statement($form, $sth, $query, conv_i($item->{id}));
1050 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1051 $ref->{assemblyitem} = 1;
1052 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1053 push(@assemblies, $ref);
1058 # copy assemblies to $form->{parts}
1059 $form->{parts} = \@assemblies;
1062 if ($form->{l_pricegroups} ) {
1064 SELECT parts_id, price, pricegroup_id
1069 my $sth = prepare_query($form, $dbh, $query);
1071 foreach my $part (@{ $form->{parts} }) {
1072 do_statement($form, $sth, $query, conv_i($part->{id}));
1074 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1075 $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
1082 $main::lxdebug->leave_sub();
1084 return wantarray ? @{ $form->{parts} } : $form->{parts};
1087 sub _create_filter_for_priceupdate {
1088 $main::lxdebug->enter_sub();
1091 my $myconfig = \%main::myconfig;
1092 my $form = $main::form;
1095 my $where = '1 = 1';
1097 foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1099 $column =~ s/.*\.//;
1100 next unless ($form->{$column});
1102 $where .= qq| AND $item ILIKE ?|;
1103 push(@where_values, '%' . $form->{$column} . '%');
1106 foreach my $item (qw(description serialnumber)) {
1107 next unless ($form->{$item});
1109 $where .= qq| AND (${item} ILIKE ?)|;
1110 push(@where_values, '%' . $form->{$item} . '%');
1114 # items which were never bought, sold or on an order
1115 if ($form->{itemstatus} eq 'orphaned') {
1117 qq| AND (p.onhand = 0)
1120 SELECT DISTINCT parts_id FROM invoice
1122 SELECT DISTINCT parts_id FROM assembly
1124 SELECT DISTINCT parts_id FROM orderitems
1127 } elsif ($form->{itemstatus} eq 'active') {
1128 $where .= qq| AND p.obsolete = '0'|;
1130 } elsif ($form->{itemstatus} eq 'obsolete') {
1131 $where .= qq| AND p.obsolete = '1'|;
1133 } elsif ($form->{itemstatus} eq 'onhand') {
1134 $where .= qq| AND p.onhand > 0|;
1136 } elsif ($form->{itemstatus} eq 'short') {
1137 $where .= qq| AND p.onhand < p.rop|;
1141 foreach my $column (qw(make model)) {
1142 next unless ($form->{$column});
1143 $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1144 push(@where_values, '%' . $form->{$column} . '%');
1147 $main::lxdebug->leave_sub();
1149 return ($where, @where_values);
1152 sub get_num_matches_for_priceupdate {
1153 $main::lxdebug->enter_sub();
1157 my $myconfig = \%main::myconfig;
1158 my $form = $main::form;
1160 my $dbh = $form->get_standard_dbh($myconfig);
1162 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1164 my $num_updated = 0;
1167 for my $column (qw(sellprice listprice)) {
1168 next if ($form->{$column} eq "");
1176 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1178 my ($result) = selectfirst_array_query($form, $dbh, $query, @where_values);
1179 $num_updated += $result if (0 <= $result);
1188 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1189 WHERE $where) AND (pricegroup_id = ?)|;
1190 my $sth = prepare_query($form, $dbh, $query);
1192 for my $i (1 .. $form->{price_rows}) {
1193 next if ($form->{"price_$i"} eq "");
1195 my ($result) = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1196 $num_updated += $result if (0 <= $result);
1200 $main::lxdebug->leave_sub();
1202 return $num_updated;
1206 $main::lxdebug->enter_sub();
1208 my ($self, $myconfig, $form) = @_;
1210 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1211 my $num_updated = 0;
1213 # connect to database
1214 my $dbh = $form->get_standard_dbh;
1216 for my $column (qw(sellprice listprice)) {
1217 next if ($form->{$column} eq "");
1219 my $value = $form->parse_amount($myconfig, $form->{$column});
1222 if ($form->{"${column}_type"} eq "percent") {
1223 $value = ($value / 100) + 1;
1228 qq|UPDATE parts SET $column = $column $operator ?
1232 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1234 my $result = do_query($form, $dbh, $query, $value, @where_values);
1235 $num_updated += $result if (0 <= $result);
1239 qq|UPDATE prices SET price = price + ?
1243 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1244 WHERE $where) AND (pricegroup_id = ?)|;
1245 my $sth_add = prepare_query($form, $dbh, $q_add);
1248 qq|UPDATE prices SET price = price * ?
1252 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1253 WHERE $where) AND (pricegroup_id = ?)|;
1254 my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1256 for my $i (1 .. $form->{price_rows}) {
1257 next if ($form->{"price_$i"} eq "");
1259 my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1262 if ($form->{"pricegroup_type_$i"} eq "percent") {
1263 $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1265 $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1268 $num_updated += $result if (0 <= $result);
1272 $sth_multiply->finish();
1274 my $rc= $dbh->commit;
1276 $main::lxdebug->leave_sub();
1278 return $num_updated;
1282 $main::lxdebug->enter_sub();
1284 my ($self, $module, $myconfig, $form) = @_;
1286 # connect to database
1287 my $dbh = $form->get_standard_dbh;
1289 my @values = ('%' . $module . '%');
1294 qq|SELECT c.accno, c.description, c.link, c.id,
1295 p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1296 FROM chart c, parts p
1297 WHERE (c.link LIKE ?) AND (p.id = ?)
1299 push(@values, conv_i($form->{id}));
1303 qq|SELECT c.accno, c.description, c.link, c.id,
1304 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1305 FROM chart c, defaults d
1310 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1311 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1312 foreach my $key (split(/:/, $ref->{link})) {
1313 if ($key =~ /\Q$module\E/) {
1314 if ( ($ref->{id} eq $ref->{inventory_accno_id})
1315 || ($ref->{id} eq $ref->{income_accno_id})
1316 || ($ref->{id} eq $ref->{expense_accno_id})) {
1317 push @{ $form->{"${module}_links"}{$key} },
1318 { accno => $ref->{accno},
1319 description => $ref->{description},
1320 selected => "selected" };
1321 $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1323 push @{ $form->{"${module}_links"}{$key} },
1324 { accno => $ref->{accno},
1325 description => $ref->{description},
1333 # get buchungsgruppen
1334 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1337 $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1340 ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1343 $main::lxdebug->leave_sub();
1346 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1348 $main::lxdebug->enter_sub();
1350 my ($self, $myconfig, $form, $sortorder) = @_;
1351 my $dbh = $form->get_standard_dbh;
1352 my $order = qq| p.partnumber|;
1353 my $where = qq|1 = 1|;
1356 if ($sortorder eq "all") {
1357 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1358 push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1360 } elsif ($sortorder eq "partnumber") {
1361 $where .= qq| AND (partnumber ILIKE ?)|;
1362 push(@values, '%' . $form->{partnumber} . '%');
1364 } elsif ($sortorder eq "description") {
1365 $where .= qq| AND (description ILIKE ?)|;
1366 push(@values, '%' . $form->{description} . '%');
1367 $order = "description";
1372 qq|SELECT id, partnumber, description, unit, sellprice
1374 WHERE $where ORDER BY $order|;
1376 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1379 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1380 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1385 $form->{"id_$j"} = $ref->{id};
1386 $form->{"partnumber_$j"} = $ref->{partnumber};
1387 $form->{"description_$j"} = $ref->{description};
1388 $form->{"unit_$j"} = $ref->{unit};
1389 $form->{"sellprice_$j"} = $ref->{sellprice};
1390 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
1395 $main::lxdebug->leave_sub();
1400 # gets sum of sold part with part_id
1402 $main::lxdebug->enter_sub();
1404 my ($dbh, $id) = @_;
1406 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1407 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1410 $main::lxdebug->leave_sub();
1413 } #end get_soldtotal
1415 sub retrieve_languages {
1416 $main::lxdebug->enter_sub();
1418 my ($self, $myconfig, $form) = @_;
1420 # connect to database
1421 my $dbh = $form->get_standard_dbh;
1427 if ($form->{language_values} ne "") {
1429 qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1431 LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1432 ORDER BY lower(l.description)|;
1433 @values = (conv_i($form->{id}));
1436 $query = qq|SELECT id, description
1438 ORDER BY lower(description)|;
1441 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1443 $main::lxdebug->leave_sub();
1448 sub follow_account_chain {
1449 $main::lxdebug->enter_sub(2);
1451 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1453 my @visited_accno_ids = ($accno_id);
1457 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
1458 map { $_->{id} => $_ }
1459 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
1460 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
1462 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
1463 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
1467 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
1468 last unless ($ref && $ref->{"is_valid"} &&
1469 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1470 $accno_id = $ref->{"new_chart_id"};
1471 $accno = $ref->{"accno"};
1472 push(@visited_accno_ids, $accno_id);
1475 $main::lxdebug->leave_sub(2);
1477 return ($accno_id, $accno);
1480 sub retrieve_accounts {
1481 $main::lxdebug->enter_sub;
1484 my $myconfig = shift;
1486 my $dbh = $form->get_standard_dbh;
1487 my %args = @_; # index => part_id
1489 $form->{taxzone_id} *= 1;
1491 return unless grep $_, values %args; # shortfuse if no part_id supplied
1493 # transdate madness.
1495 if ($form->{type} eq "invoice" or $form->{type} eq "credit_note") {
1496 # use deliverydate for sales and purchase invoice, if it exists
1497 # also use deliverydate for credit notes
1498 if (!$form->{deliverydate}) {
1499 $transdate = $form->{invdate};
1501 $transdate = $form->{deliverydate};
1503 } elsif ($form->{script} eq 'ir.pl') {
1504 # when a purchase invoice is opened from the report of purchase invoices
1505 # $form->{type} isn't set, but $form->{script} is, not sure why this is or
1506 # whether this distinction matters in some other scenario. Otherwise one
1507 # could probably take out this elsif and add a
1508 # " or $form->{script} eq 'ir.pl' "
1509 # to the above if-statement
1510 if (!$form->{deliverydate}) {
1511 $transdate = $form->{invdate};
1513 $transdate = $form->{deliverydate};
1515 } elsif (($form->{type} eq "credit_note") and $form->{deliverydate}) {
1516 # if credit_note has a deliverydate, use this instead of invdate
1517 # useful for credit_notes of invoices from an old period with different tax
1518 # if there is no deliverydate then invdate is used, old default (see next elsif)
1519 # Falls hier der Stichtag für Steuern anders bestimmt wird,
1520 # entsprechend auch bei Taxkeys.pm anpassen
1521 $transdate = $form->{deliverydate};
1522 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1523 $transdate = $form->{invdate};
1525 $transdate = $form->{transdate};
1528 if ($transdate eq "") {
1529 $transdate = DateTime->today_local->to_lxoffice;
1531 $transdate = $dbh->quote($transdate);
1534 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
1536 my @part_ids = grep { $_ } values %args;
1537 my $in = join ',', ('?') x @part_ids;
1539 my %accno_by_part = map { $_->{id} => $_ }
1540 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
1542 p.id, p.inventory_accno_id AS is_part,
1543 bg.inventory_accno_id,
1544 bg.income_accno_id_$form->{taxzone_id} AS income_accno_id,
1545 bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id,
1546 c1.accno AS inventory_accno,
1547 c2.accno AS income_accno,
1548 c3.accno AS expense_accno
1550 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
1551 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1552 LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id
1553 LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id
1557 my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1558 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1560 LEFT JOIN chart c ON c.id = t.chart_id
1564 WHERE tk.chart_id = ? AND startdate <= ?
1565 ORDER BY startdate DESC LIMIT 1)
1568 while (my ($index => $part_id) = each %args) {
1569 my $ref = $accno_by_part{$part_id} or next;
1571 $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
1574 for my $type (qw(inventory income expense)) {
1575 next unless $ref->{"${type}_accno_id"};
1576 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1577 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1580 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1582 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1583 $ref = $sth_tax->fetchrow_hashref or next;
1585 $form->{"taxaccounts_$index"} = $ref->{"accno"};
1586 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1588 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1593 $::lxdebug->leave_sub;
1596 sub get_basic_part_info {
1597 $main::lxdebug->enter_sub();
1602 Common::check_params(\%params, qw(id));
1604 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1607 $main::lxdebug->leave_sub();
1611 my $myconfig = \%main::myconfig;
1612 my $form = $main::form;
1614 my $dbh = $form->get_standard_dbh($myconfig);
1616 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1618 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1620 if ('' eq ref $params{id}) {
1621 $info = $info->[0] || { };
1623 $main::lxdebug->leave_sub();
1627 my %info_map = map { $_->{id} => $_ } @{ $info };
1629 $main::lxdebug->leave_sub();
1634 sub prepare_parts_for_printing {
1635 $main::lxdebug->enter_sub();
1640 my $myconfig = $params{myconfig} || \%main::myconfig;
1641 my $form = $params{form} || $main::form;
1643 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1645 my $prefix = $params{prefix} || 'id_';
1646 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1648 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1651 $main::lxdebug->leave_sub();
1655 my $placeholders = join ', ', ('?') x scalar(@part_ids);
1656 my $query = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
1658 LEFT JOIN vendor v ON (mm.make = v.id)
1659 WHERE mm.parts_id IN ($placeholders)|;
1663 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
1665 while (my $ref = $sth->fetchrow_hashref()) {
1666 $makemodel{$ref->{parts_id}} ||= [];
1667 push @{ $makemodel{$ref->{parts_id}} }, $ref;
1672 my @columns = qw(ean image microfiche drawing weight);
1674 $query = qq|SELECT id, | . join(', ', @columns) . qq|
1676 WHERE id IN ($placeholders)|;
1678 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1680 map { $form->{TEMPLATE_ARRAYS}{$_} = [] } (qw(make model), @columns);
1682 foreach my $i (1 .. $rowcount) {
1683 my $id = $form->{"${prefix}${i}"};
1687 foreach (@columns) {
1688 push @{ $form->{TEMPLATE_ARRAYS}{$_} }, $data{$id}->{$_};
1691 push @{ $form->{TEMPLATE_ARRAYS}{make} }, [];
1692 push @{ $form->{TEMPLATE_ARRAYS}{model} }, [];
1694 next if (!$makemodel{$id});
1696 foreach my $ref (@{ $makemodel{$id} }) {
1697 map { push @{ $form->{TEMPLATE_ARRAYS}{$_}->[-1] }, $ref->{$_} } qw(make model);
1701 $main::lxdebug->leave_sub();
1704 sub normalize_text_blocks {
1705 $main::lxdebug->enter_sub();
1710 my $form = $params{form} || $main::form;
1712 # check if feature is enabled (select normalize_part_descriptions from defaults)
1713 return unless ($::instance_conf->get_normalize_part_descriptions);
1715 foreach (qw(description notes)) {
1716 $form->{$_} =~ s/\s+$//s;
1717 $form->{$_} =~ s/^\s+//s;
1718 $form->{$_} =~ s/ {2,}/ /g;
1720 $main::lxdebug->leave_sub();