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 die "part needs a part_type" unless $form->{part_type}; # TODO from part_type enum conversion
82 # part or service item
83 $form->{item} = $form->{part_type};
84 if ($form->{item} eq 'assembly') {
86 # retrieve assembly items
88 qq|SELECT p.id, p.partnumber, p.description,
89 p.sellprice, p.lastcost, p.weight, a.qty, a.bom, p.unit,
90 pg.partsgroup, p.price_factor_id, pfac.factor AS price_factor
92 JOIN assembly a ON (a.parts_id = p.id)
93 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
94 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
97 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
99 $form->{assembly_rows} = 0;
100 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
101 $form->{assembly_rows}++;
102 foreach my $key (keys %{$ref}) {
103 $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
110 # setup accno hash for <option checked> {amount} is used in create_links
111 $form->{amount}{IC} = $form->{inventory_accno};
112 $form->{amount}{IC_income} = $form->{income_accno};
113 $form->{amount}{IC_sale} = $form->{income_accno};
114 $form->{amount}{IC_expense} = $form->{expense_accno};
115 $form->{amount}{IC_cogs} = $form->{expense_accno};
119 SELECT pg.pricegroup, pg.id AS pricegroup_id, COALESCE(pr.price, 0) AS price
121 LEFT JOIN prices pr ON (pr.pricegroup_id = pg.id) AND (pr.parts_id = ?)
122 ORDER BY lower(pg.pricegroup)
126 foreach $ref (selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}))) {
127 $form->{"${_}_${row}"} = $ref->{$_} for qw(pricegroup_id pricegroup price);
130 $form->{price_rows} = $row - 1;
133 if ($form->{makemodel}) {
135 $query = qq|SELECT m.make, m.model,m.lastcost,m.lastcost,m.lastupdate,m.sortorder FROM makemodel m | .
136 qq|WHERE m.parts_id = ? order by m.sortorder asc|;
137 my @values = ($form->{id});
138 $sth = $dbh->prepare($query);
139 $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
143 while (($form->{"make_$i"}, $form->{"model_$i"}, $form->{"old_lastcost_$i"},
144 $form->{"lastcost_$i"}, $form->{"lastupdate_$i"}, $form->{"sortorder_$i"}) = $sth->fetchrow_array)
149 $form->{makemodel_rows} = $i - 1;
154 $query = qq|SELECT language_id, translation, longdescription
157 $form->{translations} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
160 my @referencing_tables = qw(invoice orderitems inventory);
161 my %column_map = ( );
162 my $parts_id = conv_i($form->{id});
164 $form->{orphaned} = 1;
166 foreach my $table (@referencing_tables) {
167 my $column = $column_map{$table} || 'parts_id';
168 $query = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
169 my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
172 $form->{orphaned} = 0;
177 $form->{"unit_changeable"} = $form->{orphaned};
179 Common::webdav_folder($form) if $::lx_office_conf{features}{webdav};
181 $main::lxdebug->leave_sub();
184 sub get_pricegroups {
185 $main::lxdebug->enter_sub();
187 my ($self, $myconfig, $form) = @_;
189 my $dbh = $form->get_standard_dbh;
192 my $query = qq|SELECT id, pricegroup FROM pricegroup ORDER BY lower(pricegroup)|;
193 my $pricegroups = selectall_hashref_query($form, $dbh, $query);
196 foreach my $pg (@{ $pricegroups }) {
197 $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
198 $form->{"pricegroup_id_$i"} = "$pg->{id}";
199 $form->{"pricegroup_$i"} = "$pg->{pricegroup}";
204 $form->{price_rows} = $i - 1;
206 $main::lxdebug->leave_sub();
211 sub retrieve_buchungsgruppen {
212 $main::lxdebug->enter_sub();
214 my ($self, $myconfig, $form) = @_;
218 my $dbh = $form->get_standard_dbh;
220 # get buchungsgruppen
221 $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
222 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
224 $main::lxdebug->leave_sub();
228 my ($self, $myconfig, $form) = @_;
229 $main::lxdebug->enter_sub();
231 my $rc = SL::DB->client->with_transaction(\&_save, $self, $myconfig, $form);
233 $main::lxdebug->leave_sub();
238 my ($self, $myconfig, $form) = @_;
241 my $dbh = SL::DB->client->dbh;
242 my $restricter = SL::HTML::Restrict->create;
245 # make up a unique handle and store in partnumber field
246 # then retrieve the record based on the unique handle to get the id
247 # replace the partnumber field with the actual variable
248 # add records for makemodel
250 # if there is a $form->{id} then replace the old entry
251 # delete all makemodel entries and add the new ones
253 # undo amount formatting
254 map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
255 qw(rop weight listprice sellprice gv lastcost);
257 my $makemodel = ($form->{make_1} || $form->{model_1} || ($form->{makemodel_rows} > 1)) ? 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, part_type) VALUES (?, ?, ?, ?)|, $form->{id}, $form->{partnumber}, $form->{unit}, $form->{item});
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();
348 buchungsgruppen_id = ?,
350 inventory_accno_id = $subq_inventory,
351 income_accno_id = (SELECT tc.income_accno_id FROM taxzone_charts tc WHERE tc.taxzone_id = 0 and tc.buchungsgruppen_id = ?),
352 expense_accno_id = $subq_expense,
361 not_discountable = ?,
368 @values = ($form->{partnumber},
369 $form->{description},
370 $makemodel ? 't' : 'f',
376 $restricter->process($form->{notes}),
379 conv_i($form->{warehouse_id}),
380 conv_i($form->{bin_id}),
381 conv_i($form->{buchungsgruppen_id}),
382 conv_i($form->{payment_id}),
383 conv_i($form->{buchungsgruppen_id}),
384 $form->{obsolete} ? 't' : 'f',
387 $form->{shop} ? 't' : 'f',
391 $form->{has_sernumber} ? 't' : 'f',
392 $form->{not_discountable} ? 't' : 'f',
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.part_type = 'assembly' $where|;
580 $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
582 $main::lxdebug->leave_sub();
586 my ($self, $myconfig, $form) = @_;
587 $main::lxdebug->enter_sub();
589 my $rc = SL::DB->client->with_transaction(\&_delete, $self, $myconfig, $form);
591 $main::lxdebug->leave_sub();
596 my ($self, $myconfig, $form) = @_;
597 my @values = (conv_i($form->{id}));
599 my %columns = ( "assembly" => "id", "parts" => "id" );
601 for my $table (qw(prices makemodel inventory assembly translation parts)) {
602 my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
603 do_query($form, SL::DB->client->dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
610 $main::lxdebug->enter_sub();
612 my ($self, $myconfig, $form) = @_;
614 my $i = $form->{assembly_rows};
616 my $where = qq|1 = 1|;
619 my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
621 while (my ($column, $table) = each(%columns)) {
622 next unless ($form->{"${column}_$i"});
623 $where .= qq| AND ${table}.${column} ILIKE ?|;
624 push(@values, like($form->{"${column}_$i"}));
628 $where .= qq| AND NOT (p.id = ?)|;
629 push(@values, conv_i($form->{id}));
632 # Search for part ID overrides all other criteria.
633 if ($form->{"id_${i}"}) {
634 $where = qq|p.id = ?|;
635 @values = ($form->{"id_${i}"});
638 if ($form->{partnumber}) {
639 $where .= qq| ORDER BY p.partnumber|;
641 $where .= qq| ORDER BY p.description|;
645 qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
646 p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
647 p.price_factor_id, pfac.factor AS price_factor, p.notes as longdescription
649 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
650 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
652 $form->{item_list} = selectall_hashref_query($form, SL::DB->client->dbh, $query, @values);
654 $main::lxdebug->leave_sub();
659 # Warning, deep magic ahead.
660 # This function gets all parts from the database according to the filters specified
663 # sort revers - sorting field + direction
666 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
667 # partnumber ean description partsgroup microfiche drawing
670 # 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
673 # itemstatus = active | onhand | short | obsolete | orphaned
674 # searchitems = part | assembly | service
677 # make model - makemodel
678 # serialnumber transdatefrom transdateto - invoice/orderitems
681 # bought sold onorder ordered rfq quoted - aggreg joins with invoices/orders
682 # l_linetotal l_subtotal - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
683 # l_soldtotal - aggreg join to display total of sold quantity
684 # onhand - as above, but masking the simple itemstatus results (doh!)
685 # short - NOT IMPLEMENTED as form filter, only as itemstatus option
686 # l_serialnumber - belonges to serialnumber filter
687 # l_deliverydate - displays deliverydate is sold etc. flags are active
688 # l_soldtotal - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
691 # onhand - as above, but masking the simple itemstatus results (doh!)
693 # search by overrides of description
695 # disabled sanity checks and changes:
696 # - searchitems = assembly will no longer disable bought
697 # - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
698 # - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
699 # - itemstatus = obsolete will no longer disable onhand, short
700 # - allow sorting by ean
701 # - serialnumber filter also works if l_serialnumber isn't ticked
702 # - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
705 $main::lxdebug->enter_sub();
707 my ($self, $myconfig, $form) = @_;
708 my $dbh = $form->get_standard_dbh($myconfig);
710 $form->{parts} = +{ };
711 $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
713 my @simple_filters = qw(partnumber ean description partsgroup microfiche drawing onhand);
714 my @project_filters = qw(projectnumber projectdescription);
715 my @makemodel_filters = qw(make model);
716 my @invoice_oi_filters = qw(serialnumber soldtotal);
717 my @apoe_filters = qw(transdate);
718 my @like_filters = (@simple_filters, @invoice_oi_filters);
719 my @all_columns = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
720 my @simple_l_switches = (@all_columns, qw(notes listprice sellprice lastcost priceupdate weight unit rop image shop insertdate));
721 my @oe_flags = qw(bought sold onorder ordered rfq quoted);
722 my @qsooqr_flags = qw(invnumber ordnumber quonumber trans_id name module qty);
723 my @deliverydate_flags = qw(deliverydate);
724 # my @other_flags = qw(onhand); # ToDO: implement these
725 # my @inactive_flags = qw(l_subtotal short l_linetotal);
727 my @select_tokens = qw(id factor);
728 my @where_tokens = qw(1=1);
729 my @group_tokens = ();
731 my %joins_needed = ();
734 partsgroup => 'LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)',
735 makemodel => 'LEFT JOIN makemodel mm ON (mm.parts_id = p.id)',
736 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
739 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, project_id, id FROM invoice UNION
740 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
741 ) AS ioi ON ioi.parts_id = p.id|,
744 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
745 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
746 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
747 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
750 SELECT id, name, 'customer' AS cv FROM customer UNION
751 SELECT id, name, 'vendor' AS cv FROM vendor
752 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
753 mv => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
754 project => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
756 my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project);
759 deliverydate => 'apoe.', serialnumber => 'ioi.',
760 transdate => 'apoe.', trans_id => 'ioi.',
761 module => 'apoe.', name => 'cv.',
762 ordnumber => 'apoe.', make => 'mm.',
763 quonumber => 'apoe.', model => 'mm.',
764 invnumber => 'apoe.', partsgroup => 'pg.',
765 lastcost => 'p.', , soldtotal => ' ',
766 factor => 'pfac.', projectnumber => 'pj.',
767 'SUM(ioi.qty)' => ' ', projectdescription => 'pj.',
770 serialnumber => 'ioi.',
771 quotation => 'apoe.',
777 # if the join condition in these blocks are met, the column
778 # of the scecified table will gently override (coalesce actually) the original value
779 # use it to conditionally coalesce values from subtables
780 my @column_override = (
781 # column name, prefix, joins_needed, nick name (in case column is named like another)
782 [ 'description', 'ioi.', 'invoice_oi' ],
783 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
784 [ 'transdate', 'apoe.', 'apoe' ],
785 [ 'unit', 'ioi.', 'invoice_oi' ],
786 [ 'sellprice', 'ioi.', 'invoice_oi' ],
789 # careful with renames. these are HARD, and any filters done on the original column will break
790 my %renamed_columns = (
791 'factor' => 'price_factor',
792 'SUM(ioi.qty)' => 'soldtotal',
793 'ioi.id' => 'ioi_id',
795 'projectdescription' => 'projectdescription',
796 'insertdate' => 'insertdate',
800 projectdescription => 'description',
801 insertdate => 'itime::DATE',
804 if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
805 @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
808 my $make_token_builder = sub {
809 my $joins_needed = shift;
811 my ($nick, $alias) = @_;
812 my ($col) = $real_column{$nick} || $nick;
813 my @coalesce_tokens =
814 map { ($_->[1] || 'p.') . $_->[0] }
815 grep { !$_->[2] || $joins_needed->{$_->[2]} }
816 grep { ($_->[3] || $_->[0]) eq $nick }
817 @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
819 my $coalesce = scalar @coalesce_tokens > 1;
821 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
822 : shift @coalesce_tokens)
823 . ($alias && ($coalesce || $renamed_columns{$nick})
824 ? " AS " . ($renamed_columns{$nick} || $nick)
829 #===== switches and simple filters ========#
831 # special case transdate
832 if (grep { trim($form->{$_}) } qw(transdatefrom transdateto)) {
833 $form->{"l_transdate"} = 1;
834 push @select_tokens, 'transdate';
835 for (qw(transdatefrom transdateto)) {
836 my $value = trim($form->{$_});
838 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
839 push @bind_vars, $value;
843 # special case smart search
845 $form->{"l_$_"} = 1 for qw(partnumber description unit sellprice lastcost cvar_packaging linetotal);
846 push @where_tokens, "p.partnumber ILIKE ? OR p.description ILIKE ?";
847 push @bind_vars, (like($form->{all})) x 2;
850 # special case insertdate
851 if (grep { trim($form->{$_}) } qw(insertdatefrom insertdateto)) {
852 $form->{"l_insertdate"} = 1;
853 push @select_tokens, 'insertdate';
855 my $token_builder = $make_token_builder->();
856 my $token = $token_builder->('insertdate');
858 for (qw(insertdatefrom insertdateto)) {
859 my $value = trim($form->{$_});
861 push @where_tokens, sprintf "$token %s ?", /from$/ ? '>=' : '<=';
862 push @bind_vars, $value;
866 if ($form->{"partsgroup_id"}) {
867 $form->{"l_partsgroup"} = '1'; # show the column
868 push @where_tokens, "pg.id = ?";
869 push @bind_vars, $form->{"partsgroup_id"};
872 if ($form->{shop} ne '') {
873 $form->{l_shop} = '1'; # show the column
874 if ($form->{shop} eq '0' || $form->{shop} eq 'f') {
875 push @where_tokens, 'NOT p.shop';
878 push @where_tokens, 'p.shop';
882 foreach (@like_filters) {
883 next unless $form->{$_};
884 $form->{"l_$_"} = '1'; # show the column
885 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
886 push @bind_vars, like($form->{$_});
889 foreach (@simple_l_switches) {
890 next unless $form->{"l_$_"};
891 push @select_tokens, $_;
894 for ($form->{searchitems}) {
895 push @where_tokens, "p.part_type = 'part'" if /part/;
896 push @where_tokens, "p.part_type = 'service'" if /service/;
897 push @where_tokens, "p.part_type = 'assembly'" if /assembly/;
900 for ($form->{itemstatus}) {
901 push @where_tokens, 'p.id NOT IN
902 (SELECT DISTINCT parts_id FROM invoice UNION
903 SELECT DISTINCT parts_id FROM assembly UNION
904 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
905 push @where_tokens, 'p.onhand = 0' if /orphaned/;
906 push @where_tokens, 'NOT p.obsolete' if /active/;
907 push @where_tokens, ' p.obsolete', if /obsolete/;
908 push @where_tokens, 'p.onhand > 0', if /onhand/;
909 push @where_tokens, 'p.onhand < p.rop', if /short/;
912 my $q_assembly_lastcost =
913 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
915 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
916 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
917 WHERE (a_lc.id = p.id)) AS lastcost|;
918 $table_prefix{$q_assembly_lastcost} = ' ';
920 # special case makemodel search
921 # all_parts is based upon the assumption that every parameter is named like the column it represents
922 # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
923 # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
925 push @where_tokens, 'mv.name ILIKE ?';
926 push @bind_vars, like($form->{make});
928 if ($form->{model}) {
929 push @where_tokens, 'mm.model ILIKE ?';
930 push @bind_vars, like($form->{model});
933 # special case: sorting by partnumber
934 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
935 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
936 # ToDO: implement proper functional sorting
937 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
938 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
939 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
940 # if $form->{sort} eq 'partnumber';
942 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
945 $limit_clause = " LIMIT 100" if $form->{top100};
946 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
948 #=== joins and complicated filters ========#
950 my $bsooqr = any { $form->{$_} } @oe_flags;
951 my @bsooqr_tokens = ();
953 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
954 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
955 push @select_tokens, $q_assembly_lastcost if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
956 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
957 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
958 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
959 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
960 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
961 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
962 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
964 $joins_needed{partsgroup} = 1;
965 $joins_needed{pfac} = 1;
966 $joins_needed{project} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
967 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
968 $joins_needed{mv} = 1 if $joins_needed{makemodel};
969 $joins_needed{cv} = 1 if $bsooqr;
970 $joins_needed{apoe} = 1 if $joins_needed{project} || $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
971 $joins_needed{invoice_oi} = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
973 # special case for description search.
974 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
975 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
976 # find the old entries in of @where_tokens and @bind_vars, and adjust them
977 if ($joins_needed{invoice_oi}) {
978 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
979 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
980 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
981 splice @bind_vars, $bi, 0, $bind_vars[$bi];
986 # now the master trick: soldtotal.
987 if ($form->{l_soldtotal}) {
988 push @where_tokens, 'NOT ioi.qty = 0';
989 push @group_tokens, @select_tokens;
990 map { s/.*\sAS\s+//si } @group_tokens;
991 push @select_tokens, 'SUM(ioi.qty)';
994 #============= build query ================#
996 my $token_builder = $make_token_builder->(\%joins_needed);
998 my @sort_cols = (@simple_filters, qw(id priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate insertdate shop));
999 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
1000 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
1001 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
1003 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
1004 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
1005 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
1006 my $group_clause = @group_tokens ? ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens : '';
1008 my %oe_flag_to_cvar = (
1009 bought => 'invoice',
1011 onorder => 'orderitems',
1012 ordered => 'orderitems',
1013 rfq => 'orderitems',
1014 quoted => 'orderitems',
1017 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
1019 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
1021 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
1025 $where_clause .= qq| AND ($cvar_where)|;
1026 push @bind_vars, @cvar_values;
1029 my $query = <<" SQL";
1030 SELECT DISTINCT $select_clause
1039 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1041 map { $_->{onhand} *= 1 } @{ $form->{parts} };
1043 # fix qty sign in ap. those are saved negative
1044 if ($bsooqr && $form->{bought}) {
1045 for my $row (@{ $form->{parts} }) {
1046 $row->{qty} *= -1 if $row->{module} eq 'ir';
1050 # post processing for assembly parts lists (bom)
1051 # for each part get the assembly parts and add them into the partlist.
1053 if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1055 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1056 p.unit, p.notes, p.itime::DATE as insertdate,
1057 p.sellprice, p.listprice, p.lastcost,
1058 p.rop, p.weight, p.priceupdate,
1059 p.image, p.drawing, p.microfiche,
1062 INNER JOIN assembly a ON (p.id = a.parts_id)
1065 my $sth = prepare_query($form, $dbh, $query);
1067 foreach my $item (@{ $form->{parts} }) {
1068 push(@assemblies, $item);
1069 do_statement($form, $sth, $query, conv_i($item->{id}));
1071 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1072 $ref->{assemblyitem} = 1;
1073 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1074 push(@assemblies, $ref);
1079 # copy assemblies to $form->{parts}
1080 $form->{parts} = \@assemblies;
1083 if ($form->{l_pricegroups} ) {
1085 SELECT parts_id, price, pricegroup_id
1090 my $sth = prepare_query($form, $dbh, $query);
1092 foreach my $part (@{ $form->{parts} }) {
1093 do_statement($form, $sth, $query, conv_i($part->{id}));
1095 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1096 $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
1103 $main::lxdebug->leave_sub();
1105 return @{ $form->{parts} };
1108 sub _create_filter_for_priceupdate {
1109 $main::lxdebug->enter_sub();
1112 my $myconfig = \%main::myconfig;
1113 my $form = $main::form;
1116 my $where = '1 = 1';
1118 foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1120 $column =~ s/.*\.//;
1121 next unless ($form->{$column});
1123 $where .= qq| AND $item ILIKE ?|;
1124 push(@where_values, like($form->{$column}));
1127 foreach my $item (qw(description serialnumber)) {
1128 next unless ($form->{$item});
1130 $where .= qq| AND (${item} ILIKE ?)|;
1131 push(@where_values, like($form->{$item}));
1135 # items which were never bought, sold or on an order
1136 if ($form->{itemstatus} eq 'orphaned') {
1138 qq| AND (p.onhand = 0)
1141 SELECT DISTINCT parts_id FROM invoice
1143 SELECT DISTINCT parts_id FROM assembly
1145 SELECT DISTINCT parts_id FROM orderitems
1148 } elsif ($form->{itemstatus} eq 'active') {
1149 $where .= qq| AND p.obsolete = '0'|;
1151 } elsif ($form->{itemstatus} eq 'obsolete') {
1152 $where .= qq| AND p.obsolete = '1'|;
1154 } elsif ($form->{itemstatus} eq 'onhand') {
1155 $where .= qq| AND p.onhand > 0|;
1157 } elsif ($form->{itemstatus} eq 'short') {
1158 $where .= qq| AND p.onhand < p.rop|;
1162 foreach my $column (qw(make model)) {
1163 next unless ($form->{$column});
1164 $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1165 push(@where_values, like($form->{$column}));
1168 $main::lxdebug->leave_sub();
1170 return ($where, @where_values);
1173 sub get_num_matches_for_priceupdate {
1174 $main::lxdebug->enter_sub();
1178 my $myconfig = \%main::myconfig;
1179 my $form = $main::form;
1181 my $dbh = $form->get_standard_dbh($myconfig);
1183 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1185 my $num_updated = 0;
1188 for my $column (qw(sellprice listprice)) {
1189 next if ($form->{$column} eq "");
1197 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1199 my ($result) = selectfirst_array_query($form, $dbh, $query, @where_values);
1200 $num_updated += $result if (0 <= $result);
1209 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1210 WHERE $where) AND (pricegroup_id = ?)|;
1211 my $sth = prepare_query($form, $dbh, $query);
1213 for my $i (1 .. $form->{price_rows}) {
1214 next if ($form->{"price_$i"} eq "");
1216 my ($result) = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1217 $num_updated += $result if (0 <= $result);
1221 $main::lxdebug->leave_sub();
1223 return $num_updated;
1227 my ($self, $myconfig, $form) = @_;
1228 $main::lxdebug->enter_sub();
1230 my $num_updated = SL::DB->client->with_transaction(\&_update_prices, $self, $myconfig, $form);
1232 $main::lxdebug->leave_sub();
1233 return $num_updated;
1236 sub _update_prices {
1237 my ($self, $myconfig, $form) = @_;
1239 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1240 my $num_updated = 0;
1242 # connect to database
1243 my $dbh = SL::DB->client->dbh;
1245 for my $column (qw(sellprice listprice)) {
1246 next if ($form->{$column} eq "");
1248 my $value = $form->parse_amount($myconfig, $form->{$column});
1251 if ($form->{"${column}_type"} eq "percent") {
1252 $value = ($value / 100) + 1;
1257 qq|UPDATE parts SET $column = $column $operator ?
1261 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1263 my $result = do_query($form, $dbh, $query, $value, @where_values);
1264 $num_updated += $result if (0 <= $result);
1268 qq|UPDATE prices SET price = price + ?
1272 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1273 WHERE $where) AND (pricegroup_id = ?)|;
1274 my $sth_add = prepare_query($form, $dbh, $q_add);
1277 qq|UPDATE prices SET price = price * ?
1281 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1282 WHERE $where) AND (pricegroup_id = ?)|;
1283 my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1285 for my $i (1 .. $form->{price_rows}) {
1286 next if ($form->{"price_$i"} eq "");
1288 my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1291 if ($form->{"pricegroup_type_$i"} eq "percent") {
1292 $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1294 $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1297 $num_updated += $result if (0 <= $result);
1301 $sth_multiply->finish();
1303 return $num_updated;
1307 $main::lxdebug->enter_sub();
1309 my ($self, $module, $myconfig, $form) = @_;
1311 # connect to database
1312 my $dbh = $form->get_standard_dbh;
1314 my @values = like($module);
1319 qq|SELECT c.accno, c.description, c.link, c.id,
1320 p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1321 FROM chart c, parts p
1322 WHERE (c.link LIKE ?) AND (p.id = ?)
1324 push(@values, conv_i($form->{id}));
1328 qq|SELECT c.accno, c.description, c.link, c.id,
1329 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1330 FROM chart c, defaults d
1335 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1336 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1337 foreach my $key (split(/:/, $ref->{link})) {
1338 if ($key =~ /\Q$module\E/) {
1339 if ( ($ref->{id} eq $ref->{inventory_accno_id})
1340 || ($ref->{id} eq $ref->{income_accno_id})
1341 || ($ref->{id} eq $ref->{expense_accno_id})) {
1342 push @{ $form->{"${module}_links"}{$key} },
1343 { accno => $ref->{accno},
1344 description => $ref->{description},
1345 selected => "selected" };
1346 $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1348 push @{ $form->{"${module}_links"}{$key} },
1349 { accno => $ref->{accno},
1350 description => $ref->{description},
1358 # get buchungsgruppen
1359 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1362 $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1365 ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1368 $main::lxdebug->leave_sub();
1371 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1373 $main::lxdebug->enter_sub();
1375 my ($self, $myconfig, $form, $sortorder) = @_;
1376 my $dbh = $form->get_standard_dbh;
1377 my $order = qq| p.partnumber|;
1378 my $where = qq|1 = 1|;
1381 if ($sortorder eq "all") {
1382 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1383 push(@values, like($form->{partnumber}), like($form->{description}));
1385 } elsif ($sortorder eq "partnumber") {
1386 $where .= qq| AND (partnumber ILIKE ?)|;
1387 push(@values, like($form->{partnumber}));
1389 } elsif ($sortorder eq "description") {
1390 $where .= qq| AND (description ILIKE ?)|;
1391 push(@values, like($form->{description}));
1392 $order = "description";
1397 qq|SELECT id, partnumber, description, unit, sellprice
1399 WHERE $where ORDER BY $order|;
1401 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1404 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1405 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1410 $form->{"id_$j"} = $ref->{id};
1411 $form->{"partnumber_$j"} = $ref->{partnumber};
1412 $form->{"description_$j"} = $ref->{description};
1413 $form->{"unit_$j"} = $ref->{unit};
1414 $form->{"sellprice_$j"} = $ref->{sellprice};
1415 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
1420 $main::lxdebug->leave_sub();
1425 # gets sum of sold part with part_id
1427 $main::lxdebug->enter_sub();
1429 my ($dbh, $id) = @_;
1431 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1432 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1435 $main::lxdebug->leave_sub();
1438 } #end get_soldtotal
1440 sub retrieve_languages {
1441 $main::lxdebug->enter_sub();
1443 my ($self, $myconfig, $form) = @_;
1445 # connect to database
1446 my $dbh = $form->get_standard_dbh;
1452 if ($form->{language_values} ne "") {
1454 qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1456 LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1457 ORDER BY lower(l.description)|;
1458 @values = (conv_i($form->{id}));
1461 $query = qq|SELECT id, description
1463 ORDER BY lower(description)|;
1466 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1468 $main::lxdebug->leave_sub();
1473 sub follow_account_chain {
1474 $main::lxdebug->enter_sub(2);
1476 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1478 my @visited_accno_ids = ($accno_id);
1482 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
1483 map { $_->{id} => $_ }
1484 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
1485 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
1487 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
1488 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
1492 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
1493 last unless ($ref && $ref->{"is_valid"} &&
1494 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1495 $accno_id = $ref->{"new_chart_id"};
1496 $accno = $ref->{"accno"};
1497 push(@visited_accno_ids, $accno_id);
1500 $main::lxdebug->leave_sub(2);
1502 return ($accno_id, $accno);
1505 sub retrieve_accounts {
1506 $main::lxdebug->enter_sub;
1509 my $myconfig = shift;
1511 my $dbh = $form->get_standard_dbh;
1512 my %args = @_; # index => part_id
1514 $form->{taxzone_id} *= 1;
1516 return unless grep $_, values %args; # shortfuse if no part_id supplied
1518 # transdate madness.
1520 if ($form->{type} eq "invoice" or $form->{type} eq "credit_note") {
1521 # use deliverydate for sales and purchase invoice, if it exists
1522 # also use deliverydate for credit notes
1523 if (!$form->{deliverydate}) {
1524 $transdate = $form->{invdate};
1526 $transdate = $form->{deliverydate};
1528 } elsif ($form->{script} eq 'ir.pl') {
1529 # when a purchase invoice is opened from the report of purchase invoices
1530 # $form->{type} isn't set, but $form->{script} is, not sure why this is or
1531 # whether this distinction matters in some other scenario. Otherwise one
1532 # could probably take out this elsif and add a
1533 # " or $form->{script} eq 'ir.pl' "
1534 # to the above if-statement
1535 if (!$form->{deliverydate}) {
1536 $transdate = $form->{invdate};
1538 $transdate = $form->{deliverydate};
1540 } elsif (($form->{type} eq "credit_note") and $form->{deliverydate}) {
1541 # if credit_note has a deliverydate, use this instead of invdate
1542 # useful for credit_notes of invoices from an old period with different tax
1543 # if there is no deliverydate then invdate is used, old default (see next elsif)
1544 # Falls hier der Stichtag für Steuern anders bestimmt wird,
1545 # entsprechend auch bei Taxkeys.pm anpassen
1546 $transdate = $form->{deliverydate};
1547 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1548 $transdate = $form->{invdate};
1550 $transdate = $form->{transdate};
1553 if ($transdate eq "") {
1554 $transdate = DateTime->today_local->to_lxoffice;
1556 $transdate = $dbh->quote($transdate);
1559 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
1561 my @part_ids = grep { $_ } values %args;
1562 my $in = join ',', ('?') x @part_ids;
1564 my %accno_by_part = map { $_->{id} => $_ }
1565 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
1567 p.id, p.inventory_accno_id AS is_part,
1568 bg.inventory_accno_id,
1569 tc.income_accno_id AS income_accno_id,
1570 tc.expense_accno_id AS expense_accno_id,
1571 c1.accno AS inventory_accno,
1572 c2.accno AS income_accno,
1573 c3.accno AS expense_accno
1575 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
1576 LEFT JOIN taxzone_charts tc on bg.id = tc.buchungsgruppen_id
1577 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1578 LEFT JOIN chart c2 ON tc.income_accno_id = c2.id
1579 LEFT JOIN chart c3 ON tc.expense_accno_id = c3.id
1581 tc.taxzone_id = '$form->{taxzone_id}'
1586 my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1587 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1589 LEFT JOIN chart c ON c.id = t.chart_id
1593 WHERE tk.chart_id = ? AND startdate <= ?
1594 ORDER BY startdate DESC LIMIT 1)
1597 while (my ($index => $part_id) = each %args) {
1598 my $ref = $accno_by_part{$part_id} or next;
1600 $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
1603 for my $type (qw(inventory income expense)) {
1604 next unless $ref->{"${type}_accno_id"};
1605 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1606 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1609 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1611 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1612 $ref = $sth_tax->fetchrow_hashref or next;
1614 $form->{"taxaccounts_$index"} = $ref->{"accno"};
1615 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1617 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1622 $::lxdebug->leave_sub;
1625 sub get_basic_part_info {
1626 $main::lxdebug->enter_sub();
1631 Common::check_params(\%params, qw(id));
1633 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1636 $main::lxdebug->leave_sub();
1640 my $myconfig = \%main::myconfig;
1641 my $form = $main::form;
1643 my $dbh = $form->get_standard_dbh($myconfig);
1645 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1647 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1649 if ('' eq ref $params{id}) {
1650 $info = $info->[0] || { };
1652 $main::lxdebug->leave_sub();
1656 my %info_map = map { $_->{id} => $_ } @{ $info };
1658 $main::lxdebug->leave_sub();
1663 sub prepare_parts_for_printing {
1664 $main::lxdebug->enter_sub();
1669 my $myconfig = $params{myconfig} || \%main::myconfig;
1670 my $form = $params{form} || $main::form;
1672 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1674 my $prefix = $params{prefix} || 'id_';
1675 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1677 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1680 $main::lxdebug->leave_sub();
1684 my $placeholders = join ', ', ('?') x scalar(@part_ids);
1685 my $query = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
1687 LEFT JOIN vendor v ON (mm.make = v.id)
1688 WHERE mm.parts_id IN ($placeholders)|;
1692 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
1694 while (my $ref = $sth->fetchrow_hashref()) {
1695 $makemodel{$ref->{parts_id}} ||= [];
1696 push @{ $makemodel{$ref->{parts_id}} }, $ref;
1701 my @columns = qw(ean image microfiche drawing);
1703 $query = qq|SELECT id, | . join(', ', @columns) . qq|
1705 WHERE id IN ($placeholders)|;
1707 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1709 my %template_arrays;
1710 map { $template_arrays{$_} = [] } (qw(make model), @columns);
1712 foreach my $i (1 .. $rowcount) {
1713 my $id = $form->{"${prefix}${i}"};
1717 foreach (@columns) {
1718 push @{ $template_arrays{$_} }, $data{$id}->{$_};
1721 push @{ $template_arrays{make} }, [];
1722 push @{ $template_arrays{model} }, [];
1724 next if (!$makemodel{$id});
1726 foreach my $ref (@{ $makemodel{$id} }) {
1727 map { push @{ $template_arrays{$_}->[-1] }, $ref->{$_} } qw(make model);
1731 my $parts = SL::DB::Manager::Part->get_all(query => [ id => \@part_ids ]);
1732 my %parts_by_id = map { $_->id => $_ } @$parts;
1734 for my $i (1..$rowcount) {
1735 my $id = $form->{"${prefix}${i}"};
1738 push @{ $template_arrays{part_type} }, $parts_by_id{$id}->type;
1741 return %template_arrays;
1742 $main::lxdebug->leave_sub();
1745 sub normalize_text_blocks {
1746 $main::lxdebug->enter_sub();
1751 my $form = $params{form} || $main::form;
1753 # check if feature is enabled (select normalize_part_descriptions from defaults)
1754 return unless ($::instance_conf->get_normalize_part_descriptions);
1756 foreach (qw(description notes)) {
1757 $form->{$_} =~ s/\s+$//s;
1758 $form->{$_} =~ s/^\s+//s;
1759 $form->{$_} =~ s/ {2,}/ /g;
1761 $main::lxdebug->leave_sub();