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;
45 use SL::Util qw(trim);
50 $main::lxdebug->enter_sub();
52 my ($self, $myconfig, $form) = @_;
55 my $dbh = $form->get_standard_dbh;
61 c1.accno AS inventory_accno,
62 c2.accno AS income_accno,
63 c3.accno AS expense_accno,
66 LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
67 LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
68 LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
69 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
71 my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
73 # copy to $form variables
74 map { $form->{$_} = $ref->{$_} } (keys %{$ref});
76 $form->{mtime} = $form->{itime} if !$form->{mtime};
77 $form->{lastmtime} = $form->{mtime};
80 # part or service item
81 $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
82 if ($form->{assembly}) {
83 $form->{item} = 'assembly';
85 # retrieve assembly items
87 qq|SELECT p.id, p.partnumber, p.description,
88 p.sellprice, p.lastcost, p.weight, a.qty, a.bom, p.unit,
89 pg.partsgroup, p.price_factor_id, pfac.factor AS price_factor
91 JOIN assembly a ON (a.parts_id = p.id)
92 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
93 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
96 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
98 $form->{assembly_rows} = 0;
99 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
100 $form->{assembly_rows}++;
101 foreach my $key (keys %{$ref}) {
102 $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
109 # setup accno hash for <option checked> {amount} is used in create_links
110 $form->{amount}{IC} = $form->{inventory_accno};
111 $form->{amount}{IC_income} = $form->{income_accno};
112 $form->{amount}{IC_sale} = $form->{income_accno};
113 $form->{amount}{IC_expense} = $form->{expense_accno};
114 $form->{amount}{IC_cogs} = $form->{expense_accno};
118 SELECT pg.pricegroup, pg.id AS pricegroup_id, COALESCE(pr.price, 0) AS price
120 LEFT JOIN prices pr ON (pr.pricegroup_id = pg.id) AND (pr.parts_id = ?)
121 ORDER BY lower(pg.pricegroup)
125 foreach $ref (selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}))) {
126 $form->{"${_}_${row}"} = $ref->{$_} for qw(pricegroup_id pricegroup price);
129 $form->{price_rows} = $row - 1;
132 if ($form->{makemodel}) {
134 $query = qq|SELECT m.make, m.model,m.lastcost,m.lastcost,m.lastupdate,m.sortorder FROM makemodel m | .
135 qq|WHERE m.parts_id = ? order by m.sortorder asc|;
136 my @values = ($form->{id});
137 $sth = $dbh->prepare($query);
138 $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
142 while (($form->{"make_$i"}, $form->{"model_$i"}, $form->{"old_lastcost_$i"},
143 $form->{"lastcost_$i"}, $form->{"lastupdate_$i"}, $form->{"sortorder_$i"}) = $sth->fetchrow_array)
148 $form->{makemodel_rows} = $i - 1;
153 $query = qq|SELECT language_id, translation, longdescription
156 $form->{translations} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
159 my @referencing_tables = qw(invoice orderitems inventory);
160 my %column_map = ( );
161 my $parts_id = conv_i($form->{id});
163 $form->{orphaned} = 1;
165 foreach my $table (@referencing_tables) {
166 my $column = $column_map{$table} || 'parts_id';
167 $query = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
168 my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
171 $form->{orphaned} = 0;
176 $form->{"unit_changeable"} = $form->{orphaned};
178 Common::webdav_folder($form) if $::lx_office_conf{features}{webdav};
180 $main::lxdebug->leave_sub();
183 sub get_pricegroups {
184 $main::lxdebug->enter_sub();
186 my ($self, $myconfig, $form) = @_;
188 my $dbh = $form->get_standard_dbh;
191 my $query = qq|SELECT id, pricegroup FROM pricegroup ORDER BY lower(pricegroup)|;
192 my $pricegroups = selectall_hashref_query($form, $dbh, $query);
195 foreach my $pg (@{ $pricegroups }) {
196 $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
197 $form->{"pricegroup_id_$i"} = "$pg->{id}";
198 $form->{"pricegroup_$i"} = "$pg->{pricegroup}";
203 $form->{price_rows} = $i - 1;
205 $main::lxdebug->leave_sub();
210 sub retrieve_buchungsgruppen {
211 $main::lxdebug->enter_sub();
213 my ($self, $myconfig, $form) = @_;
217 my $dbh = $form->get_standard_dbh;
219 # get buchungsgruppen
220 $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
221 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
223 $main::lxdebug->leave_sub();
227 my ($self, $myconfig, $form) = @_;
228 $main::lxdebug->enter_sub();
230 my $rc = SL::DB->client->with_transaction(\&_save, $self, $myconfig, $form);
232 $main::lxdebug->leave_sub();
237 my ($self, $myconfig, $form) = @_;
239 # connect to database, turn off AutoCommit
240 my $dbh = SL::DB->client->dbh;
241 my $restricter = SL::HTML::Restrict->create;
244 # make up a unique handle and store in partnumber field
245 # then retrieve the record based on the unique handle to get the id
246 # replace the partnumber field with the actual variable
247 # add records for makemodel
249 # if there is a $form->{id} then replace the old entry
250 # delete all makemodel entries and add the new ones
252 # undo amount formatting
253 map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
254 qw(rop weight listprice sellprice gv lastcost);
256 my $makemodel = ($form->{make_1} || $form->{model_1} || ($form->{makemodel_rows} > 1)) ? 1 : 0;
258 $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
262 my $priceupdate = ', priceupdate = current_date';
265 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
266 if (!$trans_number->is_unique) {
267 $::lxdebug->leave_sub;
272 $query = qq|SELECT sellprice FROM parts WHERE id = ?|;
273 my ($sellprice) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
275 # delete makemodel records
276 do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
278 if ($form->{item} eq 'assembly') {
279 # delete assembly records
280 do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
283 # delete translations
284 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
286 # Check whether or not the prices have changed. If they haven't
287 # then 'priceupdate' should not be updated.
288 my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
289 $priceupdate = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
292 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, save => 1);
294 if ($form->{partnumber} && !$trans_number->is_unique) {
295 $::lxdebug->leave_sub;
299 $form->{partnumber} ||= $trans_number->create_unique;
301 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
302 do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber, unit) VALUES (?, ?, ?)|, $form->{id}, $form->{partnumber}, $form->{unit});
304 $form->{orphaned} = 1;
306 my $partsgroup_id = undef;
308 if ($form->{partsgroup}) {
309 (my $partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
312 my ($subq_inventory, $subq_expense, $subq_income);
313 if ($form->{"item"} eq "part") {
315 qq|(SELECT bg.inventory_accno_id
316 FROM buchungsgruppen bg
317 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
319 $subq_inventory = "NULL";
322 if ($form->{"item"} ne "assembly") {
324 qq|(SELECT tc.expense_accno_id
325 FROM taxzone_charts tc
326 WHERE tc.buchungsgruppen_id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq| and tc.taxzone_id = 0)|;
328 $subq_expense = "NULL";
331 normalize_text_blocks();
349 buchungsgruppen_id = ?,
351 inventory_accno_id = $subq_inventory,
352 income_accno_id = (SELECT tc.income_accno_id FROM taxzone_charts tc WHERE tc.taxzone_id = 0 and tc.buchungsgruppen_id = ?),
353 expense_accno_id = $subq_expense,
362 not_discountable = ?,
368 @values = ($form->{partnumber},
369 $form->{description},
370 $makemodel ? 't' : 'f',
371 $form->{assembly} ? 't' : 'f',
377 $restricter->process($form->{notes}),
380 conv_i($form->{warehouse_id}),
381 conv_i($form->{bin_id}),
382 conv_i($form->{buchungsgruppen_id}),
383 conv_i($form->{payment_id}),
384 conv_i($form->{buchungsgruppen_id}),
385 $form->{obsolete} ? 't' : 'f',
388 $form->{shop} ? 't' : 'f',
392 $form->{has_sernumber} ? 't' : 'f',
393 $form->{not_discountable} ? 't' : 'f',
395 conv_i($partsgroup_id),
396 conv_i($form->{price_factor_id}),
399 do_query($form, $dbh, $query, @values);
401 $form->new_lastmtime('parts');
403 # delete translation records
404 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
406 my @translations = grep { $_->{language_id} && $_->{translation} } @{ $form->{translations} || [] };
408 $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
409 VALUES ( ?, ?, ?, ? )|;
410 $sth = $dbh->prepare($query);
412 foreach my $translation (@translations) {
413 do_statement($form, $sth, $query, conv_i($form->{id}), conv_i($translation->{language_id}), $translation->{translation}, $restricter->process($translation->{longdescription}));
419 # delete price records
420 do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
422 $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) VALUES(?, ?, ?)|;
423 $sth = prepare_query($form, $dbh, $query);
425 for my $i (1 .. $form->{price_rows}) {
426 my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
429 @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
430 do_statement($form, $sth, $query, @values);
435 # insert makemodel records
438 for my $i (1 .. $form->{makemodel_rows}) {
439 if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
441 $value = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
442 if ($value == $form->parse_amount($myconfig, $form->{"old_lastcost_$i"}))
444 if ($form->{"lastupdate_$i"} eq "") {
445 $lastupdate = 'now()';
447 $lastupdate = $dbh->quote($form->{"lastupdate_$i"});
450 $lastupdate = 'now()';
452 $query = qq|INSERT INTO makemodel (parts_id, make, model, lastcost, lastupdate, sortorder) | .
453 qq|VALUES (?, ?, ?, ?, ?, ?)|;
454 @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"}, $value, $lastupdate, conv_i($form->{"sortorder_$i"}) );
456 do_query($form, $dbh, $query, @values);
460 # add assembly records
461 if ($form->{item} eq 'assembly') {
462 # check additional assembly row
463 my $i = $form->{assembly_rows};
464 # if last row is not empty add them
465 if ($form->{"partnumber_$i"} ne "") {
466 $query = qq|SELECT id FROM parts WHERE partnumber = ?|;
467 my ($partid) = selectrow_query($form, $dbh, $query,$form->{"partnumber_$i"} );
469 $form->{"qty_$i"} = 1 unless ($form->{"qty_$i"});
470 $form->{"id_$i"} = $partid;
471 $form->{"bom_$i"} = 0;
472 $form->{assembly_rows}++;
475 $::form->error($::locale->text("uncorrect partnumber ").$form->{"partnumber_$i"});
479 for my $i (1 .. $form->{assembly_rows}) {
480 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
482 if ($form->{"qty_$i"} != 0) {
483 $form->{"bom_$i"} *= 1;
484 $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
485 qq|VALUES (?, ?, ?, ?)|;
486 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
487 do_query($form, $dbh, $query, @values);
493 my $shippingdate = "$a[5]-$a[4]-$a[3]";
495 $form->get_employee($dbh);
499 #set expense_accno=inventory_accno if they are different => bilanz
501 ($form->{expense_accno} != $form->{inventory_accno})
502 ? $form->{inventory_accno}
503 : $form->{expense_accno};
505 # get tax rates and description
507 ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
509 qq|SELECT c.accno, c.description, t.rate, t.taxnumber
511 WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
513 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
515 $form->{taxaccount} = "";
516 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
517 $form->{taxaccount} .= "$ptr->{accno} ";
518 if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
519 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
520 $form->{"$ptr->{accno}_description"} = $ptr->{description};
521 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
522 $form->{taxaccount2} .= " $ptr->{accno} ";
526 CVar->save_custom_variables(dbh => $dbh,
528 trans_id => $form->{id},
532 # Delete saved custom variable values for configs that have been
533 # marked invalid for this part.
535 DELETE FROM custom_variables
536 WHERE (config_id IN (
538 FROM custom_variables_validity val
539 LEFT JOIN custom_variable_configs val_cfg ON (val.config_id = val_cfg.id)
540 WHERE (val_cfg.module = 'IC')
541 AND (val.trans_id = ?)))
544 do_query($form, $dbh, $query, ($form->{id}) x 2);
549 sub retrieve_assemblies {
550 $main::lxdebug->enter_sub();
552 my ($self, $myconfig, $form) = @_;
554 # connect to database
555 my $dbh = $form->get_standard_dbh;
557 my $where = qq|NOT p.obsolete|;
560 if ($form->{partnumber}) {
561 $where .= qq| AND (p.partnumber ILIKE ?)|;
562 push(@values, like($form->{partnumber}));
565 if ($form->{description}) {
566 $where .= qq| AND (p.description ILIKE ?)|;
567 push(@values, like($form->{description}));
570 # retrieve assembly items
572 qq|SELECT p.id, p.partnumber, p.description,
574 (SELECT sum(p2.inventory_accno_id)
575 FROM parts p2, assembly a
576 WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
578 WHERE NOT p.obsolete AND p.assembly $where|;
580 $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
582 $main::lxdebug->leave_sub();
586 $main::lxdebug->enter_sub();
588 my ($self, $myconfig, $form) = @_;
589 my @values = (conv_i($form->{id}));
590 # connect to database, turn off AutoCommit
591 my $dbh = $form->get_standard_dbh;
593 my %columns = ( "assembly" => "id", "parts" => "id" );
595 for my $table (qw(prices makemodel inventory assembly translation parts)) {
596 my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
597 do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
601 my $rc = $dbh->commit;
603 $main::lxdebug->leave_sub();
609 $main::lxdebug->enter_sub();
611 my ($self, $myconfig, $form) = @_;
613 my $i = $form->{assembly_rows};
615 my $where = qq|1 = 1|;
618 my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
620 while (my ($column, $table) = each(%columns)) {
621 next unless ($form->{"${column}_$i"});
622 $where .= qq| AND ${table}.${column} ILIKE ?|;
623 push(@values, like($form->{"${column}_$i"}));
627 $where .= qq| AND NOT (p.id = ?)|;
628 push(@values, conv_i($form->{id}));
631 # Search for part ID overrides all other criteria.
632 if ($form->{"id_${i}"}) {
633 $where = qq|p.id = ?|;
634 @values = ($form->{"id_${i}"});
637 if ($form->{partnumber}) {
638 $where .= qq| ORDER BY p.partnumber|;
640 $where .= qq| ORDER BY p.description|;
643 # connect to database
644 my $dbh = $form->get_standard_dbh;
647 qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
648 p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
649 p.price_factor_id, pfac.factor AS price_factor, p.notes as longdescription
651 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
652 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
654 $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
656 $main::lxdebug->leave_sub();
661 # Warning, deep magic ahead.
662 # This function gets all parts from the database according to the filters specified
665 # sort revers - sorting field + direction
668 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
669 # partnumber ean description partsgroup microfiche drawing
672 # 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
675 # itemstatus = active | onhand | short | obsolete | orphaned
676 # searchitems = part | assembly | service
679 # make model - makemodel
680 # serialnumber transdatefrom transdateto - invoice/orderitems
683 # bought sold onorder ordered rfq quoted - aggreg joins with invoices/orders
684 # l_linetotal l_subtotal - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
685 # l_soldtotal - aggreg join to display total of sold quantity
686 # onhand - as above, but masking the simple itemstatus results (doh!)
687 # short - NOT IMPLEMENTED as form filter, only as itemstatus option
688 # l_serialnumber - belonges to serialnumber filter
689 # l_deliverydate - displays deliverydate is sold etc. flags are active
690 # l_soldtotal - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
693 # onhand - as above, but masking the simple itemstatus results (doh!)
695 # search by overrides of description
697 # disabled sanity checks and changes:
698 # - searchitems = assembly will no longer disable bought
699 # - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
700 # - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
701 # - itemstatus = obsolete will no longer disable onhand, short
702 # - allow sorting by ean
703 # - serialnumber filter also works if l_serialnumber isn't ticked
704 # - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
707 $main::lxdebug->enter_sub();
709 my ($self, $myconfig, $form) = @_;
710 my $dbh = $form->get_standard_dbh($myconfig);
712 $form->{parts} = +{ };
713 $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
715 my @simple_filters = qw(partnumber ean description partsgroup microfiche drawing onhand);
716 my @project_filters = qw(projectnumber projectdescription);
717 my @makemodel_filters = qw(make model);
718 my @invoice_oi_filters = qw(serialnumber soldtotal);
719 my @apoe_filters = qw(transdate);
720 my @like_filters = (@simple_filters, @invoice_oi_filters);
721 my @all_columns = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
722 my @simple_l_switches = (@all_columns, qw(notes listprice sellprice lastcost priceupdate weight unit rop image shop insertdate));
723 my @oe_flags = qw(bought sold onorder ordered rfq quoted);
724 my @qsooqr_flags = qw(invnumber ordnumber quonumber trans_id name module qty);
725 my @deliverydate_flags = qw(deliverydate);
726 # my @other_flags = qw(onhand); # ToDO: implement these
727 # my @inactive_flags = qw(l_subtotal short l_linetotal);
729 my @select_tokens = qw(id factor);
730 my @where_tokens = qw(1=1);
731 my @group_tokens = ();
733 my %joins_needed = ();
736 partsgroup => 'LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)',
737 makemodel => 'LEFT JOIN makemodel mm ON (mm.parts_id = p.id)',
738 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
741 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, project_id, id FROM invoice UNION
742 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
743 ) AS ioi ON ioi.parts_id = p.id|,
746 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
747 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
748 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
749 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
752 SELECT id, name, 'customer' AS cv FROM customer UNION
753 SELECT id, name, 'vendor' AS cv FROM vendor
754 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
755 mv => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
756 project => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
758 my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project);
761 deliverydate => 'apoe.', serialnumber => 'ioi.',
762 transdate => 'apoe.', trans_id => 'ioi.',
763 module => 'apoe.', name => 'cv.',
764 ordnumber => 'apoe.', make => 'mm.',
765 quonumber => 'apoe.', model => 'mm.',
766 invnumber => 'apoe.', partsgroup => 'pg.',
767 lastcost => 'p.', , soldtotal => ' ',
768 factor => 'pfac.', projectnumber => 'pj.',
769 'SUM(ioi.qty)' => ' ', projectdescription => 'pj.',
772 serialnumber => 'ioi.',
773 quotation => 'apoe.',
779 # if the join condition in these blocks are met, the column
780 # of the scecified table will gently override (coalesce actually) the original value
781 # use it to conditionally coalesce values from subtables
782 my @column_override = (
783 # column name, prefix, joins_needed, nick name (in case column is named like another)
784 [ 'description', 'ioi.', 'invoice_oi' ],
785 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
786 [ 'transdate', 'apoe.', 'apoe' ],
787 [ 'unit', 'ioi.', 'invoice_oi' ],
788 [ 'sellprice', 'ioi.', 'invoice_oi' ],
791 # careful with renames. these are HARD, and any filters done on the original column will break
792 my %renamed_columns = (
793 'factor' => 'price_factor',
794 'SUM(ioi.qty)' => 'soldtotal',
795 'ioi.id' => 'ioi_id',
797 'projectdescription' => 'projectdescription',
798 'insertdate' => 'insertdate',
802 projectdescription => 'description',
803 insertdate => 'itime::DATE',
806 if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
807 @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
810 my $make_token_builder = sub {
811 my $joins_needed = shift;
813 my ($nick, $alias) = @_;
814 my ($col) = $real_column{$nick} || $nick;
815 my @coalesce_tokens =
816 map { ($_->[1] || 'p.') . $_->[0] }
817 grep { !$_->[2] || $joins_needed->{$_->[2]} }
818 grep { ($_->[3] || $_->[0]) eq $nick }
819 @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
821 my $coalesce = scalar @coalesce_tokens > 1;
823 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
824 : shift @coalesce_tokens)
825 . ($alias && ($coalesce || $renamed_columns{$nick})
826 ? " AS " . ($renamed_columns{$nick} || $nick)
831 #===== switches and simple filters ========#
833 # special case transdate
834 if (grep { trim($form->{$_}) } qw(transdatefrom transdateto)) {
835 $form->{"l_transdate"} = 1;
836 push @select_tokens, 'transdate';
837 for (qw(transdatefrom transdateto)) {
838 my $value = trim($form->{$_});
840 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
841 push @bind_vars, $value;
845 # special case smart search
847 $form->{"l_$_"} = 1 for qw(partnumber description unit sellprice lastcost cvar_packaging linetotal);
848 push @where_tokens, "p.partnumber ILIKE ? OR p.description ILIKE ?";
849 push @bind_vars, (like($form->{all})) x 2;
852 # special case insertdate
853 if (grep { trim($form->{$_}) } qw(insertdatefrom insertdateto)) {
854 $form->{"l_insertdate"} = 1;
855 push @select_tokens, 'insertdate';
857 my $token_builder = $make_token_builder->();
858 my $token = $token_builder->('insertdate');
860 for (qw(insertdatefrom insertdateto)) {
861 my $value = trim($form->{$_});
863 push @where_tokens, sprintf "$token %s ?", /from$/ ? '>=' : '<=';
864 push @bind_vars, $value;
868 if ($form->{"partsgroup_id"}) {
869 $form->{"l_partsgroup"} = '1'; # show the column
870 push @where_tokens, "pg.id = ?";
871 push @bind_vars, $form->{"partsgroup_id"};
874 if ($form->{shop} ne '') {
875 $form->{l_shop} = '1'; # show the column
876 if ($form->{shop} eq '0' || $form->{shop} eq 'f') {
877 push @where_tokens, 'NOT p.shop';
880 push @where_tokens, 'p.shop';
884 foreach (@like_filters) {
885 next unless $form->{$_};
886 $form->{"l_$_"} = '1'; # show the column
887 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
888 push @bind_vars, like($form->{$_});
891 foreach (@simple_l_switches) {
892 next unless $form->{"l_$_"};
893 push @select_tokens, $_;
896 for ($form->{searchitems}) {
897 push @where_tokens, 'p.inventory_accno_id > 0' if /part/;
898 push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
899 push @where_tokens, 'NOT p.assembly' if /service/;
900 push @where_tokens, ' p.assembly' if /assembly/;
903 for ($form->{itemstatus}) {
904 push @where_tokens, 'p.id NOT IN
905 (SELECT DISTINCT parts_id FROM invoice UNION
906 SELECT DISTINCT parts_id FROM assembly UNION
907 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
908 push @where_tokens, 'p.onhand = 0' if /orphaned/;
909 push @where_tokens, 'NOT p.obsolete' if /active/;
910 push @where_tokens, ' p.obsolete', if /obsolete/;
911 push @where_tokens, 'p.onhand > 0', if /onhand/;
912 push @where_tokens, 'p.onhand < p.rop', if /short/;
915 my $q_assembly_lastcost =
916 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
918 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
919 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
920 WHERE (a_lc.id = p.id)) AS lastcost|;
921 $table_prefix{$q_assembly_lastcost} = ' ';
923 # special case makemodel search
924 # all_parts is based upon the assumption that every parameter is named like the column it represents
925 # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
926 # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
928 push @where_tokens, 'mv.name ILIKE ?';
929 push @bind_vars, like($form->{make});
931 if ($form->{model}) {
932 push @where_tokens, 'mm.model ILIKE ?';
933 push @bind_vars, like($form->{model});
936 # special case: sorting by partnumber
937 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
938 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
939 # ToDO: implement proper functional sorting
940 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
941 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
942 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
943 # if $form->{sort} eq 'partnumber';
945 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
948 $limit_clause = " LIMIT 100" if $form->{top100};
949 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
951 #=== joins and complicated filters ========#
953 my $bsooqr = any { $form->{$_} } @oe_flags;
954 my @bsooqr_tokens = ();
956 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
957 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
958 push @select_tokens, $q_assembly_lastcost if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
959 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
960 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
961 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
962 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
963 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
964 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
965 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
967 $joins_needed{partsgroup} = 1;
968 $joins_needed{pfac} = 1;
969 $joins_needed{project} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
970 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
971 $joins_needed{mv} = 1 if $joins_needed{makemodel};
972 $joins_needed{cv} = 1 if $bsooqr;
973 $joins_needed{apoe} = 1 if $joins_needed{project} || $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
974 $joins_needed{invoice_oi} = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
976 # special case for description search.
977 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
978 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
979 # find the old entries in of @where_tokens and @bind_vars, and adjust them
980 if ($joins_needed{invoice_oi}) {
981 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
982 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
983 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
984 splice @bind_vars, $bi, 0, $bind_vars[$bi];
989 # now the master trick: soldtotal.
990 if ($form->{l_soldtotal}) {
991 push @where_tokens, 'NOT ioi.qty = 0';
992 push @group_tokens, @select_tokens;
993 map { s/.*\sAS\s+//si } @group_tokens;
994 push @select_tokens, 'SUM(ioi.qty)';
997 #============= build query ================#
999 my $token_builder = $make_token_builder->(\%joins_needed);
1001 my @sort_cols = (@simple_filters, qw(id priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate insertdate shop));
1002 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
1003 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
1004 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
1006 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
1007 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
1008 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
1009 my $group_clause = @group_tokens ? ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens : '';
1011 my %oe_flag_to_cvar = (
1012 bought => 'invoice',
1014 onorder => 'orderitems',
1015 ordered => 'orderitems',
1016 rfq => 'orderitems',
1017 quoted => 'orderitems',
1020 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
1022 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
1024 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
1028 $where_clause .= qq| AND ($cvar_where)|;
1029 push @bind_vars, @cvar_values;
1032 my $query = <<" SQL";
1033 SELECT DISTINCT $select_clause
1042 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1044 map { $_->{onhand} *= 1 } @{ $form->{parts} };
1046 # fix qty sign in ap. those are saved negative
1047 if ($bsooqr && $form->{bought}) {
1048 for my $row (@{ $form->{parts} }) {
1049 $row->{qty} *= -1 if $row->{module} eq 'ir';
1053 # post processing for assembly parts lists (bom)
1054 # for each part get the assembly parts and add them into the partlist.
1056 if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1058 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1059 p.unit, p.notes, p.itime::DATE as insertdate,
1060 p.sellprice, p.listprice, p.lastcost,
1061 p.rop, p.weight, p.priceupdate,
1062 p.image, p.drawing, p.microfiche,
1065 INNER JOIN assembly a ON (p.id = a.parts_id)
1068 my $sth = prepare_query($form, $dbh, $query);
1070 foreach my $item (@{ $form->{parts} }) {
1071 push(@assemblies, $item);
1072 do_statement($form, $sth, $query, conv_i($item->{id}));
1074 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1075 $ref->{assemblyitem} = 1;
1076 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1077 push(@assemblies, $ref);
1082 # copy assemblies to $form->{parts}
1083 $form->{parts} = \@assemblies;
1086 if ($form->{l_pricegroups} ) {
1088 SELECT parts_id, price, pricegroup_id
1093 my $sth = prepare_query($form, $dbh, $query);
1095 foreach my $part (@{ $form->{parts} }) {
1096 do_statement($form, $sth, $query, conv_i($part->{id}));
1098 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1099 $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
1106 $main::lxdebug->leave_sub();
1108 return @{ $form->{parts} };
1111 sub _create_filter_for_priceupdate {
1112 $main::lxdebug->enter_sub();
1115 my $myconfig = \%main::myconfig;
1116 my $form = $main::form;
1119 my $where = '1 = 1';
1121 foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1123 $column =~ s/.*\.//;
1124 next unless ($form->{$column});
1126 $where .= qq| AND $item ILIKE ?|;
1127 push(@where_values, like($form->{$column}));
1130 foreach my $item (qw(description serialnumber)) {
1131 next unless ($form->{$item});
1133 $where .= qq| AND (${item} ILIKE ?)|;
1134 push(@where_values, like($form->{$item}));
1138 # items which were never bought, sold or on an order
1139 if ($form->{itemstatus} eq 'orphaned') {
1141 qq| AND (p.onhand = 0)
1144 SELECT DISTINCT parts_id FROM invoice
1146 SELECT DISTINCT parts_id FROM assembly
1148 SELECT DISTINCT parts_id FROM orderitems
1151 } elsif ($form->{itemstatus} eq 'active') {
1152 $where .= qq| AND p.obsolete = '0'|;
1154 } elsif ($form->{itemstatus} eq 'obsolete') {
1155 $where .= qq| AND p.obsolete = '1'|;
1157 } elsif ($form->{itemstatus} eq 'onhand') {
1158 $where .= qq| AND p.onhand > 0|;
1160 } elsif ($form->{itemstatus} eq 'short') {
1161 $where .= qq| AND p.onhand < p.rop|;
1165 foreach my $column (qw(make model)) {
1166 next unless ($form->{$column});
1167 $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1168 push(@where_values, like($form->{$column}));
1171 $main::lxdebug->leave_sub();
1173 return ($where, @where_values);
1176 sub get_num_matches_for_priceupdate {
1177 $main::lxdebug->enter_sub();
1181 my $myconfig = \%main::myconfig;
1182 my $form = $main::form;
1184 my $dbh = $form->get_standard_dbh($myconfig);
1186 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1188 my $num_updated = 0;
1191 for my $column (qw(sellprice listprice)) {
1192 next if ($form->{$column} eq "");
1200 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1202 my ($result) = selectfirst_array_query($form, $dbh, $query, @where_values);
1203 $num_updated += $result if (0 <= $result);
1212 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1213 WHERE $where) AND (pricegroup_id = ?)|;
1214 my $sth = prepare_query($form, $dbh, $query);
1216 for my $i (1 .. $form->{price_rows}) {
1217 next if ($form->{"price_$i"} eq "");
1219 my ($result) = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1220 $num_updated += $result if (0 <= $result);
1224 $main::lxdebug->leave_sub();
1226 return $num_updated;
1230 $main::lxdebug->enter_sub();
1232 my ($self, $myconfig, $form) = @_;
1234 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1235 my $num_updated = 0;
1237 # connect to database
1238 my $dbh = $form->get_standard_dbh;
1240 for my $column (qw(sellprice listprice)) {
1241 next if ($form->{$column} eq "");
1243 my $value = $form->parse_amount($myconfig, $form->{$column});
1246 if ($form->{"${column}_type"} eq "percent") {
1247 $value = ($value / 100) + 1;
1252 qq|UPDATE parts SET $column = $column $operator ?
1256 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1258 my $result = do_query($form, $dbh, $query, $value, @where_values);
1259 $num_updated += $result if (0 <= $result);
1263 qq|UPDATE prices SET price = price + ?
1267 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1268 WHERE $where) AND (pricegroup_id = ?)|;
1269 my $sth_add = prepare_query($form, $dbh, $q_add);
1272 qq|UPDATE prices SET price = price * ?
1276 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1277 WHERE $where) AND (pricegroup_id = ?)|;
1278 my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1280 for my $i (1 .. $form->{price_rows}) {
1281 next if ($form->{"price_$i"} eq "");
1283 my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1286 if ($form->{"pricegroup_type_$i"} eq "percent") {
1287 $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1289 $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1292 $num_updated += $result if (0 <= $result);
1296 $sth_multiply->finish();
1298 my $rc= $dbh->commit;
1300 $main::lxdebug->leave_sub();
1302 return $num_updated;
1306 $main::lxdebug->enter_sub();
1308 my ($self, $module, $myconfig, $form) = @_;
1310 # connect to database
1311 my $dbh = $form->get_standard_dbh;
1313 my @values = like($module);
1318 qq|SELECT c.accno, c.description, c.link, c.id,
1319 p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1320 FROM chart c, parts p
1321 WHERE (c.link LIKE ?) AND (p.id = ?)
1323 push(@values, conv_i($form->{id}));
1327 qq|SELECT c.accno, c.description, c.link, c.id,
1328 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1329 FROM chart c, defaults d
1334 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1335 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1336 foreach my $key (split(/:/, $ref->{link})) {
1337 if ($key =~ /\Q$module\E/) {
1338 if ( ($ref->{id} eq $ref->{inventory_accno_id})
1339 || ($ref->{id} eq $ref->{income_accno_id})
1340 || ($ref->{id} eq $ref->{expense_accno_id})) {
1341 push @{ $form->{"${module}_links"}{$key} },
1342 { accno => $ref->{accno},
1343 description => $ref->{description},
1344 selected => "selected" };
1345 $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1347 push @{ $form->{"${module}_links"}{$key} },
1348 { accno => $ref->{accno},
1349 description => $ref->{description},
1357 # get buchungsgruppen
1358 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1361 $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1364 ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1367 $main::lxdebug->leave_sub();
1370 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1372 $main::lxdebug->enter_sub();
1374 my ($self, $myconfig, $form, $sortorder) = @_;
1375 my $dbh = $form->get_standard_dbh;
1376 my $order = qq| p.partnumber|;
1377 my $where = qq|1 = 1|;
1380 if ($sortorder eq "all") {
1381 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1382 push(@values, like($form->{partnumber}), like($form->{description}));
1384 } elsif ($sortorder eq "partnumber") {
1385 $where .= qq| AND (partnumber ILIKE ?)|;
1386 push(@values, like($form->{partnumber}));
1388 } elsif ($sortorder eq "description") {
1389 $where .= qq| AND (description ILIKE ?)|;
1390 push(@values, like($form->{description}));
1391 $order = "description";
1396 qq|SELECT id, partnumber, description, unit, sellprice
1398 WHERE $where ORDER BY $order|;
1400 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1403 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1404 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1409 $form->{"id_$j"} = $ref->{id};
1410 $form->{"partnumber_$j"} = $ref->{partnumber};
1411 $form->{"description_$j"} = $ref->{description};
1412 $form->{"unit_$j"} = $ref->{unit};
1413 $form->{"sellprice_$j"} = $ref->{sellprice};
1414 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
1419 $main::lxdebug->leave_sub();
1424 # gets sum of sold part with part_id
1426 $main::lxdebug->enter_sub();
1428 my ($dbh, $id) = @_;
1430 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1431 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1434 $main::lxdebug->leave_sub();
1437 } #end get_soldtotal
1439 sub retrieve_languages {
1440 $main::lxdebug->enter_sub();
1442 my ($self, $myconfig, $form) = @_;
1444 # connect to database
1445 my $dbh = $form->get_standard_dbh;
1451 if ($form->{language_values} ne "") {
1453 qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1455 LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1456 ORDER BY lower(l.description)|;
1457 @values = (conv_i($form->{id}));
1460 $query = qq|SELECT id, description
1462 ORDER BY lower(description)|;
1465 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1467 $main::lxdebug->leave_sub();
1472 sub follow_account_chain {
1473 $main::lxdebug->enter_sub(2);
1475 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1477 my @visited_accno_ids = ($accno_id);
1481 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
1482 map { $_->{id} => $_ }
1483 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
1484 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
1486 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
1487 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
1491 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
1492 last unless ($ref && $ref->{"is_valid"} &&
1493 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1494 $accno_id = $ref->{"new_chart_id"};
1495 $accno = $ref->{"accno"};
1496 push(@visited_accno_ids, $accno_id);
1499 $main::lxdebug->leave_sub(2);
1501 return ($accno_id, $accno);
1504 sub retrieve_accounts {
1505 $main::lxdebug->enter_sub;
1508 my $myconfig = shift;
1510 my $dbh = $form->get_standard_dbh;
1511 my %args = @_; # index => part_id
1513 $form->{taxzone_id} *= 1;
1515 return unless grep $_, values %args; # shortfuse if no part_id supplied
1517 # transdate madness.
1519 if ($form->{type} eq "invoice" or $form->{type} eq "credit_note") {
1520 # use deliverydate for sales and purchase invoice, if it exists
1521 # also use deliverydate for credit notes
1522 if (!$form->{deliverydate}) {
1523 $transdate = $form->{invdate};
1525 $transdate = $form->{deliverydate};
1527 } elsif ($form->{script} eq 'ir.pl') {
1528 # when a purchase invoice is opened from the report of purchase invoices
1529 # $form->{type} isn't set, but $form->{script} is, not sure why this is or
1530 # whether this distinction matters in some other scenario. Otherwise one
1531 # could probably take out this elsif and add a
1532 # " or $form->{script} eq 'ir.pl' "
1533 # to the above if-statement
1534 if (!$form->{deliverydate}) {
1535 $transdate = $form->{invdate};
1537 $transdate = $form->{deliverydate};
1539 } elsif (($form->{type} eq "credit_note") and $form->{deliverydate}) {
1540 # if credit_note has a deliverydate, use this instead of invdate
1541 # useful for credit_notes of invoices from an old period with different tax
1542 # if there is no deliverydate then invdate is used, old default (see next elsif)
1543 # Falls hier der Stichtag für Steuern anders bestimmt wird,
1544 # entsprechend auch bei Taxkeys.pm anpassen
1545 $transdate = $form->{deliverydate};
1546 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1547 $transdate = $form->{invdate};
1549 $transdate = $form->{transdate};
1552 if ($transdate eq "") {
1553 $transdate = DateTime->today_local->to_lxoffice;
1555 $transdate = $dbh->quote($transdate);
1558 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
1560 my @part_ids = grep { $_ } values %args;
1561 my $in = join ',', ('?') x @part_ids;
1563 my %accno_by_part = map { $_->{id} => $_ }
1564 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
1566 p.id, p.inventory_accno_id AS is_part,
1567 bg.inventory_accno_id,
1568 tc.income_accno_id AS income_accno_id,
1569 tc.expense_accno_id AS expense_accno_id,
1570 c1.accno AS inventory_accno,
1571 c2.accno AS income_accno,
1572 c3.accno AS expense_accno
1574 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
1575 LEFT JOIN taxzone_charts tc on bg.id = tc.buchungsgruppen_id
1576 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1577 LEFT JOIN chart c2 ON tc.income_accno_id = c2.id
1578 LEFT JOIN chart c3 ON tc.expense_accno_id = c3.id
1580 tc.taxzone_id = '$form->{taxzone_id}'
1585 my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1586 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1588 LEFT JOIN chart c ON c.id = t.chart_id
1592 WHERE tk.chart_id = ? AND startdate <= ?
1593 ORDER BY startdate DESC LIMIT 1)
1596 while (my ($index => $part_id) = each %args) {
1597 my $ref = $accno_by_part{$part_id} or next;
1599 $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
1602 for my $type (qw(inventory income expense)) {
1603 next unless $ref->{"${type}_accno_id"};
1604 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1605 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1608 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1610 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1611 $ref = $sth_tax->fetchrow_hashref or next;
1613 $form->{"taxaccounts_$index"} = $ref->{"accno"};
1614 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1616 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1621 $::lxdebug->leave_sub;
1624 sub get_basic_part_info {
1625 $main::lxdebug->enter_sub();
1630 Common::check_params(\%params, qw(id));
1632 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1635 $main::lxdebug->leave_sub();
1639 my $myconfig = \%main::myconfig;
1640 my $form = $main::form;
1642 my $dbh = $form->get_standard_dbh($myconfig);
1644 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1646 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1648 if ('' eq ref $params{id}) {
1649 $info = $info->[0] || { };
1651 $main::lxdebug->leave_sub();
1655 my %info_map = map { $_->{id} => $_ } @{ $info };
1657 $main::lxdebug->leave_sub();
1662 sub prepare_parts_for_printing {
1663 $main::lxdebug->enter_sub();
1668 my $myconfig = $params{myconfig} || \%main::myconfig;
1669 my $form = $params{form} || $main::form;
1671 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1673 my $prefix = $params{prefix} || 'id_';
1674 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1676 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1679 $main::lxdebug->leave_sub();
1683 my $placeholders = join ', ', ('?') x scalar(@part_ids);
1684 my $query = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
1686 LEFT JOIN vendor v ON (mm.make = v.id)
1687 WHERE mm.parts_id IN ($placeholders)|;
1691 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
1693 while (my $ref = $sth->fetchrow_hashref()) {
1694 $makemodel{$ref->{parts_id}} ||= [];
1695 push @{ $makemodel{$ref->{parts_id}} }, $ref;
1700 my @columns = qw(ean image microfiche drawing);
1702 $query = qq|SELECT id, | . join(', ', @columns) . qq|
1704 WHERE id IN ($placeholders)|;
1706 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1708 my %template_arrays;
1709 map { $template_arrays{$_} = [] } (qw(make model), @columns);
1711 foreach my $i (1 .. $rowcount) {
1712 my $id = $form->{"${prefix}${i}"};
1716 foreach (@columns) {
1717 push @{ $template_arrays{$_} }, $data{$id}->{$_};
1720 push @{ $template_arrays{make} }, [];
1721 push @{ $template_arrays{model} }, [];
1723 next if (!$makemodel{$id});
1725 foreach my $ref (@{ $makemodel{$id} }) {
1726 map { push @{ $template_arrays{$_}->[-1] }, $ref->{$_} } qw(make model);
1730 my $parts = SL::DB::Manager::Part->get_all(query => [ id => \@part_ids ]);
1731 my %parts_by_id = map { $_->id => $_ } @$parts;
1733 for my $i (1..$rowcount) {
1734 my $id = $form->{"${prefix}${i}"};
1737 push @{ $template_arrays{part_type} }, $parts_by_id{$id}->type;
1740 return %template_arrays;
1741 $main::lxdebug->leave_sub();
1744 sub normalize_text_blocks {
1745 $main::lxdebug->enter_sub();
1750 my $form = $params{form} || $main::form;
1752 # check if feature is enabled (select normalize_part_descriptions from defaults)
1753 return unless ($::instance_conf->get_normalize_part_descriptions);
1755 foreach (qw(description notes)) {
1756 $form->{$_} =~ s/\s+$//s;
1757 $form->{$_} =~ s/^\s+//s;
1758 $form->{$_} =~ s/ {2,}/ /g;
1760 $main::lxdebug->leave_sub();