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);
51 $main::lxdebug->enter_sub();
53 my ($self, $myconfig, $form) = @_;
56 my $dbh = $form->get_standard_dbh;
62 c1.accno AS inventory_accno,
63 c2.accno AS income_accno,
64 c3.accno AS expense_accno,
67 LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
68 LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
69 LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
70 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
72 my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
74 # copy to $form variables
75 map { $form->{$_} = $ref->{$_} } (keys %{$ref});
77 $form->{mtime} = $form->{itime} if !$form->{mtime};
78 $form->{lastmtime} = $form->{mtime};
81 # part or service item
82 if ($form->{part_type} eq 'assembly') {
84 # retrieve assembly items
86 qq|SELECT p.id, p.partnumber, p.description,
87 p.sellprice, p.lastcost, p.weight, a.qty, a.bom, p.unit,
88 pg.partsgroup, p.price_factor_id, pfac.factor AS price_factor
90 JOIN assembly a ON (a.parts_id = p.id)
91 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
92 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
95 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
97 $form->{assembly_rows} = 0;
98 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
99 $form->{assembly_rows}++;
100 foreach my $key (keys %{$ref}) {
101 $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
108 # setup accno hash for <option checked> {amount} is used in create_links
109 $form->{amount}{IC} = $form->{inventory_accno};
110 $form->{amount}{IC_income} = $form->{income_accno};
111 $form->{amount}{IC_sale} = $form->{income_accno};
112 $form->{amount}{IC_expense} = $form->{expense_accno};
113 $form->{amount}{IC_cogs} = $form->{expense_accno};
117 SELECT pg.pricegroup, pg.id AS pricegroup_id, COALESCE(pr.price, 0) AS price
119 LEFT JOIN prices pr ON (pr.pricegroup_id = pg.id) AND (pr.parts_id = ?)
120 ORDER BY lower(pg.pricegroup)
124 foreach $ref (selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}))) {
125 $form->{"${_}_${row}"} = $ref->{$_} for qw(pricegroup_id pricegroup price);
128 $form->{price_rows} = $row - 1;
131 if ($form->{makemodel}) {
133 $query = qq|SELECT m.make, m.model,m.lastcost,m.lastcost,m.lastupdate,m.sortorder FROM makemodel m | .
134 qq|WHERE m.parts_id = ? order by m.sortorder asc|;
135 my @values = ($form->{id});
136 $sth = $dbh->prepare($query);
137 $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
141 while (($form->{"make_$i"}, $form->{"model_$i"}, $form->{"old_lastcost_$i"},
142 $form->{"lastcost_$i"}, $form->{"lastupdate_$i"}, $form->{"sortorder_$i"}) = $sth->fetchrow_array)
147 $form->{makemodel_rows} = $i - 1;
152 $query = qq|SELECT language_id, translation, longdescription
155 $form->{translations} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
158 my @referencing_tables = qw(invoice orderitems inventory);
159 my %column_map = ( );
160 my $parts_id = conv_i($form->{id});
162 $form->{orphaned} = 1;
164 foreach my $table (@referencing_tables) {
165 my $column = $column_map{$table} || 'parts_id';
166 $query = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
167 my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
170 $form->{orphaned} = 0;
175 $form->{"unit_changeable"} = $form->{orphaned};
177 Common::webdav_folder($form) if $::lx_office_conf{features}{webdav};
179 $main::lxdebug->leave_sub();
182 sub get_pricegroups {
183 $main::lxdebug->enter_sub();
185 my ($self, $myconfig, $form) = @_;
187 my $dbh = $form->get_standard_dbh;
190 my $query = qq|SELECT id, pricegroup FROM pricegroup ORDER BY lower(pricegroup)|;
191 my $pricegroups = selectall_hashref_query($form, $dbh, $query);
194 foreach my $pg (@{ $pricegroups }) {
195 $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
196 $form->{"pricegroup_id_$i"} = "$pg->{id}";
197 $form->{"pricegroup_$i"} = "$pg->{pricegroup}";
202 $form->{price_rows} = $i - 1;
204 $main::lxdebug->leave_sub();
209 sub retrieve_buchungsgruppen {
210 $main::lxdebug->enter_sub();
212 my ($self, $myconfig, $form) = @_;
216 my $dbh = $form->get_standard_dbh;
218 # get buchungsgruppen
219 $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
220 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
222 $main::lxdebug->leave_sub();
226 my ($self, $myconfig, $form) = @_;
227 $main::lxdebug->enter_sub();
229 my $rc = SL::DB->client->with_transaction(\&_save, $self, $myconfig, $form);
231 $main::lxdebug->leave_sub();
236 my ($self, $myconfig, $form) = @_;
239 my $dbh = SL::DB->client->dbh;
240 my $restricter = SL::HTML::Restrict->create;
243 # make up a unique handle and store in partnumber field
244 # then retrieve the record based on the unique handle to get the id
245 # replace the partnumber field with the actual variable
246 # add records for makemodel
248 # if there is a $form->{id} then replace the old entry
249 # delete all makemodel entries and add the new ones
251 # undo amount formatting
252 map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
253 qw(rop weight listprice sellprice gv lastcost);
255 my $makemodel = ($form->{make_1} || $form->{model_1} || ($form->{makemodel_rows} > 1)) ? 1 : 0;
260 my $priceupdate = ', priceupdate = current_date';
263 my $trans_number = SL::TransNumber->new(type => $form->{part_type}, dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
264 if (!$trans_number->is_unique) {
265 $::lxdebug->leave_sub;
270 $query = qq|SELECT sellprice FROM parts WHERE id = ?|;
271 my ($sellprice) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
273 # delete makemodel records
274 do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
276 if ($form->{part_type} 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->{part_type}, 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, part_type) VALUES (?, ?, ?, ?)|, $form->{id}, $form->{partnumber}, $form->{unit}, $form->{part_type});
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->{part_type} 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->{part_type} ne "assembly") {
322 qq|(SELECT tc.expense_accno_id
323 FROM taxzone_charts tc
324 WHERE tc.buchungsgruppen_id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq| and tc.taxzone_id = 0)|;
326 $subq_expense = "NULL";
329 normalize_text_blocks();
346 buchungsgruppen_id = ?,
348 inventory_accno_id = $subq_inventory,
349 income_accno_id = (SELECT tc.income_accno_id FROM taxzone_charts tc WHERE tc.taxzone_id = 0 and tc.buchungsgruppen_id = ?),
350 expense_accno_id = $subq_expense,
359 not_discountable = ?,
366 @values = ($form->{partnumber},
367 $form->{description},
368 $makemodel ? 't' : 'f',
374 $restricter->process($form->{notes}),
377 conv_i($form->{warehouse_id}),
378 conv_i($form->{bin_id}),
379 conv_i($form->{buchungsgruppen_id}),
380 conv_i($form->{payment_id}),
381 conv_i($form->{buchungsgruppen_id}),
382 $form->{obsolete} ? 't' : 'f',
385 $form->{shop} ? 't' : 'f',
389 $form->{has_sernumber} ? 't' : 'f',
390 $form->{not_discountable} ? 't' : 'f',
393 conv_i($partsgroup_id),
394 conv_i($form->{price_factor_id}),
397 do_query($form, $dbh, $query, @values);
399 $form->new_lastmtime('parts');
401 # delete translation records
402 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
404 my @translations = grep { $_->{language_id} && $_->{translation} } @{ $form->{translations} || [] };
406 $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
407 VALUES ( ?, ?, ?, ? )|;
408 $sth = $dbh->prepare($query);
410 foreach my $translation (@translations) {
411 do_statement($form, $sth, $query, conv_i($form->{id}), conv_i($translation->{language_id}), $translation->{translation}, $restricter->process($translation->{longdescription}));
417 # delete price records
418 do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
420 $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) VALUES(?, ?, ?)|;
421 $sth = prepare_query($form, $dbh, $query);
423 for my $i (1 .. $form->{price_rows}) {
424 my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
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->{part_type} 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},
530 # Delete saved custom variable values for configs that have been
531 # marked invalid for this part.
533 DELETE FROM custom_variables
534 WHERE (config_id IN (
536 FROM custom_variables_validity val
537 LEFT JOIN custom_variable_configs val_cfg ON (val.config_id = val_cfg.id)
538 WHERE (val_cfg.module = 'IC')
539 AND (val.trans_id = ?)))
542 do_query($form, $dbh, $query, ($form->{id}) x 2);
547 sub retrieve_assemblies {
548 $main::lxdebug->enter_sub();
550 my ($self, $myconfig, $form) = @_;
552 # connect to database
553 my $dbh = $form->get_standard_dbh;
555 my $where = qq|NOT p.obsolete|;
558 if ($form->{partnumber}) {
559 $where .= qq| AND (p.partnumber ILIKE ?)|;
560 push(@values, like($form->{partnumber}));
563 if ($form->{description}) {
564 $where .= qq| AND (p.description ILIKE ?)|;
565 push(@values, like($form->{description}));
568 # retrieve assembly items
570 qq|SELECT p.id, p.partnumber, p.description,
572 (SELECT sum(p2.inventory_accno_id)
573 FROM parts p2, assembly a
574 WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
576 WHERE NOT p.obsolete AND p.part_type = 'assembly' $where|;
578 $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
580 $main::lxdebug->leave_sub();
584 my ($self, $myconfig, $form) = @_;
585 $main::lxdebug->enter_sub();
587 my $rc = SL::DB->client->with_transaction(\&_delete, $self, $myconfig, $form);
589 $main::lxdebug->leave_sub();
594 my ($self, $myconfig, $form) = @_;
595 my @values = (conv_i($form->{id}));
597 my %columns = ( "assembly" => "id", "parts" => "id" );
599 for my $table (qw(prices makemodel inventory assembly translation parts)) {
600 my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
601 do_query($form, SL::DB->client->dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
608 $main::lxdebug->enter_sub();
610 my ($self, $myconfig, $form) = @_;
612 my $i = $form->{assembly_rows};
614 my $where = qq|1 = 1|;
617 my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
619 while (my ($column, $table) = each(%columns)) {
620 next unless ($form->{"${column}_$i"});
621 $where .= qq| AND ${table}.${column} ILIKE ?|;
622 push(@values, like($form->{"${column}_$i"}));
626 $where .= qq| AND NOT (p.id = ?)|;
627 push(@values, conv_i($form->{id}));
630 # Search for part ID overrides all other criteria.
631 if ($form->{"id_${i}"}) {
632 $where = qq|p.id = ?|;
633 @values = ($form->{"id_${i}"});
636 if ($form->{partnumber}) {
637 $where .= qq| ORDER BY p.partnumber|;
639 $where .= qq| ORDER BY p.description|;
643 qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
644 p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
645 p.price_factor_id, pfac.factor AS price_factor, p.notes as longdescription
647 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
648 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
650 $form->{item_list} = selectall_hashref_query($form, SL::DB->client->dbh, $query, @values);
652 $main::lxdebug->leave_sub();
657 # Warning, deep magic ahead.
658 # This function gets all parts from the database according to the filters specified
661 # sort revers - sorting field + direction
664 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
665 # partnumber ean description partsgroup microfiche drawing
668 # 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
671 # itemstatus = active | onhand | short | obsolete | orphaned
672 # searchitems = part | assembly | service
675 # make model - makemodel
676 # serialnumber transdatefrom transdateto - invoice/orderitems
679 # bought sold onorder ordered rfq quoted - aggreg joins with invoices/orders
680 # l_linetotal l_subtotal - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
681 # l_soldtotal - aggreg join to display total of sold quantity
682 # onhand - as above, but masking the simple itemstatus results (doh!)
683 # short - NOT IMPLEMENTED as form filter, only as itemstatus option
684 # l_serialnumber - belonges to serialnumber filter
685 # l_deliverydate - displays deliverydate is sold etc. flags are active
686 # l_soldtotal - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
689 # onhand - as above, but masking the simple itemstatus results (doh!)
691 # search by overrides of description
693 # disabled sanity checks and changes:
694 # - searchitems = assembly will no longer disable bought
695 # - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
696 # - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
697 # - itemstatus = obsolete will no longer disable onhand, short
698 # - allow sorting by ean
699 # - serialnumber filter also works if l_serialnumber isn't ticked
700 # - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
703 $main::lxdebug->enter_sub();
705 my ($self, $myconfig, $form) = @_;
706 my $dbh = $form->get_standard_dbh($myconfig);
708 $form->{parts} = +{ };
709 $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
711 my @simple_filters = qw(partnumber ean description partsgroup microfiche drawing onhand);
712 my @project_filters = qw(projectnumber projectdescription);
713 my @makemodel_filters = qw(make model);
714 my @invoice_oi_filters = qw(serialnumber soldtotal);
715 my @apoe_filters = qw(transdate);
716 my @like_filters = (@simple_filters, @invoice_oi_filters);
717 my @all_columns = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
718 my @simple_l_switches = (@all_columns, qw(notes listprice sellprice lastcost priceupdate weight unit rop image shop insertdate));
719 my @oe_flags = qw(bought sold onorder ordered rfq quoted);
720 my @qsooqr_flags = qw(invnumber ordnumber quonumber trans_id name module qty);
721 my @deliverydate_flags = qw(deliverydate);
722 # my @other_flags = qw(onhand); # ToDO: implement these
723 # my @inactive_flags = qw(l_subtotal short l_linetotal);
725 my @select_tokens = qw(id factor);
726 my @where_tokens = qw(1=1);
727 my @group_tokens = ();
729 my %joins_needed = ();
732 partsgroup => 'LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)',
733 makemodel => 'LEFT JOIN makemodel mm ON (mm.parts_id = p.id)',
734 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
737 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, project_id, id FROM invoice UNION
738 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
739 ) AS ioi ON ioi.parts_id = p.id|,
742 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
743 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
744 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
745 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
748 SELECT id, name, 'customer' AS cv FROM customer UNION
749 SELECT id, name, 'vendor' AS cv FROM vendor
750 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
751 mv => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
752 project => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
754 my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project);
757 deliverydate => 'apoe.', serialnumber => 'ioi.',
758 transdate => 'apoe.', trans_id => 'ioi.',
759 module => 'apoe.', name => 'cv.',
760 ordnumber => 'apoe.', make => 'mm.',
761 quonumber => 'apoe.', model => 'mm.',
762 invnumber => 'apoe.', partsgroup => 'pg.',
763 lastcost => 'p.', , soldtotal => ' ',
764 factor => 'pfac.', projectnumber => 'pj.',
765 'SUM(ioi.qty)' => ' ', projectdescription => 'pj.',
768 serialnumber => 'ioi.',
769 quotation => 'apoe.',
775 # if the join condition in these blocks are met, the column
776 # of the scecified table will gently override (coalesce actually) the original value
777 # use it to conditionally coalesce values from subtables
778 my @column_override = (
779 # column name, prefix, joins_needed, nick name (in case column is named like another)
780 [ 'description', 'ioi.', 'invoice_oi' ],
781 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
782 [ 'transdate', 'apoe.', 'apoe' ],
783 [ 'unit', 'ioi.', 'invoice_oi' ],
784 [ 'sellprice', 'ioi.', 'invoice_oi' ],
787 # careful with renames. these are HARD, and any filters done on the original column will break
788 my %renamed_columns = (
789 'factor' => 'price_factor',
790 'SUM(ioi.qty)' => 'soldtotal',
791 'ioi.id' => 'ioi_id',
793 'projectdescription' => 'projectdescription',
794 'insertdate' => 'insertdate',
798 projectdescription => 'description',
799 insertdate => 'itime::DATE',
802 if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
803 @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
806 my $make_token_builder = sub {
807 my $joins_needed = shift;
809 my ($nick, $alias) = @_;
810 my ($col) = $real_column{$nick} || $nick;
811 my @coalesce_tokens =
812 map { ($_->[1] || 'p.') . $_->[0] }
813 grep { !$_->[2] || $joins_needed->{$_->[2]} }
814 grep { ($_->[3] || $_->[0]) eq $nick }
815 @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
817 my $coalesce = scalar @coalesce_tokens > 1;
819 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
820 : shift @coalesce_tokens)
821 . ($alias && ($coalesce || $renamed_columns{$nick})
822 ? " AS " . ($renamed_columns{$nick} || $nick)
827 #===== switches and simple filters ========#
829 # special case transdate
830 if (grep { trim($form->{$_}) } qw(transdatefrom transdateto)) {
831 $form->{"l_transdate"} = 1;
832 push @select_tokens, 'transdate';
833 for (qw(transdatefrom transdateto)) {
834 my $value = trim($form->{$_});
836 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
837 push @bind_vars, $value;
841 # special case smart search
843 $form->{"l_$_"} = 1 for qw(partnumber description unit sellprice lastcost cvar_packaging linetotal);
844 push @where_tokens, "p.partnumber ILIKE ? OR p.description ILIKE ?";
845 push @bind_vars, (like($form->{all})) x 2;
848 # special case insertdate
849 if (grep { trim($form->{$_}) } qw(insertdatefrom insertdateto)) {
850 $form->{"l_insertdate"} = 1;
851 push @select_tokens, 'insertdate';
853 my $token_builder = $make_token_builder->();
854 my $token = $token_builder->('insertdate');
856 for (qw(insertdatefrom insertdateto)) {
857 my $value = trim($form->{$_});
859 push @where_tokens, sprintf "$token %s ?", /from$/ ? '>=' : '<=';
860 push @bind_vars, $value;
864 if ($form->{"partsgroup_id"}) {
865 $form->{"l_partsgroup"} = '1'; # show the column
866 push @where_tokens, "pg.id = ?";
867 push @bind_vars, $form->{"partsgroup_id"};
870 if ($form->{shop} ne '') {
871 $form->{l_shop} = '1'; # show the column
872 if ($form->{shop} eq '0' || $form->{shop} eq 'f') {
873 push @where_tokens, 'NOT p.shop';
876 push @where_tokens, 'p.shop';
880 foreach (@like_filters) {
881 next unless $form->{$_};
882 $form->{"l_$_"} = '1'; # show the column
883 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
884 push @bind_vars, like($form->{$_});
887 foreach (@simple_l_switches) {
888 next unless $form->{"l_$_"};
889 push @select_tokens, $_;
892 for ($form->{searchitems}) {
893 push @where_tokens, "p.part_type = 'part'" if /part/;
894 push @where_tokens, "p.part_type = 'service'" if /service/;
895 push @where_tokens, "p.part_type = 'assembly'" if /assembly/;
898 for ($form->{itemstatus}) {
899 push @where_tokens, 'p.id NOT IN
900 (SELECT DISTINCT parts_id FROM invoice UNION
901 SELECT DISTINCT parts_id FROM assembly UNION
902 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
903 push @where_tokens, 'p.onhand = 0' if /orphaned/;
904 push @where_tokens, 'NOT p.obsolete' if /active/;
905 push @where_tokens, ' p.obsolete', if /obsolete/;
906 push @where_tokens, 'p.onhand > 0', if /onhand/;
907 push @where_tokens, 'p.onhand < p.rop', if /short/;
910 my $q_assembly_lastcost =
911 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
913 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
914 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
915 WHERE (a_lc.id = p.id)) AS lastcost|;
916 $table_prefix{$q_assembly_lastcost} = ' ';
918 # special case makemodel search
919 # all_parts is based upon the assumption that every parameter is named like the column it represents
920 # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
921 # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
923 push @where_tokens, 'mv.name ILIKE ?';
924 push @bind_vars, like($form->{make});
926 if ($form->{model}) {
927 push @where_tokens, 'mm.model ILIKE ?';
928 push @bind_vars, like($form->{model});
931 # special case: sorting by partnumber
932 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
933 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
934 # ToDO: implement proper functional sorting
935 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
936 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
937 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
938 # if $form->{sort} eq 'partnumber';
940 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
943 $limit_clause = " LIMIT 100" if $form->{top100};
944 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
946 #=== joins and complicated filters ========#
948 my $bsooqr = any { $form->{$_} } @oe_flags;
949 my @bsooqr_tokens = ();
951 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
952 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
953 push @select_tokens, $q_assembly_lastcost if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
954 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
955 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
956 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
957 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
958 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
959 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
960 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
962 $joins_needed{partsgroup} = 1;
963 $joins_needed{pfac} = 1;
964 $joins_needed{project} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
965 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
966 $joins_needed{mv} = 1 if $joins_needed{makemodel};
967 $joins_needed{cv} = 1 if $bsooqr;
968 $joins_needed{apoe} = 1 if $joins_needed{project} || $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
969 $joins_needed{invoice_oi} = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
971 # special case for description search.
972 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
973 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
974 # find the old entries in of @where_tokens and @bind_vars, and adjust them
975 if ($joins_needed{invoice_oi}) {
976 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
977 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
978 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
979 splice @bind_vars, $bi, 0, $bind_vars[$bi];
984 # now the master trick: soldtotal.
985 if ($form->{l_soldtotal}) {
986 push @where_tokens, 'NOT ioi.qty = 0';
987 push @group_tokens, @select_tokens;
988 map { s/.*\sAS\s+//si } @group_tokens;
989 push @select_tokens, 'SUM(ioi.qty)';
992 #============= build query ================#
994 my $token_builder = $make_token_builder->(\%joins_needed);
996 my @sort_cols = (@simple_filters, qw(id priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate insertdate shop));
997 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
998 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
999 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
1001 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
1002 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
1003 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
1004 my $group_clause = @group_tokens ? ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens : '';
1006 my %oe_flag_to_cvar = (
1007 bought => 'invoice',
1009 onorder => 'orderitems',
1010 ordered => 'orderitems',
1011 rfq => 'orderitems',
1012 quoted => 'orderitems',
1015 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
1017 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
1019 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
1023 $where_clause .= qq| AND ($cvar_where)|;
1024 push @bind_vars, @cvar_values;
1027 my $query = <<" SQL";
1028 SELECT DISTINCT $select_clause
1037 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1039 map { $_->{onhand} *= 1 } @{ $form->{parts} };
1041 # fix qty sign in ap. those are saved negative
1042 if ($bsooqr && $form->{bought}) {
1043 for my $row (@{ $form->{parts} }) {
1044 $row->{qty} *= -1 if $row->{module} eq 'ir';
1048 # post processing for assembly parts lists (bom)
1049 # for each part get the assembly parts and add them into the partlist.
1051 if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1053 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1054 p.unit, p.notes, p.itime::DATE as insertdate,
1055 p.sellprice, p.listprice, p.lastcost,
1056 p.rop, p.weight, p.priceupdate,
1057 p.image, p.drawing, p.microfiche,
1060 INNER JOIN assembly a ON (p.id = a.parts_id)
1063 my $sth = prepare_query($form, $dbh, $query);
1065 foreach my $item (@{ $form->{parts} }) {
1066 push(@assemblies, $item);
1067 do_statement($form, $sth, $query, conv_i($item->{id}));
1069 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1070 $ref->{assemblyitem} = 1;
1071 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1072 push(@assemblies, $ref);
1077 # copy assemblies to $form->{parts}
1078 $form->{parts} = \@assemblies;
1081 if ($form->{l_pricegroups} ) {
1083 SELECT parts_id, price, pricegroup_id
1088 my $sth = prepare_query($form, $dbh, $query);
1090 foreach my $part (@{ $form->{parts} }) {
1091 do_statement($form, $sth, $query, conv_i($part->{id}));
1093 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1094 $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
1101 $main::lxdebug->leave_sub();
1103 return @{ $form->{parts} };
1106 sub _create_filter_for_priceupdate {
1107 $main::lxdebug->enter_sub();
1110 my $myconfig = \%main::myconfig;
1111 my $form = $main::form;
1114 my $where = '1 = 1';
1116 foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1118 $column =~ s/.*\.//;
1119 next unless ($form->{$column});
1121 $where .= qq| AND $item ILIKE ?|;
1122 push(@where_values, like($form->{$column}));
1125 foreach my $item (qw(description serialnumber)) {
1126 next unless ($form->{$item});
1128 $where .= qq| AND (${item} ILIKE ?)|;
1129 push(@where_values, like($form->{$item}));
1133 # items which were never bought, sold or on an order
1134 if ($form->{itemstatus} eq 'orphaned') {
1136 qq| AND (p.onhand = 0)
1139 SELECT DISTINCT parts_id FROM invoice
1141 SELECT DISTINCT parts_id FROM assembly
1143 SELECT DISTINCT parts_id FROM orderitems
1146 } elsif ($form->{itemstatus} eq 'active') {
1147 $where .= qq| AND p.obsolete = '0'|;
1149 } elsif ($form->{itemstatus} eq 'obsolete') {
1150 $where .= qq| AND p.obsolete = '1'|;
1152 } elsif ($form->{itemstatus} eq 'onhand') {
1153 $where .= qq| AND p.onhand > 0|;
1155 } elsif ($form->{itemstatus} eq 'short') {
1156 $where .= qq| AND p.onhand < p.rop|;
1160 foreach my $column (qw(make model)) {
1161 next unless ($form->{$column});
1162 $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1163 push(@where_values, like($form->{$column}));
1166 $main::lxdebug->leave_sub();
1168 return ($where, @where_values);
1171 sub get_num_matches_for_priceupdate {
1172 $main::lxdebug->enter_sub();
1176 my $myconfig = \%main::myconfig;
1177 my $form = $main::form;
1179 my $dbh = $form->get_standard_dbh($myconfig);
1181 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1183 my $num_updated = 0;
1186 for my $column (qw(sellprice listprice)) {
1187 next if ($form->{$column} eq "");
1195 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1197 my ($result) = selectfirst_array_query($form, $dbh, $query, @where_values);
1198 $num_updated += $result if (0 <= $result);
1207 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1208 WHERE $where) AND (pricegroup_id = ?)|;
1209 my $sth = prepare_query($form, $dbh, $query);
1211 for my $i (1 .. $form->{price_rows}) {
1212 next if ($form->{"price_$i"} eq "");
1214 my ($result) = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1215 $num_updated += $result if (0 <= $result);
1219 $main::lxdebug->leave_sub();
1221 return $num_updated;
1225 my ($self, $myconfig, $form) = @_;
1226 $main::lxdebug->enter_sub();
1228 my $num_updated = SL::DB->client->with_transaction(\&_update_prices, $self, $myconfig, $form);
1230 $main::lxdebug->leave_sub();
1231 return $num_updated;
1234 sub _update_prices {
1235 my ($self, $myconfig, $form) = @_;
1237 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1238 my $num_updated = 0;
1240 # connect to database
1241 my $dbh = SL::DB->client->dbh;
1243 for my $column (qw(sellprice listprice)) {
1244 next if ($form->{$column} eq "");
1246 my $value = $form->parse_amount($myconfig, $form->{$column});
1249 if ($form->{"${column}_type"} eq "percent") {
1250 $value = ($value / 100) + 1;
1255 qq|UPDATE parts SET $column = $column $operator ?
1259 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1261 my $result = do_query($form, $dbh, $query, $value, @where_values);
1262 $num_updated += $result if (0 <= $result);
1266 qq|UPDATE prices SET price = price + ?
1270 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1271 WHERE $where) AND (pricegroup_id = ?)|;
1272 my $sth_add = prepare_query($form, $dbh, $q_add);
1275 qq|UPDATE prices SET price = price * ?
1279 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1280 WHERE $where) AND (pricegroup_id = ?)|;
1281 my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1283 for my $i (1 .. $form->{price_rows}) {
1284 next if ($form->{"price_$i"} eq "");
1286 my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1289 if ($form->{"pricegroup_type_$i"} eq "percent") {
1290 $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1292 $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1295 $num_updated += $result if (0 <= $result);
1299 $sth_multiply->finish();
1301 return $num_updated;
1305 $main::lxdebug->enter_sub();
1307 my ($self, $module, $myconfig, $form) = @_;
1309 # connect to database
1310 my $dbh = $form->get_standard_dbh;
1312 my @values = like($module);
1317 qq|SELECT c.accno, c.description, c.link, c.id,
1318 p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1319 FROM chart c, parts p
1320 WHERE (c.link LIKE ?) AND (p.id = ?)
1322 push(@values, conv_i($form->{id}));
1326 qq|SELECT c.accno, c.description, c.link, c.id,
1327 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1328 FROM chart c, defaults d
1333 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1334 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1335 foreach my $key (split(/:/, $ref->{link})) {
1336 if ($key =~ /\Q$module\E/) {
1337 if ( ($ref->{id} eq $ref->{inventory_accno_id})
1338 || ($ref->{id} eq $ref->{income_accno_id})
1339 || ($ref->{id} eq $ref->{expense_accno_id})) {
1340 push @{ $form->{"${module}_links"}{$key} },
1341 { accno => $ref->{accno},
1342 description => $ref->{description},
1343 selected => "selected" };
1344 $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1346 push @{ $form->{"${module}_links"}{$key} },
1347 { accno => $ref->{accno},
1348 description => $ref->{description},
1356 # get buchungsgruppen
1357 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1360 $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1363 ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1366 $main::lxdebug->leave_sub();
1369 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1371 $main::lxdebug->enter_sub();
1373 my ($self, $myconfig, $form, $sortorder) = @_;
1374 my $dbh = $form->get_standard_dbh;
1375 my $order = qq| p.partnumber|;
1376 my $where = qq|1 = 1|;
1379 if ($sortorder eq "all") {
1380 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1381 push(@values, like($form->{partnumber}), like($form->{description}));
1383 } elsif ($sortorder eq "partnumber") {
1384 $where .= qq| AND (partnumber ILIKE ?)|;
1385 push(@values, like($form->{partnumber}));
1387 } elsif ($sortorder eq "description") {
1388 $where .= qq| AND (description ILIKE ?)|;
1389 push(@values, like($form->{description}));
1390 $order = "description";
1395 qq|SELECT id, partnumber, description, unit, sellprice
1397 WHERE $where ORDER BY $order|;
1399 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1402 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1403 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1408 $form->{"id_$j"} = $ref->{id};
1409 $form->{"partnumber_$j"} = $ref->{partnumber};
1410 $form->{"description_$j"} = $ref->{description};
1411 $form->{"unit_$j"} = $ref->{unit};
1412 $form->{"sellprice_$j"} = $ref->{sellprice};
1413 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
1418 $main::lxdebug->leave_sub();
1423 # gets sum of sold part with part_id
1425 $main::lxdebug->enter_sub();
1427 my ($dbh, $id) = @_;
1429 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1430 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1433 $main::lxdebug->leave_sub();
1436 } #end get_soldtotal
1438 sub retrieve_languages {
1439 $main::lxdebug->enter_sub();
1441 my ($self, $myconfig, $form) = @_;
1443 # connect to database
1444 my $dbh = $form->get_standard_dbh;
1450 if ($form->{language_values} ne "") {
1452 qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1454 LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1455 ORDER BY lower(l.description)|;
1456 @values = (conv_i($form->{id}));
1459 $query = qq|SELECT id, description
1461 ORDER BY lower(description)|;
1464 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1466 $main::lxdebug->leave_sub();
1471 sub follow_account_chain {
1472 $main::lxdebug->enter_sub(2);
1474 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1476 my @visited_accno_ids = ($accno_id);
1480 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
1481 map { $_->{id} => $_ }
1482 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
1483 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
1485 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
1486 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
1490 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
1491 last unless ($ref && $ref->{"is_valid"} &&
1492 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1493 $accno_id = $ref->{"new_chart_id"};
1494 $accno = $ref->{"accno"};
1495 push(@visited_accno_ids, $accno_id);
1498 $main::lxdebug->leave_sub(2);
1500 return ($accno_id, $accno);
1503 sub retrieve_accounts {
1504 $main::lxdebug->enter_sub;
1507 my $myconfig = shift;
1509 my $dbh = $form->get_standard_dbh;
1510 my %args = @_; # index => part_id
1512 $form->{taxzone_id} *= 1;
1514 return unless grep $_, values %args; # shortfuse if no part_id supplied
1516 # transdate madness.
1518 if ($form->{type} eq "invoice" or $form->{type} eq "credit_note") {
1519 # use deliverydate for sales and purchase invoice, if it exists
1520 # also use deliverydate for credit notes
1521 if (!$form->{deliverydate}) {
1522 $transdate = $form->{invdate};
1524 $transdate = $form->{deliverydate};
1526 } elsif ($form->{script} eq 'ir.pl') {
1527 # when a purchase invoice is opened from the report of purchase invoices
1528 # $form->{type} isn't set, but $form->{script} is, not sure why this is or
1529 # whether this distinction matters in some other scenario. Otherwise one
1530 # could probably take out this elsif and add a
1531 # " or $form->{script} eq 'ir.pl' "
1532 # to the above if-statement
1533 if (!$form->{deliverydate}) {
1534 $transdate = $form->{invdate};
1536 $transdate = $form->{deliverydate};
1538 } elsif (($form->{type} eq "credit_note") and $form->{deliverydate}) {
1539 # if credit_note has a deliverydate, use this instead of invdate
1540 # useful for credit_notes of invoices from an old period with different tax
1541 # if there is no deliverydate then invdate is used, old default (see next elsif)
1542 # Falls hier der Stichtag für Steuern anders bestimmt wird,
1543 # entsprechend auch bei Taxkeys.pm anpassen
1544 $transdate = $form->{deliverydate};
1545 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1546 $transdate = $form->{invdate};
1548 $transdate = $form->{transdate};
1551 if ($transdate eq "") {
1552 $transdate = DateTime->today_local->to_lxoffice;
1554 $transdate = $dbh->quote($transdate);
1557 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
1559 my @part_ids = grep { $_ } values %args;
1560 my $in = join ',', ('?') x @part_ids;
1562 my %accno_by_part = map { $_->{id} => $_ }
1563 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
1565 p.id, p.inventory_accno_id AS is_part,
1566 bg.inventory_accno_id,
1567 tc.income_accno_id AS income_accno_id,
1568 tc.expense_accno_id AS expense_accno_id,
1569 c1.accno AS inventory_accno,
1570 c2.accno AS income_accno,
1571 c3.accno AS expense_accno
1573 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
1574 LEFT JOIN taxzone_charts tc on bg.id = tc.buchungsgruppen_id
1575 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1576 LEFT JOIN chart c2 ON tc.income_accno_id = c2.id
1577 LEFT JOIN chart c3 ON tc.expense_accno_id = c3.id
1579 tc.taxzone_id = '$form->{taxzone_id}'
1584 my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1585 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1587 LEFT JOIN chart c ON c.id = t.chart_id
1591 WHERE tk.chart_id = ? AND startdate <= ?
1592 ORDER BY startdate DESC LIMIT 1)
1595 while (my ($index => $part_id) = each %args) {
1596 my $ref = $accno_by_part{$part_id} or next;
1598 $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
1601 for my $type (qw(inventory income expense)) {
1602 next unless $ref->{"${type}_accno_id"};
1603 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1604 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1607 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1609 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1610 $ref = $sth_tax->fetchrow_hashref or next;
1612 $form->{"taxaccounts_$index"} = $ref->{"accno"};
1613 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1615 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1620 $::lxdebug->leave_sub;
1623 sub get_basic_part_info {
1624 $main::lxdebug->enter_sub();
1629 Common::check_params(\%params, qw(id));
1631 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1634 $main::lxdebug->leave_sub();
1638 my $myconfig = \%main::myconfig;
1639 my $form = $main::form;
1641 my $dbh = $form->get_standard_dbh($myconfig);
1643 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1645 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1647 if ('' eq ref $params{id}) {
1648 $info = $info->[0] || { };
1650 $main::lxdebug->leave_sub();
1654 my %info_map = map { $_->{id} => $_ } @{ $info };
1656 $main::lxdebug->leave_sub();
1661 sub prepare_parts_for_printing {
1662 $main::lxdebug->enter_sub();
1667 my $myconfig = $params{myconfig} || \%main::myconfig;
1668 my $form = $params{form} || $main::form;
1670 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1672 my $prefix = $params{prefix} || 'id_';
1673 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1675 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1678 $main::lxdebug->leave_sub();
1682 my $placeholders = join ', ', ('?') x scalar(@part_ids);
1683 my $query = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
1685 LEFT JOIN vendor v ON (mm.make = v.id)
1686 WHERE mm.parts_id IN ($placeholders)|;
1690 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
1692 while (my $ref = $sth->fetchrow_hashref()) {
1693 $makemodel{$ref->{parts_id}} ||= [];
1694 push @{ $makemodel{$ref->{parts_id}} }, $ref;
1699 my @columns = qw(ean image microfiche drawing);
1701 $query = qq|SELECT id, | . join(', ', @columns) . qq|
1703 WHERE id IN ($placeholders)|;
1705 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1707 my %template_arrays;
1708 map { $template_arrays{$_} = [] } (qw(make model), @columns);
1710 foreach my $i (1 .. $rowcount) {
1711 my $id = $form->{"${prefix}${i}"};
1715 foreach (@columns) {
1716 push @{ $template_arrays{$_} }, $data{$id}->{$_};
1719 push @{ $template_arrays{make} }, [];
1720 push @{ $template_arrays{model} }, [];
1722 next if (!$makemodel{$id});
1724 foreach my $ref (@{ $makemodel{$id} }) {
1725 map { push @{ $template_arrays{$_}->[-1] }, $ref->{$_} } qw(make model);
1729 my $parts = SL::DB::Manager::Part->get_all(query => [ id => \@part_ids ]);
1730 my %parts_by_id = map { $_->id => $_ } @$parts;
1732 for my $i (1..$rowcount) {
1733 my $id = $form->{"${prefix}${i}"};
1736 push @{ $template_arrays{part_type} }, $parts_by_id{$id}->type;
1739 return %template_arrays;
1740 $main::lxdebug->leave_sub();
1743 sub normalize_text_blocks {
1744 $main::lxdebug->enter_sub();
1749 my $form = $params{form} || $main::form;
1751 # check if feature is enabled (select normalize_part_descriptions from defaults)
1752 return unless ($::instance_conf->get_normalize_part_descriptions);
1754 foreach (qw(description notes)) {
1755 $form->{$_} =~ s/\s+$//s;
1756 $form->{$_} =~ s/^\s+//s;
1757 $form->{$_} =~ s/ {2,}/ /g;
1759 $main::lxdebug->leave_sub();