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., 51 Franklin Street, Fifth Floor, Boston,
30 #======================================================================
32 # Inventory Control backend
34 #======================================================================
39 use List::MoreUtils qw(all any uniq);
43 use SL::HTML::Restrict;
45 use SL::Util qw(trim);
47 use SL::Presenter::Part qw(type_abbreviation classification_abbreviation separate_abbreviation);
52 sub retrieve_buchungsgruppen {
53 $main::lxdebug->enter_sub();
55 my ($self, $myconfig, $form) = @_;
59 my $dbh = $form->get_standard_dbh;
62 $query = qq|SELECT id, description FROM buchungsgruppen ORDER BY sortkey|;
63 $form->{BUCHUNGSGRUPPEN} = selectall_hashref_query($form, $dbh, $query);
65 $main::lxdebug->leave_sub();
69 $main::lxdebug->enter_sub();
71 my ($self, $myconfig, $form) = @_;
73 my $i = $form->{assembly_rows};
75 my $where = qq|1 = 1|;
78 my %columns = ("partnumber" => "p", "description" => "p", "partsgroup" => "pg");
80 while (my ($column, $table) = each(%columns)) {
81 next unless ($form->{"${column}_$i"});
82 $where .= qq| AND ${table}.${column} ILIKE ?|;
83 push(@values, like($form->{"${column}_$i"}));
87 $where .= qq| AND NOT (p.id = ?)|;
88 push(@values, conv_i($form->{id}));
91 # Search for part ID overrides all other criteria.
92 if ($form->{"id_${i}"}) {
93 $where = qq|p.id = ?|;
94 @values = ($form->{"id_${i}"});
97 if ($form->{partnumber}) {
98 $where .= qq| ORDER BY p.partnumber|;
100 $where .= qq| ORDER BY p.description|;
104 qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
106 p.weight, p.onhand, p.unit, pg.partsgroup, p.lastcost,
107 p.price_factor_id, pfac.factor AS price_factor, p.notes as longdescription
109 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
110 LEFT JOIN price_factors pfac ON pfac.id = p.price_factor_id
112 $form->{item_list} = selectall_hashref_query($form, SL::DB->client->dbh, $query, @values);
114 $main::lxdebug->leave_sub();
119 # Warning, deep magic ahead.
120 # This function gets all parts from the database according to the filters specified
123 # sort revers - sorting field + direction
126 # simple filter strings (every one of those also has a column flag prefixed with 'l_' associated):
127 # partnumber ean description partsgroup microfiche drawing
130 # 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
134 # itemstatus = active | onhand | short | obsolete | orphaned
135 # searchitems = part | assembly | service
138 # make model - makemodel
139 # serialnumber transdatefrom transdateto - invoice/orderitems
140 # warehouse - warehouse
144 # bought sold onorder ordered rfq quoted - aggreg joins with invoices/orders
145 # l_linetotal l_subtotal - aggreg joins to display totals (complicated) - NOT IMPLEMENTED here, implementation at frontend
146 # l_soldtotal - aggreg join to display total of sold quantity
147 # onhand - as above, but masking the simple itemstatus results (doh!)
148 # short - NOT IMPLEMENTED as form filter, only as itemstatus option
149 # l_serialnumber - belonges to serialnumber filter
150 # l_deliverydate - displays deliverydate is sold etc. flags are active
151 # l_soldtotal - aggreg join to display total of sold quantity, works as long as there's no bullshit in soldtotal
154 # onhand - as above, but masking the simple itemstatus results (doh!)
156 # search by overrides of description
157 # soldtotal drops option default warehouse and bin
158 # soldtotal can not work if there are no documents checked
160 # disabled sanity checks and changes:
161 # - searchitems = assembly will no longer disable bought
162 # - searchitems = service will no longer disable make and model, although services don't have make/model, it doesn't break the query
163 # - itemstatus = orphaned will no longer disable onhand short bought sold onorder ordered rfq quoted transdate[from|to]
164 # - itemstatus = obsolete will no longer disable onhand, short
165 # - allow sorting by ean
166 # - serialnumber filter also works if l_serialnumber isn't ticked
167 # - sorting will now change sorting if the requested sorting column isn't checked and doesn't get checked as a side effect
170 $main::lxdebug->enter_sub();
172 my ($self, $myconfig, $form) = @_;
173 my $dbh = $form->get_standard_dbh($myconfig);
175 # sanity backend check
176 croak "Cannot combine soldtotal with default bin or default warehouse" if ($form->{l_soldtotal} && ($form->{l_bin} || $form->{l_warehouse}));
178 $form->{parts} = +{ };
179 $form->{soldtotal} = undef if $form->{l_soldtotal}; # security fix. top100 insists on putting strings in there...
181 my @simple_filters = qw(partnumber ean description partsgroup microfiche drawing onhand);
182 my @project_filters = qw(projectnumber projectdescription);
183 my @makemodel_filters = qw(make model);
184 my @invoice_oi_filters = qw(serialnumber soldtotal);
185 my @apoe_filters = qw(transdate);
186 my @like_filters = (@simple_filters, @invoice_oi_filters);
187 my @all_columns = (@simple_filters, @makemodel_filters, @apoe_filters, @project_filters, qw(serialnumber));
188 my @simple_l_switches = (@all_columns, qw(notes listprice sellprice lastcost priceupdate weight unit rop image shop insertdate));
189 my %no_simple_l_switches = (warehouse => 'wh.description as warehouse', bin => 'bin.description as bin');
190 my @oe_flags = qw(bought sold onorder ordered rfq quoted);
191 my @qsooqr_flags = qw(invnumber ordnumber quonumber trans_id name module qty);
192 my @deliverydate_flags = qw(deliverydate);
193 # my @other_flags = qw(onhand); # ToDO: implement these
194 # my @inactive_flags = qw(l_subtotal short l_linetotal);
196 my @select_tokens = qw(id factor part_type classification_id);
197 my @where_tokens = qw(1=1);
198 my @group_tokens = ();
200 my %joins_needed = ();
203 partsgroup => 'LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)',
204 makemodel => 'LEFT JOIN makemodel mm ON (mm.parts_id = p.id)',
205 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
208 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, project_id, id FROM invoice UNION
209 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
210 ) AS ioi ON ioi.parts_id = p.id|,
213 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
214 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
215 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
216 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
219 SELECT id, name, 'customer' AS cv FROM customer UNION
220 SELECT id, name, 'vendor' AS cv FROM vendor
221 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
222 mv => 'LEFT JOIN vendor AS mv ON mv.id = mm.make',
223 project => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
224 warehouse => 'LEFT JOIN warehouse AS wh ON wh.id = p.warehouse_id',
225 bin => 'LEFT JOIN bin ON bin.id = p.bin_id',
227 my @join_order = qw(partsgroup makemodel mv invoice_oi apoe cv pfac project warehouse bin);
230 deliverydate => 'apoe.', serialnumber => 'ioi.',
231 transdate => 'apoe.', trans_id => 'ioi.',
232 module => 'apoe.', name => 'cv.',
233 ordnumber => 'apoe.', make => 'mm.',
234 quonumber => 'apoe.', model => 'mm.',
235 invnumber => 'apoe.', partsgroup => 'pg.',
236 lastcost => 'p.', , soldtotal => ' ',
237 factor => 'pfac.', projectnumber => 'pj.',
238 'SUM(ioi.qty)' => ' ', projectdescription => 'pj.',
241 serialnumber => 'ioi.',
242 quotation => 'apoe.',
248 # if the join condition in these blocks are met, the column
249 # of the specified table will gently override (coalesce actually) the original value
250 # use it to conditionally coalesce values from subtables
251 my @column_override = (
252 # column name, prefix, joins_needed, nick name (in case column is named like another)
253 [ 'description', 'ioi.', 'invoice_oi' ],
254 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
255 [ 'transdate', 'apoe.', 'apoe' ],
256 [ 'unit', 'ioi.', 'invoice_oi' ],
257 [ 'sellprice', 'ioi.', 'invoice_oi' ],
260 # careful with renames. these are HARD, and any filters done on the original column will break
261 my %renamed_columns = (
262 'factor' => 'price_factor',
263 'SUM(ioi.qty)' => 'soldtotal',
264 'ioi.id' => 'ioi_id',
266 'projectdescription' => 'projectdescription',
267 'insertdate' => 'insertdate',
271 projectdescription => 'description',
272 insertdate => 'itime::DATE',
277 my $make_token_builder = sub {
278 my $joins_needed = shift;
280 my ($nick, $alias) = @_;
281 my ($col) = $real_column{$nick} || $nick;
282 my @coalesce_tokens =
283 map { ($_->[1] || 'p.') . $_->[0] }
284 grep { !$_->[2] || $joins_needed->{$_->[2]} }
285 grep { ($_->[3] || $_->[0]) eq $nick }
286 @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
288 my $coalesce = scalar @coalesce_tokens > 1;
290 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
291 : shift @coalesce_tokens)
292 . ($alias && ($coalesce || $renamed_columns{$nick})
293 ? " AS " . ($renamed_columns{$nick} || $nick)
298 #===== switches and simple filters ========#
300 # special case transdate
301 if (grep { trim($form->{$_}) } qw(transdatefrom transdateto)) {
302 $form->{"l_transdate"} = 1;
303 push @select_tokens, 'transdate';
304 for (qw(transdatefrom transdateto)) {
305 my $value = trim($form->{$_});
307 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
308 push @bind_vars, $value;
312 # special case smart search
314 $form->{"l_$_"} = 1 for qw(partnumber description unit sellprice lastcost linetotal);
315 $form->{l_service} = 1 if $form->{searchitems} eq 'service' || $form->{searchitems} eq '';
316 $form->{l_assembly} = 1 if $form->{searchitems} eq 'assembly' || $form->{searchitems} eq '';
317 $form->{l_part} = 1 if $form->{searchitems} eq 'part' || $form->{searchitems} eq '';
318 $form->{l_assortment} = 1 if $form->{searchitems} eq 'assortment' || $form->{searchitems} eq '';
319 push @where_tokens, "p.partnumber ILIKE ? OR p.description ILIKE ?";
320 push @bind_vars, (like($form->{all})) x 2;
323 # special case insertdate
324 if (grep { trim($form->{$_}) } qw(insertdatefrom insertdateto)) {
325 $form->{"l_insertdate"} = 1;
326 push @select_tokens, 'insertdate';
328 my $token_builder = $make_token_builder->();
329 my $token = $token_builder->('insertdate');
331 for (qw(insertdatefrom insertdateto)) {
332 my $value = trim($form->{$_});
334 push @where_tokens, sprintf "$token %s ?", /from$/ ? '>=' : '<=';
335 push @bind_vars, $value;
339 if ($form->{"partsgroup_id"}) {
340 $form->{"l_partsgroup"} = '1'; # show the column
341 push @where_tokens, "pg.id = ?";
342 push @bind_vars, $form->{"partsgroup_id"};
345 if ($form->{shop} ne '') {
346 $form->{l_shop} = '1'; # show the column
347 if ($form->{shop} eq '0' || $form->{shop} eq 'f') {
348 push @where_tokens, 'NOT p.shop';
351 push @where_tokens, 'p.shop';
355 foreach (@like_filters) {
356 next unless $form->{$_};
357 $form->{"l_$_"} = '1'; # show the column
358 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
359 push @bind_vars, like($form->{$_});
362 foreach (@simple_l_switches) {
363 next unless $form->{"l_$_"};
364 push @select_tokens, $_;
367 # Oder Bedingungen fuer Ware Dienstleistung Erzeugnis:
368 if ($form->{l_part} || $form->{l_assembly} || $form->{l_service} || $form->{l_assortment}) {
370 push @or_tokens, "p.part_type = 'service'" if $form->{l_service};
371 push @or_tokens, "p.part_type = 'assembly'" if $form->{l_assembly};
372 push @or_tokens, "p.part_type = 'part'" if $form->{l_part};
373 push @or_tokens, "p.part_type = 'assortment'" if $form->{l_assortment};
374 push @where_tokens, join ' OR ', map { "($_)" } @or_tokens;
378 push @where_tokens, q|'F' = 'T'|;
381 if ( $form->{classification_id} > 0 ) {
382 push @where_tokens, "p.classification_id = ?";
383 push @bind_vars, $form->{classification_id};
386 for ($form->{itemstatus}) {
387 push @where_tokens, 'p.id NOT IN
388 (SELECT DISTINCT parts_id FROM invoice UNION
389 SELECT DISTINCT parts_id FROM assembly UNION
390 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
391 push @where_tokens, 'p.onhand = 0' if /orphaned/;
392 push @where_tokens, 'NOT p.obsolete' if /active/;
393 push @where_tokens, ' p.obsolete', if /obsolete/;
394 push @where_tokens, 'p.onhand > 0', if /onhand/;
395 push @where_tokens, 'p.onhand < p.rop', if /short/;
398 my $q_assembly_lastcost =
399 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
401 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
402 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
403 WHERE (a_lc.id = p.id)) AS assembly_lastcost|;
404 $table_prefix{$q_assembly_lastcost} = ' ';
406 # special case makemodel search
407 # all_parts is based upon the assumption that every parameter is named like the column it represents
408 # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
409 # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
411 push @where_tokens, 'mv.name ILIKE ?';
412 push @bind_vars, like($form->{make});
414 if ($form->{model}) {
415 push @where_tokens, 'mm.model ILIKE ?';
416 push @bind_vars, like($form->{model});
419 # special case: sorting by partnumber
420 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
421 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
422 # ToDO: implement proper functional sorting
423 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
424 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
425 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
426 # if $form->{sort} eq 'partnumber';
428 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
431 $limit_clause = " LIMIT 100" if $form->{top100};
432 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
434 #=== joins and complicated filters ========#
436 my $bsooqr = any { $form->{$_} } @oe_flags;
437 my @bsooqr_tokens = ();
439 push @select_tokens, @qsooqr_flags, 'quotation', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
440 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
441 push @select_tokens, $q_assembly_lastcost if $form->{l_assembly} && $form->{l_lastcost};
442 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
443 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
444 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'customer'| if $form->{ordered};
445 push @bsooqr_tokens, q|module = 'oe' AND NOT quotation AND cv = 'vendor'| if $form->{onorder};
446 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'customer'| if $form->{quoted};
447 push @bsooqr_tokens, q|module = 'oe' AND quotation AND cv = 'vendor'| if $form->{rfq};
448 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
450 $joins_needed{partsgroup} = 1;
451 $joins_needed{pfac} = 1;
452 $joins_needed{project} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
453 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
454 $joins_needed{mv} = 1 if $joins_needed{makemodel};
455 $joins_needed{cv} = 1 if $bsooqr;
456 $joins_needed{apoe} = 1 if $joins_needed{project} || $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
457 $joins_needed{invoice_oi} = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
458 $joins_needed{bin} = 1 if $form->{l_bin};
459 $joins_needed{warehouse} = 1 if $form->{l_warehouse};
461 # special case for description search.
462 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
463 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
464 # find the old entries in of @where_tokens and @bind_vars, and adjust them
465 if ($joins_needed{invoice_oi}) {
466 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
467 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
468 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
469 splice @bind_vars, $bi, 0, $bind_vars[$bi];
474 # now the master trick: soldtotal.
475 if ($form->{l_soldtotal}) {
476 push @where_tokens, 'NOT ioi.qty = 0';
477 push @group_tokens, @select_tokens;
478 map { s/.*\sAS\s+//si } @group_tokens;
479 push @select_tokens, 'SUM(ioi.qty)';
482 #============= build query ================#
484 my $token_builder = $make_token_builder->(\%joins_needed);
486 my @sort_cols = (@simple_filters, qw(id priceupdate onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate insertdate shop));
487 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
488 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
489 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
491 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
492 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
493 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
494 my $group_clause = @group_tokens ? ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens : '';
496 # key of %no_simple_l_switch is the logical l_switch.
497 # the assigned value is the 'not so simple
499 my $no_simple_select_clause;
500 foreach my $no_simple_l_switch (keys %no_simple_l_switches) {
501 next unless $form->{"l_${no_simple_l_switch}"};
502 $no_simple_select_clause .= ', '. $no_simple_l_switches{$no_simple_l_switch};
504 $select_clause .= $no_simple_select_clause;
506 my %oe_flag_to_cvar = (
509 onorder => 'orderitems',
510 ordered => 'orderitems',
512 quoted => 'orderitems',
515 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
517 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
519 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
523 $where_clause .= qq| AND ($cvar_where)|;
524 push @bind_vars, @cvar_values;
527 # simple search for assemblies by items used in assemblies
528 if ($form->{bom} eq '2' && $form->{l_assembly}) {
529 # nuke where clause and bind vars
530 $where_clause = ' 1=1 AND p.id in (SELECT id from assembly where parts_id IN ' .
531 ' (select id from parts where 1=1 AND ';
533 # use only like filter for items used in assemblies
534 foreach (@like_filters) {
535 next unless $form->{$_};
536 $form->{"l_$_"} = '1'; # show the column
537 $where_clause .= " $_ ILIKE ? ";
538 push @bind_vars, like($form->{$_});
540 $where_clause .='))';
543 my $query = <<" SQL";
544 SELECT DISTINCT $select_clause
553 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
555 map { $_->{onhand} *= 1 } @{ $form->{parts} };
557 # fix qty sign in ap. those are saved negative
558 if ($bsooqr && $form->{bought}) {
559 for my $row (@{ $form->{parts} }) {
560 $row->{qty} *= -1 if $row->{module} eq 'ir';
564 # post processing for assembly parts lists (bom)
565 # for each part get the assembly parts and add them into the partlist.
567 if ($form->{l_assembly} && $form->{bom}) {
569 qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
570 p.unit, p.notes, p.itime::DATE as insertdate,
571 p.sellprice, p.listprice, p.lastcost,
572 p.rop, p.weight, p.priceupdate,
573 p.image, p.drawing, p.microfiche,
576 INNER JOIN assembly a ON (p.id = a.parts_id)
579 my $sth = prepare_query($form, $dbh, $query);
581 foreach my $item (@{ $form->{parts} }) {
582 push(@assemblies, $item);
583 do_statement($form, $sth, $query, conv_i($item->{id}));
585 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
586 $ref->{assemblyitem} = 1;
587 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
588 push(@assemblies, $ref);
593 # copy assemblies to $form->{parts}
594 $form->{parts} = \@assemblies;
597 if ($form->{l_pricegroups} ) {
599 SELECT parts_id, price, pricegroup_id
604 my $sth = prepare_query($form, $dbh, $query);
606 foreach my $part (@{ $form->{parts} }) {
607 do_statement($form, $sth, $query, conv_i($part->{id}));
609 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
610 $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
616 $main::lxdebug->leave_sub();
618 return $form->{parts};
621 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
623 $main::lxdebug->enter_sub();
625 my ($self, $myconfig, $form, $sortorder) = @_;
626 my $dbh = $form->get_standard_dbh;
627 my $order = qq| p.partnumber|;
628 my $where = qq|1 = 1|;
631 if ($sortorder eq "all") {
632 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
633 push(@values, like($form->{partnumber}), like($form->{description}));
635 } elsif ($sortorder eq "partnumber") {
636 $where .= qq| AND (partnumber ILIKE ?)|;
637 push(@values, like($form->{partnumber}));
639 } elsif ($sortorder eq "description") {
640 $where .= qq| AND (description ILIKE ?)|;
641 push(@values, like($form->{description}));
642 $order = "description";
647 qq|SELECT id, partnumber, description, unit, sellprice,
650 WHERE $where ORDER BY $order|;
652 my $sth = prepare_execute_query($form, $dbh, $query, @values);
655 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
656 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
661 $form->{"type_and_classific_$j"} = type_abbreviation($ref->{part_type}).
662 classification_abbreviation($ref->{classification_id});
663 $form->{"id_$j"} = $ref->{id};
664 $form->{"partnumber_$j"} = $ref->{partnumber};
665 $form->{"description_$j"} = $ref->{description};
666 $form->{"unit_$j"} = $ref->{unit};
667 $form->{"sellprice_$j"} = $ref->{sellprice};
668 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
673 $main::lxdebug->leave_sub();
678 # gets sum of sold part with part_id
680 $main::lxdebug->enter_sub();
684 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
685 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
688 $main::lxdebug->leave_sub();
693 sub follow_account_chain {
694 $main::lxdebug->enter_sub(2);
696 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
698 my @visited_accno_ids = ($accno_id);
702 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
703 map { $_->{id} => $_ }
704 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
705 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
707 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
708 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
712 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
713 last unless ($ref && $ref->{"is_valid"} &&
714 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
715 $accno_id = $ref->{"new_chart_id"};
716 $accno = $ref->{"accno"};
717 push(@visited_accno_ids, $accno_id);
720 $main::lxdebug->leave_sub(2);
722 return ($accno_id, $accno);
725 sub retrieve_accounts {
726 $main::lxdebug->enter_sub;
729 my $myconfig = shift;
731 my $dbh = $form->get_standard_dbh;
732 my %args = @_; # index => part_id
734 $form->{taxzone_id} *= 1;
736 return unless grep $_, values %args; # shortfuse if no part_id supplied
740 if (($form->{type} eq "invoice") or ($form->{type} eq "credit_note") or ($form->{script} eq 'ir.pl')) {
741 # use deliverydate for sales and purchase invoice, if it exists
742 # also use deliverydate for credit notes
743 $transdate = $form->{tax_point} || $form->{deliverydate} || $form->{invdate};
746 $deliverydate = $form->{reqdate} if any { $_ eq $form->{type} } qw(sales_order request_quotation purchase_order);
747 $transdate = $form->{tax_point} || $deliverydate || $form->{transdate};
750 if ($transdate eq "") {
751 $transdate = DateTime->today_local->to_lxoffice;
753 $transdate = $dbh->quote($transdate);
756 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
758 my @part_ids = grep { $_ } values %args;
759 my $in = join ',', ('?') x @part_ids;
761 my %accno_by_part = map { $_->{id} => $_ }
762 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
765 bg.inventory_accno_id,
766 tc.income_accno_id AS income_accno_id,
767 tc.expense_accno_id AS expense_accno_id,
768 c1.accno AS inventory_accno,
769 c2.accno AS income_accno,
770 c3.accno AS expense_accno
772 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
773 LEFT JOIN taxzone_charts tc on bg.id = tc.buchungsgruppen_id
774 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
775 LEFT JOIN chart c2 ON tc.income_accno_id = c2.id
776 LEFT JOIN chart c3 ON tc.expense_accno_id = c3.id
778 tc.taxzone_id = '$form->{taxzone_id}'
783 my $query_tax = <<SQL;
784 SELECT c.accno, t.taxdescription AS description, t.id as tax_id, t.rate,
787 LEFT JOIN chart c ON c.id = t.chart_id
791 WHERE tk.chart_id = ? AND startdate <= ?
792 ORDER BY startdate DESC LIMIT 1)
794 my $sth_tax = prepare_query($::form, $dbh, $query_tax);
796 while (my ($index => $part_id) = each %args) {
797 my $ref = $accno_by_part{$part_id} or next;
799 $ref->{"inventory_accno_id"} = undef unless $ref->{"part_type"} eq 'part';
802 for my $type (qw(inventory income expense)) {
803 next unless $ref->{"${type}_accno_id"};
804 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
805 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
808 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
810 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate)) || $::form->dberror($query_tax);
811 $ref = $sth_tax->fetchrow_hashref or next;
813 $form->{"taxaccounts_$index"} = $ref->{"accno"};
814 $form->{"taxaccounts"} .= "$ref->{accno} "if $form->{"taxaccounts"} !~ /$ref->{accno}/;
816 $form->{"$ref->{accno}_${_}"} = $ref->{$_} for qw(rate description taxnumber tax_id);
821 $::lxdebug->leave_sub;
824 sub get_basic_part_info {
825 $main::lxdebug->enter_sub();
830 Common::check_params(\%params, qw(id));
832 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
835 $main::lxdebug->leave_sub();
839 my $myconfig = \%main::myconfig;
840 my $form = $main::form;
842 my $dbh = $form->get_standard_dbh($myconfig);
844 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
846 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
848 if ('' eq ref $params{id}) {
849 $info = $info->[0] || { };
851 $main::lxdebug->leave_sub();
855 my %info_map = map { $_->{id} => $_ } @{ $info };
857 $main::lxdebug->leave_sub();
862 sub prepare_parts_for_printing {
863 $main::lxdebug->enter_sub();
868 my $myconfig = $params{myconfig} || \%main::myconfig;
869 my $form = $params{form} || $main::form;
871 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
873 my $prefix = $params{prefix} || 'id_';
874 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
876 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
879 $main::lxdebug->leave_sub();
883 my $placeholders = join ', ', ('?') x scalar(@part_ids);
884 my $query = qq|SELECT mm.parts_id, mm.model, mm.lastcost, v.name AS make
886 LEFT JOIN vendor v ON (mm.make = v.id)
887 WHERE mm.parts_id IN ($placeholders)|;
891 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
893 while (my $ref = $sth->fetchrow_hashref()) {
894 $makemodel{$ref->{parts_id}} ||= [];
895 push @{ $makemodel{$ref->{parts_id}} }, $ref;
902 cp.customer_partnumber AS customer_model,
903 c.name AS customer_make
904 FROM part_customer_prices cp
905 LEFT JOIN customer c ON (cp.customer_id = c.id)
906 WHERE cp.parts_id IN ($placeholders)|;
908 my %customermodel = ();
910 $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
912 while (my $ref = $sth->fetchrow_hashref()) {
913 $customermodel{$ref->{parts_id}} ||= [];
914 push @{ $customermodel{$ref->{parts_id}} }, $ref;
919 my @columns = qw(ean image microfiche drawing);
921 $query = qq|SELECT id, | . join(', ', @columns) . qq|
923 WHERE id IN ($placeholders)|;
925 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
928 map { $template_arrays{$_} = [] } (qw(make model customer_make customer_model), @columns);
930 foreach my $i (1 .. $rowcount) {
931 my $id = $form->{"${prefix}${i}"};
936 push @{ $template_arrays{$_} }, $data{$id}->{$_};
939 push @{ $template_arrays{make} }, [];
940 push @{ $template_arrays{model} }, [];
942 if ($makemodel{$id}) {
943 foreach my $ref (@{ $makemodel{$id} }) {
944 map { push @{ $template_arrays{$_}->[-1] }, $ref->{$_} } qw(make model);
948 push @{ $template_arrays{customer_make} }, [];
949 push @{ $template_arrays{customer_model} }, [];
951 if ($customermodel{$id}) {
952 foreach my $ref (@{ $customermodel{$id} }) {
953 push @{ $template_arrays{$_}->[-1] }, $ref->{$_} for qw(customer_make customer_model);
959 my $parts = SL::DB::Manager::Part->get_all(query => [ id => \@part_ids ]);
960 my %parts_by_id = map { $_->id => $_ } @$parts;
962 for my $i (1..$rowcount) {
963 my $id = $form->{"${prefix}${i}"};
965 my $prt = $parts_by_id{$id};
966 my $type_abbr = type_abbreviation($prt->part_type);
967 push @{ $template_arrays{part_type} }, $prt->part_type;
968 push @{ $template_arrays{part_abbreviation} }, $type_abbr;
969 push @{ $template_arrays{type_and_classific}}, $type_abbr . classification_abbreviation($prt->classification_id);
970 push @{ $template_arrays{separate} }, separate_abbreviation($prt->classification_id);
973 $main::lxdebug->leave_sub();
974 return %template_arrays;