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);
48 $main::lxdebug->enter_sub();
50 my ($self, $myconfig, $form) = @_;
53 my $dbh = $form->get_standard_dbh;
59 c1.accno AS inventory_accno,
60 c2.accno AS income_accno,
61 c3.accno AS expense_accno,
64 LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
65 LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
66 LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
67 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
69 my $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
71 # copy to $form variables
72 map { $form->{$_} = $ref->{$_} } (keys %{$ref});
76 # part or service item
77 $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
78 if ($form->{assembly}) {
79 $form->{item} = 'assembly';
81 # retrieve assembly items
83 qq|SELECT p.id, p.partnumber, p.description,
84 p.sellprice, p.lastcost, p.weight, a.qty, a.bom, p.unit,
85 pg.partsgroup, p.price_factor_id, pfac.factor AS price_factor
87 JOIN assembly a ON (a.parts_id = p.id)
88 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
89 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
92 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
94 $form->{assembly_rows} = 0;
95 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
96 $form->{assembly_rows}++;
97 foreach my $key (keys %{$ref}) {
98 $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
105 # setup accno hash for <option checked> {amount} is used in create_links
106 $form->{amount}{IC} = $form->{inventory_accno};
107 $form->{amount}{IC_income} = $form->{income_accno};
108 $form->{amount}{IC_sale} = $form->{income_accno};
109 $form->{amount}{IC_expense} = $form->{expense_accno};
110 $form->{amount}{IC_cogs} = $form->{expense_accno};
114 SELECT pg.pricegroup, pg.id AS pricegroup_id, COALESCE(pr.price, 0) AS price
116 LEFT JOIN prices pr ON (pr.pricegroup_id = pg.id) AND (pr.parts_id = ?)
117 ORDER BY lower(pg.pricegroup)
121 foreach $ref (selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}))) {
122 $form->{"${_}_${row}"} = $ref->{$_} for qw(pricegroup_id pricegroup price);
125 $form->{price_rows} = $row - 1;
128 if ($form->{makemodel}) {
130 $query = qq|SELECT m.make, m.model,m.lastcost,m.lastcost,m.lastupdate,m.sortorder FROM makemodel m | .
131 qq|WHERE m.parts_id = ? order by m.sortorder asc|;
132 my @values = ($form->{id});
133 $sth = $dbh->prepare($query);
134 $sth->execute(@values) || $form->dberror("$query (" . join(', ', @values) . ")");
138 while (($form->{"make_$i"}, $form->{"model_$i"}, $form->{"old_lastcost_$i"},
139 $form->{"lastcost_$i"}, $form->{"lastupdate_$i"}, $form->{"sortorder_$i"}) = $sth->fetchrow_array)
144 $form->{makemodel_rows} = $i - 1;
149 $query = qq|SELECT language_id, translation, longdescription
152 $form->{translations} = selectall_hashref_query($form, $dbh, $query, conv_i($form->{id}));
155 my @referencing_tables = qw(invoice orderitems inventory);
156 my %column_map = ( );
157 my $parts_id = conv_i($form->{id});
159 $form->{orphaned} = 1;
161 foreach my $table (@referencing_tables) {
162 my $column = $column_map{$table} || 'parts_id';
163 $query = qq|SELECT $column FROM $table WHERE $column = ? LIMIT 1|;
164 my ($found) = selectrow_query($form, $dbh, $query, $parts_id);
167 $form->{orphaned} = 0;
172 $form->{"unit_changeable"} = $form->{orphaned};
174 Common::webdav_folder($form) if $::lx_office_conf{features}{webdav};
176 $main::lxdebug->leave_sub();
179 sub get_pricegroups {
180 $main::lxdebug->enter_sub();
182 my ($self, $myconfig, $form) = @_;
184 my $dbh = $form->get_standard_dbh;
187 my $query = qq|SELECT id, pricegroup FROM pricegroup ORDER BY lower(pricegroup)|;
188 my $pricegroups = selectall_hashref_query($form, $dbh, $query);
191 foreach my $pg (@{ $pricegroups }) {
192 $form->{"klass_$i"} = "$pg->{id}";
193 $form->{"price_$i"} = $form->format_amount($myconfig, $form->{"price_$i"}, -2);
194 $form->{"pricegroup_id_$i"} = "$pg->{id}";
195 $form->{"pricegroup_$i"} = "$pg->{pricegroup}";
200 $form->{price_rows} = $i - 1;
202 $main::lxdebug->leave_sub();
207 sub retrieve_buchungsgruppen {
208 $main::lxdebug->enter_sub();
210 my ($self, $myconfig, $form) = @_;
214 my $dbh = $form->get_standard_dbh;
216 # get buchungsgruppen
217 $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
218 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
220 $main::lxdebug->leave_sub();
224 $main::lxdebug->enter_sub();
226 my ($self, $myconfig, $form) = @_;
228 # connect to database, turn off AutoCommit
229 my $dbh = $form->get_standard_dbh;
232 # make up a unique handle and store in partnumber field
233 # then retrieve the record based on the unique handle to get the id
234 # replace the partnumber field with the actual variable
235 # add records for makemodel
237 # if there is a $form->{id} then replace the old entry
238 # delete all makemodel entries and add the new ones
240 # undo amount formatting
241 map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
242 qw(rop weight listprice sellprice gv lastcost);
244 my $makemodel = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
246 $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
250 my $priceupdate = ', priceupdate = current_date';
253 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, id => $form->{id});
254 if (!$trans_number->is_unique) {
255 $::lxdebug->leave_sub;
260 $query = qq|SELECT sellprice, weight FROM parts WHERE id = ?|;
261 my ($sellprice, $weight) = selectrow_query($form, $dbh, $query, conv_i($form->{id}));
263 # if item is part of an assembly adjust all assemblies
264 $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
265 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
266 while (my ($id, $qty) = $sth->fetchrow_array) {
267 &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
271 # delete makemodel records
272 do_query($form, $dbh, qq|DELETE FROM makemodel WHERE parts_id = ?|, conv_i($form->{id}));
274 if ($form->{item} eq 'assembly') {
275 # delete assembly records
276 do_query($form, $dbh, qq|DELETE FROM assembly WHERE id = ?|, conv_i($form->{id}));
279 # delete translations
280 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
282 # Check whether or not the prices have changed. If they haven't
283 # then 'priceupdate' should not be updated.
284 my $previous_values = selectfirst_hashref_query($form, $dbh, qq|SELECT * FROM parts WHERE id = ?|, conv_i($form->{id})) || {};
285 $priceupdate = '' if (all { $previous_values->{$_} == $form->{$_} } qw(sellprice lastcost listprice));
288 my $trans_number = SL::TransNumber->new(type => $form->{item}, dbh => $dbh, number => $form->{partnumber}, save => 1);
290 if ($form->{partnumber} && !$trans_number->is_unique) {
291 $::lxdebug->leave_sub;
295 $form->{partnumber} ||= $trans_number->create_unique;
297 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('id')|);
298 do_query($form, $dbh, qq|INSERT INTO parts (id, partnumber, unit) VALUES (?, ?, ?)|, $form->{id}, $form->{partnumber}, $form->{unit});
300 $form->{orphaned} = 1;
302 my $partsgroup_id = undef;
304 if ($form->{partsgroup}) {
305 (my $partsgroup, $partsgroup_id) = split(/--/, $form->{partsgroup});
308 my ($subq_inventory, $subq_expense, $subq_income);
309 if ($form->{"item"} eq "part") {
311 qq|(SELECT bg.inventory_accno_id
312 FROM buchungsgruppen bg
313 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
315 $subq_inventory = "NULL";
318 if ($form->{"item"} ne "assembly") {
320 qq|(SELECT bg.expense_accno_id_0
321 FROM buchungsgruppen bg
322 WHERE bg.id = | . conv_i($form->{"buchungsgruppen_id"}, 'NULL') . qq|)|;
324 $subq_expense = "NULL";
344 buchungsgruppen_id = ?,
346 inventory_accno_id = $subq_inventory,
347 income_accno_id = (SELECT bg.income_accno_id_0 FROM buchungsgruppen bg WHERE bg.id = ?),
348 expense_accno_id = $subq_expense,
357 not_discountable = ?,
363 @values = ($form->{partnumber},
364 $form->{description},
365 $makemodel ? 't' : 'f',
366 $form->{assembly} ? 't' : 'f',
375 conv_i($form->{warehouse_id}),
376 conv_i($form->{bin_id}),
377 conv_i($form->{buchungsgruppen_id}),
378 conv_i($form->{payment_id}),
379 conv_i($form->{buchungsgruppen_id}),
380 $form->{obsolete} ? 't' : 'f',
383 $form->{shop} ? 't' : 'f',
387 $form->{has_sernumber} ? 't' : 'f',
388 $form->{not_discountable} ? 't' : 'f',
390 conv_i($partsgroup_id),
391 conv_i($form->{price_factor_id}),
394 do_query($form, $dbh, $query, @values);
396 # delete translation records
397 do_query($form, $dbh, qq|DELETE FROM translation WHERE parts_id = ?|, conv_i($form->{id}));
399 my @translations = grep { $_->{language_id} && $_->{translation} } @{ $form->{translations} || [] };
401 $query = qq|INSERT into translation (parts_id, language_id, translation, longdescription)
402 VALUES ( ?, ?, ?, ? )|;
403 $sth = $dbh->prepare($query);
405 foreach my $translation (@translations) {
406 do_statement($form, $sth, $query, conv_i($form->{id}), conv_i($translation->{language_id}), $translation->{translation}, $translation->{longdescription});
412 # delete price records
413 do_query($form, $dbh, qq|DELETE FROM prices WHERE parts_id = ?|, conv_i($form->{id}));
415 $query = qq|INSERT INTO prices (parts_id, pricegroup_id, price) VALUES(?, ?, ?)|;
416 $sth = prepare_query($form, $dbh, $query);
418 # insert price records only if different to sellprice
419 for my $i (1 .. $form->{price_rows}) {
420 my $price = $form->parse_amount($myconfig, $form->{"price_$i"});
421 next unless $price && ($price != $form->{sellprice});
423 @values = (conv_i($form->{id}), conv_i($form->{"pricegroup_id_$i"}), $price);
424 do_statement($form, $sth, $query, @values);
429 # insert makemodel records
432 for my $i (1 .. $form->{makemodel_rows}) {
433 if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
435 $value = $form->parse_amount($myconfig, $form->{"lastcost_$i"});
436 if ($value == $form->parse_amount($myconfig, $form->{"old_lastcost_$i"}))
438 if ($form->{"lastupdate_$i"} eq "") {
439 $lastupdate = 'now()';
441 $lastupdate = $dbh->quote($form->{"lastupdate_$i"});
444 $lastupdate = 'now()';
446 $query = qq|INSERT INTO makemodel (parts_id, make, model, lastcost, lastupdate, sortorder) | .
447 qq|VALUES (?, ?, ?, ?, ?, ?)|;
448 @values = (conv_i($form->{id}), conv_i($form->{"make_$i"}), $form->{"model_$i"}, $value, $lastupdate, conv_i($form->{"sortorder_$i"}) );
450 do_query($form, $dbh, $query, @values);
454 # add assembly records
455 if ($form->{item} eq 'assembly') {
456 # check additional assembly row
457 my $i = $form->{assembly_rows};
458 # if last row is not empty add them
459 if ($form->{"partnumber_$i"} ne "") {
460 $query = qq|SELECT id FROM parts WHERE partnumber = ?|;
461 my ($partid) = selectrow_query($form, $dbh, $query,$form->{"partnumber_$i"} );
463 $form->{"qty_$i"} = 1 unless ($form->{"qty_$i"});
464 $form->{"id_$i"} = $partid;
465 $form->{"bom_$i"} = 0;
466 $form->{assembly_rows}++;
469 $::form->error($::locale->text("uncorrect partnumber ").$form->{"partnumber_$i"});
473 for my $i (1 .. $form->{assembly_rows}) {
474 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
476 if ($form->{"qty_$i"} != 0) {
477 $form->{"bom_$i"} *= 1;
478 $query = qq|INSERT INTO assembly (id, parts_id, qty, bom) | .
479 qq|VALUES (?, ?, ?, ?)|;
480 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}), conv_i($form->{"qty_$i"}), $form->{"bom_$i"} ? 't' : 'f');
481 do_query($form, $dbh, $query, @values);
487 my $shippingdate = "$a[5]-$a[4]-$a[3]";
489 $form->get_employee($dbh);
493 #set expense_accno=inventory_accno if they are different => bilanz
495 ($form->{expense_accno} != $form->{inventory_accno})
496 ? $form->{inventory_accno}
497 : $form->{expense_accno};
499 # get tax rates and description
501 ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
503 qq|SELECT c.accno, c.description, t.rate, t.taxnumber
505 WHERE (c.id = t.chart_id) AND (t.taxkey IN (SELECT taxkey_id FROM chart where accno = ?))
507 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
509 $form->{taxaccount} = "";
510 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
511 $form->{taxaccount} .= "$ptr->{accno} ";
512 if (!($form->{taxaccount2} =~ /\Q$ptr->{accno}\E/)) {
513 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
514 $form->{"$ptr->{accno}_description"} = $ptr->{description};
515 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
516 $form->{taxaccount2} .= " $ptr->{accno} ";
520 CVar->save_custom_variables(dbh => $dbh,
522 trans_id => $form->{id},
527 my $rc = $dbh->commit;
529 $main::lxdebug->leave_sub();
534 sub update_assembly {
535 $main::lxdebug->enter_sub();
537 my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
539 my $query = qq|SELECT id, qty FROM assembly WHERE parts_id = ?|;
540 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
542 while (my ($pid, $aqty) = $sth->fetchrow_array) {
543 &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
548 qq|UPDATE parts SET sellprice = sellprice + ?, weight = weight + ?
550 my @values = ($qty * ($form->{sellprice} - $sellprice),
551 $qty * ($form->{weight} - $weight), conv_i($id));
552 do_query($form, $dbh, $query, @values);
554 $main::lxdebug->leave_sub();
557 sub retrieve_assemblies {
558 $main::lxdebug->enter_sub();
560 my ($self, $myconfig, $form) = @_;
562 # connect to database
563 my $dbh = $form->get_standard_dbh;
565 my $where = qq|NOT p.obsolete|;
568 if ($form->{partnumber}) {
569 $where .= qq| AND (p.partnumber ILIKE ?)|;
570 push(@values, '%' . $form->{partnumber} . '%');
573 if ($form->{description}) {
574 $where .= qq| AND (p.description ILIKE ?)|;
575 push(@values, '%' . $form->{description} . '%');
578 # retrieve assembly items
580 qq|SELECT p.id, p.partnumber, p.description,
582 (SELECT sum(p2.inventory_accno_id)
583 FROM parts p2, assembly a
584 WHERE (p2.id = a.parts_id) AND (a.id = p.id)) AS inventory
586 WHERE NOT p.obsolete AND p.assembly $where|;
588 $form->{assembly_items} = selectall_hashref_query($form, $dbh, $query, @values);
590 $main::lxdebug->leave_sub();
594 $main::lxdebug->enter_sub();
596 my ($self, $myconfig, $form) = @_;
597 my @values = (conv_i($form->{id}));
598 # connect to database, turn off AutoCommit
599 my $dbh = $form->get_standard_dbh;
601 my %columns = ( "assembly" => "id", "parts" => "id" );
603 for my $table (qw(prices makemodel inventory assembly translation parts)) {
604 my $column = defined($columns{$table}) ? $columns{$table} : "parts_id";
605 do_query($form, $dbh, qq|DELETE FROM $table WHERE $column = ?|, @values);
609 my $rc = $dbh->commit;
611 $main::lxdebug->leave_sub();
617 $main::lxdebug->enter_sub();
619 my ($self, $myconfig, $form) = @_;
621 my $i = $form->{assembly_rows};
623 my $where = qq|1 = 1|;
626 my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
628 while (my ($column, $table) = each(%columns)) {
629 next unless ($form->{"${column}_$i"});
630 $where .= qq| AND ${table}.${column} ILIKE ?|;
631 push(@values, '%' . $form->{"${column}_$i"} . '%');
635 $where .= qq| AND NOT (p.id = ?)|;
636 push(@values, conv_i($form->{id}));
639 # Search for part ID overrides all other criteria.
640 if ($form->{"id_${i}"}) {
641 $where = qq|p.id = ?|;
642 @values = ($form->{"id_${i}"});
645 if ($form->{partnumber}) {
646 $where .= qq| ORDER BY p.partnumber|;
648 $where .= qq| ORDER BY p.description|;
651 # connect to database
652 my $dbh = $form->get_standard_dbh;
655 qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
656 p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
657 p.price_factor_id, pfac.factor AS price_factor
659 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
660 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
662 $form->{item_list} = selectall_hashref_query($form, $dbh, $query, @values);
664 $main::lxdebug->leave_sub();
669 # Warning, deep magic ahead.
670 # This function gets all parts from the database according to the filters specified
673 # sort revers - sorting field + direction
676 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
677 # partnumber ean description partsgroup microfiche drawing
680 # 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
683 # itemstatus = active | onhand | short | obsolete | orphaned
684 # searchitems = part | assembly | service
687 # make model - makemodel
688 # serialnumber transdatefrom transdateto - invoice/orderitems
691 # bought sold onorder ordered rfq quoted - aggreg joins with invoices/orders
692 # l_linetotal l_subtotal - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
693 # l_soldtotal - aggreg join to display total of sold quantity
694 # onhand - as above, but masking the simple itemstatus results (doh!)
695 # short - NOT IMPLEMENTED as form filter, only as itemstatus option
696 # l_serialnumber - belonges to serialnumber filter
697 # l_deliverydate - displays deliverydate is sold etc. flags are active
698 # l_soldtotal - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
701 # onhand - as above, but masking the simple itemstatus results (doh!)
703 # search by overrides of description
705 # disabled sanity checks and changes:
706 # - searchitems = assembly will no longer disable bought
707 # - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
708 # - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
709 # - itemstatus = obsolete will no longer disable onhand, short
710 # - allow sorting by ean
711 # - serialnumber filter also works if l_serialnumber isn't ticked
712 # - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
715 $main::lxdebug->enter_sub();
717 my ($self, $myconfig, $form) = @_;
718 my $dbh = $form->get_standard_dbh($myconfig);
720 $form->{parts} = +{ };
721 $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
723 my @simple_filters = qw(partnumber ean description partsgroup microfiche drawing onhand);
724 my @project_filters = qw(projectnumber projectdescription);
725 my @makemodel_filters = qw(make model);
726 my @invoice_oi_filters = qw(serialnumber soldtotal);
727 my @apoe_filters = qw(transdate);
728 my @like_filters = (@simple_filters, @invoice_oi_filters);
729 my @all_columns = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
730 my @simple_l_switches = (@all_columns, qw(notes listprice sellprice lastcost priceupdate weight unit rop image));
731 my @oe_flags = qw(bought sold onorder ordered rfq quoted);
732 my @qsooqr_flags = qw(invnumber ordnumber quonumber trans_id name module qty);
733 my @deliverydate_flags = qw(deliverydate);
734 # my @other_flags = qw(onhand); # ToDO: implement these
735 # my @inactive_flags = qw(l_subtotal short l_linetotal);
737 my @select_tokens = qw(id factor);
738 my @where_tokens = qw(1=1);
739 my @group_tokens = ();
741 my %joins_needed = ();
744 partsgroup => 'LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)',
745 makemodel => 'LEFT JOIN makemodel mm ON (mm.parts_id = p.id)',
746 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
749 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, project_id, id FROM invoice UNION
750 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
751 ) AS ioi ON ioi.parts_id = p.id|,
754 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
755 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
756 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
757 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
760 SELECT id, name, 'customer' AS cv FROM customer UNION
761 SELECT id, name, 'vendor' AS cv FROM vendor
762 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
763 mv => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
764 project => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
766 my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project);
769 deliverydate => 'apoe.', serialnumber => 'ioi.',
770 transdate => 'apoe.', trans_id => 'ioi.',
771 module => 'apoe.', name => 'cv.',
772 ordnumber => 'apoe.', make => 'mm.',
773 quonumber => 'apoe.', model => 'mm.',
774 invnumber => 'apoe.', partsgroup => 'pg.',
775 lastcost => 'p.', , soldtotal => ' ',
776 factor => 'pfac.', projectnumber => 'pj.',
777 'SUM(ioi.qty)' => ' ', projectdescription => 'pj.',
780 serialnumber => 'ioi.',
781 quotation => 'apoe.',
787 # if the join condition in these blocks are met, the column
788 # of the scecified table will gently override (coalesce actually) the original value
789 # use it to conditionally coalesce values from subtables
790 my @column_override = (
791 # column name, prefix, joins_needed, nick name (in case column is named like another)
792 [ 'description', 'ioi.', 'invoice_oi' ],
793 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
794 [ 'transdate', 'apoe.', 'apoe' ],
795 [ 'unit', 'ioi.', 'invoice_oi' ],
796 [ 'sellprice', 'ioi.', 'invoice_oi' ],
799 # careful with renames. these are HARD, and any filters done on the original column will break
800 my %renamed_columns = (
801 'factor' => 'price_factor',
802 'SUM(ioi.qty)' => 'soldtotal',
803 'ioi.id' => 'ioi_id',
805 'projectdescription' => 'projectdescription',
809 projectdescription => 'description',
812 if (($form->{searchitems} eq 'assembly') && $form->{l_lastcost}) {
813 @simple_l_switches = grep { $_ ne 'lastcost' } @simple_l_switches;
816 my $make_token_builder = sub {
817 my $joins_needed = shift;
819 my ($nick, $alias) = @_;
820 my ($col) = $real_column{$nick} || $nick;
821 my @coalesce_tokens =
822 map { ($_->[1] || 'p.') . $_->[0] }
823 grep { !$_->[2] || $joins_needed->{$_->[2]} }
824 grep { ($_->[3] || $_->[0]) eq $nick }
825 @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
827 my $coalesce = scalar @coalesce_tokens > 1;
829 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
830 : shift @coalesce_tokens)
831 . ($alias && ($coalesce || $renamed_columns{$nick})
832 ? " AS " . ($renamed_columns{$nick} || $nick)
837 #===== switches and simple filters ========#
839 # special case transdate
840 if (grep { $form->{$_} } qw(transdatefrom transdateto)) {
841 $form->{"l_transdate"} = 1;
842 push @select_tokens, 'transdate';
843 for (qw(transdatefrom transdateto)) {
844 next unless $form->{$_};
845 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
846 push @bind_vars, $form->{$_};
850 if ($form->{"partsgroup_id"}) {
851 $form->{"l_partsgroup"} = '1'; # show the column
852 push @where_tokens, "pg.id = ?";
853 push @bind_vars, $form->{"partsgroup_id"};
856 foreach (@like_filters) {
857 next unless $form->{$_};
858 $form->{"l_$_"} = '1'; # show the column
859 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
860 push @bind_vars, "%$form->{$_}%";
863 foreach (@simple_l_switches) {
864 next unless $form->{"l_$_"};
865 push @select_tokens, $_;
868 for ($form->{searchitems}) {
869 push @where_tokens, 'p.inventory_accno_id > 0' if /part/;
870 push @where_tokens, 'p.inventory_accno_id IS NULL' if /service/;
871 push @where_tokens, 'NOT p.assembly' if /service/;
872 push @where_tokens, ' p.assembly' if /assembly/;
875 for ($form->{itemstatus}) {
876 push @where_tokens, 'p.id NOT IN
877 (SELECT DISTINCT parts_id FROM invoice UNION
878 SELECT DISTINCT parts_id FROM assembly UNION
879 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
880 push @where_tokens, 'p.onhand = 0' if /orphaned/;
881 push @where_tokens, 'NOT p.obsolete' if /active/;
882 push @where_tokens, ' p.obsolete', if /obsolete/;
883 push @where_tokens, 'p.onhand > 0', if /onhand/;
884 push @where_tokens, 'p.onhand < p.rop', if /short/;
887 my $q_assembly_lastcost =
888 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
890 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
891 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
892 WHERE (a_lc.id = p.id)) AS lastcost|;
893 $table_prefix{$q_assembly_lastcost} = ' ';
895 # special case makemodel search
896 # all_parts is based upon the assumption that every parameter is named like the column it represents
897 # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
898 # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
900 push @where_tokens, 'mv.name ILIKE ?';
901 push @bind_vars, "%$form->{make}%";
903 if ($form->{model}) {
904 push @where_tokens, 'mm.model ILIKE ?';
905 push @bind_vars, "%$form->{model}%";
908 # special case: sorting by partnumber
909 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
910 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
911 # ToDO: implement proper functional sorting
912 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
913 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
914 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
915 # if $form->{sort} eq 'partnumber';
917 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
920 $limit_clause = " LIMIT 100" if $form->{top100};
921 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
923 #=== joins and complicated filters ========#
925 my $bsooqr = any { $form->{$_} } @oe_flags;
926 my @bsooqr_tokens = ();
928 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
929 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
930 push @select_tokens, $q_assembly_lastcost if ($form->{searchitems} eq 'assembly') && $form->{l_lastcost};
931 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
932 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
933 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
934 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
935 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
936 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
937 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
939 $joins_needed{partsgroup} = 1;
940 $joins_needed{pfac} = 1;
941 $joins_needed{project} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
942 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
943 $joins_needed{mv} = 1 if $joins_needed{makemodel};
944 $joins_needed{cv} = 1 if $bsooqr;
945 $joins_needed{apoe} = 1 if $joins_needed{project} || $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
946 $joins_needed{invoice_oi} = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
948 # special case for description search.
949 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
950 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
951 # find the old entries in of @where_tokens and @bind_vars, and adjust them
952 if ($joins_needed{invoice_oi}) {
953 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
954 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
955 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
956 splice @bind_vars, $bi, 0, $bind_vars[$bi];
961 # now the master trick: soldtotal.
962 if ($form->{l_soldtotal}) {
963 push @where_tokens, 'NOT ioi.qty = 0';
964 push @group_tokens, @select_tokens;
965 map { s/.*\sAS\s+//si } @group_tokens;
966 push @select_tokens, 'SUM(ioi.qty)';
969 #============= build query ================#
971 my $token_builder = $make_token_builder->(\%joins_needed);
973 my @sort_cols = (@simple_filters, qw(id priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate));
974 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
975 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
976 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
978 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
979 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
980 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
981 my $group_clause = @group_tokens ? ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens : '';
983 my %oe_flag_to_cvar = (
986 onorder => 'orderitems',
987 ordered => 'orderitems',
989 quoted => 'orderitems',
992 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
994 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
996 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
1000 $where_clause .= qq| AND ($cvar_where)|;
1001 push @bind_vars, @cvar_values;
1004 my $query = <<" SQL";
1005 SELECT DISTINCT $select_clause
1014 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
1016 map { $_->{onhand} *= 1 } @{ $form->{parts} };
1018 # fix qty sign in ap. those are saved negative
1019 if ($bsooqr && $form->{bought}) {
1020 for my $row (@{ $form->{parts} }) {
1021 $row->{qty} *= -1 if $row->{module} eq 'ir';
1025 # post processing for assembly parts lists (bom)
1026 # for each part get the assembly parts and add them into the partlist.
1028 if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1030 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1032 p.sellprice, p.listprice, p.lastcost,
1033 p.rop, p.weight, p.priceupdate,
1034 p.image, p.drawing, p.microfiche,
1037 INNER JOIN assembly a ON (p.id = a.parts_id)
1040 my $sth = prepare_query($form, $dbh, $query);
1042 foreach my $item (@{ $form->{parts} }) {
1043 push(@assemblies, $item);
1044 do_statement($form, $sth, $query, conv_i($item->{id}));
1046 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1047 $ref->{assemblyitem} = 1;
1048 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
1049 push(@assemblies, $ref);
1054 # copy assemblies to $form->{parts}
1055 $form->{parts} = \@assemblies;
1058 if ($form->{l_pricegroups} ) {
1060 SELECT parts_id, price, pricegroup_id
1065 my $sth = prepare_query($form, $dbh, $query);
1067 foreach my $part (@{ $form->{parts} }) {
1068 do_statement($form, $sth, $query, conv_i($part->{id}));
1070 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1071 $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
1078 $main::lxdebug->leave_sub();
1080 return wantarray ? @{ $form->{parts} } : $form->{parts};
1083 sub _create_filter_for_priceupdate {
1084 $main::lxdebug->enter_sub();
1087 my $myconfig = \%main::myconfig;
1088 my $form = $main::form;
1091 my $where = '1 = 1';
1093 foreach my $item (qw(partnumber drawing microfiche make model pg.partsgroup)) {
1095 $column =~ s/.*\.//;
1096 next unless ($form->{$column});
1098 $where .= qq| AND $item ILIKE ?|;
1099 push(@where_values, '%' . $form->{$column} . '%');
1102 foreach my $item (qw(description serialnumber)) {
1103 next unless ($form->{$item});
1105 $where .= qq| AND (${item} ILIKE ?)|;
1106 push(@where_values, '%' . $form->{$item} . '%');
1110 # items which were never bought, sold or on an order
1111 if ($form->{itemstatus} eq 'orphaned') {
1113 qq| AND (p.onhand = 0)
1116 SELECT DISTINCT parts_id FROM invoice
1118 SELECT DISTINCT parts_id FROM assembly
1120 SELECT DISTINCT parts_id FROM orderitems
1123 } elsif ($form->{itemstatus} eq 'active') {
1124 $where .= qq| AND p.obsolete = '0'|;
1126 } elsif ($form->{itemstatus} eq 'obsolete') {
1127 $where .= qq| AND p.obsolete = '1'|;
1129 } elsif ($form->{itemstatus} eq 'onhand') {
1130 $where .= qq| AND p.onhand > 0|;
1132 } elsif ($form->{itemstatus} eq 'short') {
1133 $where .= qq| AND p.onhand < p.rop|;
1137 foreach my $column (qw(make model)) {
1138 next unless ($form->{$column});
1139 $where .= qq| AND p.id IN (SELECT DISTINCT parts_id FROM makemodel WHERE $column ILIKE ?|;
1140 push(@where_values, '%' . $form->{$column} . '%');
1143 $main::lxdebug->leave_sub();
1145 return ($where, @where_values);
1148 sub get_num_matches_for_priceupdate {
1149 $main::lxdebug->enter_sub();
1153 my $myconfig = \%main::myconfig;
1154 my $form = $main::form;
1156 my $dbh = $form->get_standard_dbh($myconfig);
1158 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1160 my $num_updated = 0;
1163 for my $column (qw(sellprice listprice)) {
1164 next if ($form->{$column} eq "");
1172 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1174 my ($result) = selectfirst_array_query($form, $dbh, $query, @where_values);
1175 $num_updated += $result if (0 <= $result);
1184 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1185 WHERE $where) AND (pricegroup_id = ?)|;
1186 my $sth = prepare_query($form, $dbh, $query);
1188 for my $i (1 .. $form->{price_rows}) {
1189 next if ($form->{"price_$i"} eq "");
1191 my ($result) = do_statement($form, $sth, $query, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1192 $num_updated += $result if (0 <= $result);
1196 $main::lxdebug->leave_sub();
1198 return $num_updated;
1202 $main::lxdebug->enter_sub();
1204 my ($self, $myconfig, $form) = @_;
1206 my ($where, @where_values) = $self->_create_filter_for_priceupdate();
1207 my $num_updated = 0;
1209 # connect to database
1210 my $dbh = $form->get_standard_dbh;
1212 for my $column (qw(sellprice listprice)) {
1213 next if ($form->{$column} eq "");
1215 my $value = $form->parse_amount($myconfig, $form->{$column});
1218 if ($form->{"${column}_type"} eq "percent") {
1219 $value = ($value / 100) + 1;
1224 qq|UPDATE parts SET $column = $column $operator ?
1228 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1230 my $result = do_query($form, $dbh, $query, $value, @where_values);
1231 $num_updated += $result if (0 <= $result);
1235 qq|UPDATE prices SET price = price + ?
1239 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1240 WHERE $where) AND (pricegroup_id = ?)|;
1241 my $sth_add = prepare_query($form, $dbh, $q_add);
1244 qq|UPDATE prices SET price = price * ?
1248 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1249 WHERE $where) AND (pricegroup_id = ?)|;
1250 my $sth_multiply = prepare_query($form, $dbh, $q_multiply);
1252 for my $i (1 .. $form->{price_rows}) {
1253 next if ($form->{"price_$i"} eq "");
1255 my $value = $form->parse_amount($myconfig, $form->{"price_$i"});
1258 if ($form->{"pricegroup_type_$i"} eq "percent") {
1259 $result = do_statement($form, $sth_multiply, $q_multiply, ($value / 100) + 1, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1261 $result = do_statement($form, $sth_add, $q_add, $value, @where_values, conv_i($form->{"pricegroup_id_$i"}));
1264 $num_updated += $result if (0 <= $result);
1268 $sth_multiply->finish();
1270 my $rc= $dbh->commit;
1272 $main::lxdebug->leave_sub();
1274 return $num_updated;
1278 $main::lxdebug->enter_sub();
1280 my ($self, $module, $myconfig, $form) = @_;
1282 # connect to database
1283 my $dbh = $form->get_standard_dbh;
1285 my @values = ('%' . $module . '%');
1290 qq|SELECT c.accno, c.description, c.link, c.id,
1291 p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1292 FROM chart c, parts p
1293 WHERE (c.link LIKE ?) AND (p.id = ?)
1295 push(@values, conv_i($form->{id}));
1299 qq|SELECT c.accno, c.description, c.link, c.id,
1300 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1301 FROM chart c, defaults d
1306 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1307 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1308 foreach my $key (split(/:/, $ref->{link})) {
1309 if ($key =~ /\Q$module\E/) {
1310 if ( ($ref->{id} eq $ref->{inventory_accno_id})
1311 || ($ref->{id} eq $ref->{income_accno_id})
1312 || ($ref->{id} eq $ref->{expense_accno_id})) {
1313 push @{ $form->{"${module}_links"}{$key} },
1314 { accno => $ref->{accno},
1315 description => $ref->{description},
1316 selected => "selected" };
1317 $form->{"${key}_default"} = "$ref->{accno}--$ref->{description}";
1319 push @{ $form->{"${module}_links"}{$key} },
1320 { accno => $ref->{accno},
1321 description => $ref->{description},
1329 # get buchungsgruppen
1330 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM buchungsgruppen|);
1333 $form->{payment_terms} = selectall_hashref_query($form, $dbh, qq|SELECT id, description FROM payment_terms ORDER BY sortkey|);
1336 ($form->{priceupdate}) = selectrow_query($form, $dbh, qq|SELECT current_date|);
1339 $main::lxdebug->leave_sub();
1342 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1344 $main::lxdebug->enter_sub();
1346 my ($self, $myconfig, $form, $sortorder) = @_;
1347 my $dbh = $form->get_standard_dbh;
1348 my $order = qq| p.partnumber|;
1349 my $where = qq|1 = 1|;
1352 if ($sortorder eq "all") {
1353 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
1354 push(@values, '%' . $form->{partnumber} . '%', '%' . $form->{description} . '%');
1356 } elsif ($sortorder eq "partnumber") {
1357 $where .= qq| AND (partnumber ILIKE ?)|;
1358 push(@values, '%' . $form->{partnumber} . '%');
1360 } elsif ($sortorder eq "description") {
1361 $where .= qq| AND (description ILIKE ?)|;
1362 push(@values, '%' . $form->{description} . '%');
1363 $order = "description";
1368 qq|SELECT id, partnumber, description, unit, sellprice
1370 WHERE $where ORDER BY $order|;
1372 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1375 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1376 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1381 $form->{"id_$j"} = $ref->{id};
1382 $form->{"partnumber_$j"} = $ref->{partnumber};
1383 $form->{"description_$j"} = $ref->{description};
1384 $form->{"unit_$j"} = $ref->{unit};
1385 $form->{"sellprice_$j"} = $ref->{sellprice};
1386 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
1391 $main::lxdebug->leave_sub();
1396 # gets sum of sold part with part_id
1398 $main::lxdebug->enter_sub();
1400 my ($dbh, $id) = @_;
1402 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
1403 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
1406 $main::lxdebug->leave_sub();
1409 } #end get_soldtotal
1411 sub retrieve_languages {
1412 $main::lxdebug->enter_sub();
1414 my ($self, $myconfig, $form) = @_;
1416 # connect to database
1417 my $dbh = $form->get_standard_dbh;
1423 if ($form->{language_values} ne "") {
1425 qq|SELECT l.id, l.description, tr.translation, tr.longdescription
1427 LEFT OUTER JOIN translation tr ON (tr.language_id = l.id) AND (tr.parts_id = ?)
1428 ORDER BY lower(l.description)|;
1429 @values = (conv_i($form->{id}));
1432 $query = qq|SELECT id, description
1434 ORDER BY lower(description)|;
1437 my $languages = selectall_hashref_query($form, $dbh, $query, @values);
1439 $main::lxdebug->leave_sub();
1444 sub follow_account_chain {
1445 $main::lxdebug->enter_sub(2);
1447 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
1449 my @visited_accno_ids = ($accno_id);
1453 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
1454 map { $_->{id} => $_ }
1455 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
1456 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
1458 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
1459 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
1463 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
1464 last unless ($ref && $ref->{"is_valid"} &&
1465 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
1466 $accno_id = $ref->{"new_chart_id"};
1467 $accno = $ref->{"accno"};
1468 push(@visited_accno_ids, $accno_id);
1471 $main::lxdebug->leave_sub(2);
1473 return ($accno_id, $accno);
1476 sub retrieve_accounts {
1477 $main::lxdebug->enter_sub;
1480 my $myconfig = shift;
1482 my $dbh = $form->get_standard_dbh;
1483 my %args = @_; # index => part_id
1485 $form->{taxzone_id} *= 1;
1487 return unless grep $_, values %args; # shortfuse if no part_id supplied
1489 # transdate madness.
1491 if ($form->{type} eq "invoice" or $form->{type} eq "credit_note") {
1492 # use deliverydate for sales and purchase invoice, if it exists
1493 # also use deliverydate for credit notes
1494 if (!$form->{deliverydate}) {
1495 $transdate = $form->{invdate};
1497 $transdate = $form->{deliverydate};
1499 } elsif ($form->{script} eq 'ir.pl') {
1500 # when a purchase invoice is opened from the report of purchase invoices
1501 # $form->{type} isn't set, but $form->{script} is, not sure why this is or
1502 # whether this distinction matters in some other scenario. Otherwise one
1503 # could probably take out this elsif and add a
1504 # " or $form->{script} eq 'ir.pl' "
1505 # to the above if-statement
1506 if (!$form->{deliverydate}) {
1507 $transdate = $form->{invdate};
1509 $transdate = $form->{deliverydate};
1511 } elsif (($form->{type} eq "credit_note") and $form->{deliverydate}) {
1512 # if credit_note has a deliverydate, use this instead of invdate
1513 # useful for credit_notes of invoices from an old period with different tax
1514 # if there is no deliverydate then invdate is used, old default (see next elsif)
1515 # Falls hier der Stichtag für Steuern anders bestimmt wird,
1516 # entsprechend auch bei Taxkeys.pm anpassen
1517 $transdate = $form->{deliverydate};
1518 } elsif (($form->{type} eq "credit_note") || ($form->{script} eq 'ir.pl')) {
1519 $transdate = $form->{invdate};
1521 $transdate = $form->{transdate};
1524 if ($transdate eq "") {
1525 $transdate = DateTime->today_local->to_lxoffice;
1527 $transdate = $dbh->quote($transdate);
1530 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
1532 my @part_ids = grep { $_ } values %args;
1533 my $in = join ',', ('?') x @part_ids;
1535 my %accno_by_part = map { $_->{id} => $_ }
1536 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
1538 p.id, p.inventory_accno_id AS is_part,
1539 bg.inventory_accno_id,
1540 bg.income_accno_id_$form->{taxzone_id} AS income_accno_id,
1541 bg.expense_accno_id_$form->{taxzone_id} AS expense_accno_id,
1542 c1.accno AS inventory_accno,
1543 c2.accno AS income_accno,
1544 c3.accno AS expense_accno
1546 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
1547 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
1548 LEFT JOIN chart c2 ON bg.income_accno_id_$form->{taxzone_id} = c2.id
1549 LEFT JOIN chart c3 ON bg.expense_accno_id_$form->{taxzone_id} = c3.id
1553 my $sth_tax = prepare_query($::form, $dbh, <<SQL);
1554 SELECT c.accno, t.taxdescription AS description, t.rate, t.taxnumber
1556 LEFT JOIN chart c ON c.id = t.chart_id
1560 WHERE tk.chart_id = ? AND startdate <= ?
1561 ORDER BY startdate DESC LIMIT 1)
1564 while (my ($index => $part_id) = each %args) {
1565 my $ref = $accno_by_part{$part_id} or next;
1567 $ref->{"inventory_accno_id"} = undef unless $ref->{"is_part"};
1570 for my $type (qw(inventory income expense)) {
1571 next unless $ref->{"${type}_accno_id"};
1572 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
1573 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
1576 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
1578 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate));
1579 $ref = $sth_tax->fetchrow_hashref or next;
1581 $form->{"taxaccounts_$index"} = $ref->{"accno"};
1582 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
1584 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber);
1589 $::lxdebug->leave_sub;
1592 sub get_basic_part_info {
1593 $main::lxdebug->enter_sub();
1598 Common::check_params(\%params, qw(id));
1600 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
1603 $main::lxdebug->leave_sub();
1607 my $myconfig = \%main::myconfig;
1608 my $form = $main::form;
1610 my $dbh = $form->get_standard_dbh($myconfig);
1612 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
1614 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
1616 if ('' eq ref $params{id}) {
1617 $info = $info->[0] || { };
1619 $main::lxdebug->leave_sub();
1623 my %info_map = map { $_->{id} => $_ } @{ $info };
1625 $main::lxdebug->leave_sub();
1630 sub prepare_parts_for_printing {
1631 $main::lxdebug->enter_sub();
1636 my $myconfig = $params{myconfig} || \%main::myconfig;
1637 my $form = $params{form} || $main::form;
1639 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1641 my $prefix = $params{prefix} || 'id_';
1642 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
1644 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
1647 $main::lxdebug->leave_sub();
1651 my $placeholders = join ', ', ('?') x scalar(@part_ids);
1652 my $query = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
1654 LEFT JOIN vendor v ON (mm.make = v.id)
1655 WHERE mm.parts_id IN ($placeholders)|;
1659 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
1661 while (my $ref = $sth->fetchrow_hashref()) {
1662 $makemodel{$ref->{parts_id}} ||= [];
1663 push @{ $makemodel{$ref->{parts_id}} }, $ref;
1668 my @columns = qw(ean image microfiche drawing weight);
1670 $query = qq|SELECT id, | . join(', ', @columns) . qq|
1672 WHERE id IN ($placeholders)|;
1674 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
1676 map { $form->{TEMPLATE_ARRAYS}{$_} = [] } (qw(make model), @columns);
1678 foreach my $i (1 .. $rowcount) {
1679 my $id = $form->{"${prefix}${i}"};
1683 foreach (@columns) {
1684 push @{ $form->{TEMPLATE_ARRAYS}{$_} }, $data{$id}->{$_};
1687 push @{ $form->{TEMPLATE_ARRAYS}{make} }, [];
1688 push @{ $form->{TEMPLATE_ARRAYS}{model} }, [];
1690 next if (!$makemodel{$id});
1692 foreach my $ref (@{ $makemodel{$id} }) {
1693 map { push @{ $form->{TEMPLATE_ARRAYS}{$_}->[-1] }, $ref->{$_} } qw(make model);
1697 $main::lxdebug->leave_sub();