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 | order_locked | 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 notes);
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', price_factor_description => 'pfac.description as price_factor_description');
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 LATERAL (
205 SELECT string_agg(mv.vendornumber || ' ' || mv.name, ', ') AS make,
206 string_agg(mm.model, ', ') AS model
208 LEFT JOIN vendor mv ON (mv.id = mm.make)
209 WHERE mm.parts_id = p.id
211 pfac => 'LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)',
214 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, assemblyitem, deliverydate, 'invoice' AS ioi, project_id, id FROM invoice UNION
215 SELECT parts_id, description, serialnumber, trans_id, unit, sellprice, qty, FALSE AS assemblyitem, NULL AS deliverydate, 'orderitems' AS ioi, project_id, id FROM orderitems
216 ) AS ioi ON ioi.parts_id = p.id|,
219 SELECT id, transdate, 'ir' AS module, ordnumber, quonumber, invnumber, 'purchase_invoice' AS record_type, NULL AS customer_id, vendor_id, NULL AS deliverydate, globalproject_id, 'invoice' AS ioi FROM ap UNION
220 SELECT id, transdate, 'is' AS module, ordnumber, quonumber, invnumber, 'sales_invoice' AS record_type, customer_id, NULL AS vendor_id, deliverydate, globalproject_id, 'invoice' AS ioi FROM ar UNION
221 SELECT id, transdate, 'oe' AS module, ordnumber, quonumber, NULL AS invnumber, record_type::text, customer_id, vendor_id, reqdate AS deliverydate, globalproject_id, 'orderitems' AS ioi FROM oe
222 ) AS apoe ON ((ioi.trans_id = apoe.id) AND (ioi.ioi = apoe.ioi))|,
225 SELECT id, name, 'customer' AS cv FROM customer UNION
226 SELECT id, name, 'vendor' AS cv FROM vendor
227 ) AS cv ON cv.id = apoe.customer_id OR cv.id = apoe.vendor_id|,
228 project => 'LEFT JOIN project AS pj ON pj.id = COALESCE(ioi.project_id, apoe.globalproject_id)',
229 warehouse => 'LEFT JOIN warehouse AS wh ON wh.id = p.warehouse_id',
230 bin => 'LEFT JOIN bin ON bin.id = p.bin_id',
232 my @join_order = qw(partsgroup makemodel invoice_oi apoe cv pfac project warehouse bin);
235 deliverydate => 'apoe.', serialnumber => 'ioi.',
236 transdate => 'apoe.', trans_id => 'ioi.',
237 module => 'apoe.', name => 'cv.',
238 ordnumber => 'apoe.', make => 'mm.',
239 quonumber => 'apoe.', model => 'mm.',
240 invnumber => 'apoe.', partsgroup => 'pg.',
241 lastcost => 'p.', , soldtotal => ' ',
242 factor => 'pfac.', projectnumber => 'pj.',
243 'SUM(ioi.qty)' => ' ', projectdescription => 'pj.',
246 serialnumber => 'ioi.',
247 record_type => 'apoe.',
253 # if the join condition in these blocks are met, the column
254 # of the specified table will gently override (coalesce actually) the original value
255 # use it to conditionally coalesce values from subtables
256 my @column_override = (
257 # column name, prefix, joins_needed, nick name (in case column is named like another)
258 [ 'description', 'ioi.', 'invoice_oi' ],
259 [ 'deliverydate', 'ioi.', 'invoice_oi' ],
260 [ 'transdate', 'apoe.', 'apoe' ],
261 [ 'unit', 'ioi.', 'invoice_oi' ],
262 [ 'sellprice', 'ioi.', 'invoice_oi' ],
265 # careful with renames. these are HARD, and any filters done on the original column will break
266 my %renamed_columns = (
267 'factor' => 'price_factor',
268 'SUM(ioi.qty)' => 'soldtotal',
269 'ioi.id' => 'ioi_id',
271 'projectdescription' => 'projectdescription',
272 'insertdate' => 'insertdate',
276 projectdescription => 'description',
277 insertdate => 'itime::DATE',
280 my $make_token_builder = sub {
281 my $joins_needed = shift;
283 my ($nick, $alias) = @_;
284 my ($col) = $real_column{$nick} || $nick;
285 my @coalesce_tokens =
286 map { ($_->[1] || 'p.') . $_->[0] }
287 grep { !$_->[2] || $joins_needed->{$_->[2]} }
288 grep { ($_->[3] || $_->[0]) eq $nick }
289 @column_override, [ $col, $table_prefix{$nick}, undef , $nick ];
291 my $coalesce = scalar @coalesce_tokens > 1;
293 ? sprintf 'COALESCE(%s)', join ', ', @coalesce_tokens
294 : shift @coalesce_tokens)
295 . ($alias && ($coalesce || $renamed_columns{$nick})
296 ? " AS " . ($renamed_columns{$nick} || $nick)
301 #===== switches and simple filters ========#
303 # special case transdate
304 if (grep { trim($form->{$_}) } qw(transdatefrom transdateto)) {
305 $form->{"l_transdate"} = 1;
306 push @select_tokens, 'transdate';
307 for (qw(transdatefrom transdateto)) {
308 my $value = trim($form->{$_});
310 push @where_tokens, sprintf "transdate %s ?", /from$/ ? '>=' : '<=';
311 push @bind_vars, $value;
315 # special case smart search
317 $form->{"l_$_"} = 1 for qw(partnumber description unit sellprice lastcost linetotal);
318 $form->{l_service} = 1 if $form->{searchitems} eq 'service' || $form->{searchitems} eq '';
319 $form->{l_assembly} = 1 if $form->{searchitems} eq 'assembly' || $form->{searchitems} eq '';
320 $form->{l_part} = 1 if $form->{searchitems} eq 'part' || $form->{searchitems} eq '';
321 $form->{l_assortment} = 1 if $form->{searchitems} eq 'assortment' || $form->{searchitems} eq '';
322 push @where_tokens, "p.partnumber ILIKE ? OR p.description ILIKE ?";
323 push @bind_vars, (like($form->{all})) x 2;
326 # special case insertdate
327 if (grep { trim($form->{$_}) } qw(insertdatefrom insertdateto)) {
328 $form->{"l_insertdate"} = 1;
329 push @select_tokens, 'insertdate';
331 my $token_builder = $make_token_builder->();
332 my $token = $token_builder->('insertdate');
334 for (qw(insertdatefrom insertdateto)) {
335 my $value = trim($form->{$_});
337 push @where_tokens, sprintf "$token %s ?", /from$/ ? '>=' : '<=';
338 push @bind_vars, $value;
342 if ($form->{"partsgroup_id"}) {
343 $form->{"l_partsgroup"} = '1'; # show the column
344 push @where_tokens, "pg.id = ?";
345 push @bind_vars, $form->{"partsgroup_id"};
348 if ($form->{shop} ne '') {
349 $form->{l_shop} = '1'; # show the column
350 if ($form->{shop} eq '0' || $form->{shop} eq 'f') {
351 push @where_tokens, 'NOT p.shop';
354 push @where_tokens, 'p.shop';
358 foreach (@like_filters) {
359 next unless $form->{$_};
360 $form->{"l_$_"} = '1'; # show the column
361 push @where_tokens, "$table_prefix{$_}$_ ILIKE ?";
362 push @bind_vars, like($form->{$_});
365 foreach (@simple_l_switches) {
366 next unless $form->{"l_$_"};
367 push @select_tokens, $_;
370 # Oder Bedingungen fuer Ware Dienstleistung Erzeugnis:
371 if ($form->{l_part} || $form->{l_assembly} || $form->{l_service} || $form->{l_assortment}) {
373 push @or_tokens, "p.part_type = 'service'" if $form->{l_service};
374 push @or_tokens, "p.part_type = 'assembly'" if $form->{l_assembly};
375 push @or_tokens, "p.part_type = 'part'" if $form->{l_part};
376 push @or_tokens, "p.part_type = 'assortment'" if $form->{l_assortment};
377 push @where_tokens, join ' OR ', map { "($_)" } @or_tokens;
381 push @where_tokens, q|'F' = 'T'|;
384 if ( $form->{classification_id} > 0 ) {
385 push @where_tokens, "p.classification_id = ?";
386 push @bind_vars, $form->{classification_id};
389 for ($form->{itemstatus}) {
390 push @where_tokens, 'p.id NOT IN
391 (SELECT DISTINCT parts_id FROM invoice UNION
392 SELECT DISTINCT parts_id FROM assembly UNION
393 SELECT DISTINCT parts_id FROM orderitems)' if /orphaned/;
394 push @where_tokens, 'p.onhand = 0' if /orphaned/;
395 push @where_tokens, 'NOT p.obsolete' if /active/;
396 push @where_tokens, ' p.obsolete', if /obsolete/;
397 push @where_tokens, 'p.onhand > 0', if /onhand/;
398 push @where_tokens, 'p.onhand < p.rop', if /short/;
399 push @where_tokens, 'p.order_locked', if /order_locked/;
402 my $q_assembly_lastcost =
403 qq|(SELECT SUM(a_lc.qty * p_lc.lastcost / COALESCE(pfac_lc.factor, 1))
405 LEFT JOIN parts p_lc ON (a_lc.parts_id = p_lc.id)
406 LEFT JOIN price_factors pfac_lc ON (p_lc.price_factor_id = pfac_lc.id)
407 WHERE (a_lc.id = p.id)) AS assembly_lastcost|;
408 $table_prefix{$q_assembly_lastcost} = ' ';
410 # special case makemodel search
411 # all_parts is based upon the assumption that every parameter is named like the column it represents
412 # unfortunately make would have to match vendor.name which is already taken for vendor.name in bsooqr mode.
413 # fortunately makemodel doesn't need to be displayed later, so adding a special clause to where_token is sufficient.
414 # the lateral join mm already creates a string consisting of vendornumbers and vendornames in mm.make
415 # and the models in mm.make
417 push @where_tokens, 'mm.make ILIKE ?';
418 push @bind_vars, like($form->{make});
420 if ($form->{model}) {
421 push @where_tokens, 'mm.model ILIKE ?';
422 push @bind_vars, like($form->{model});
425 # special case: sorting by partnumber
426 # since partnumbers are expected to be prefixed integers, a special sorting is implemented sorting first lexically by prefix and then by suffix.
427 # and yes, that expression is designed to hold that array of regexes only once, so the map is kinda messy, sorry about that.
428 # ToDO: implement proper functional sorting
429 # Nette Idee von Sven, gibt aber Probleme wenn die Artikelnummern groesser als 32bit sind. Korrekt waere es, dass Sort-Natural-Modul zu nehmen
430 # Ich lass das mal hier drin, damit die Idee erhalten bleibt jb 28.5.2009 bug 1018
431 #$form->{sort} = join ', ', map { push @select_tokens, $_; ($table_prefix{$_} = "substring(partnumber,'[") . $_ } qw|^[:digit:]]+') [:digit:]]+')::INTEGER|
432 # if $form->{sort} eq 'partnumber';
434 #my $order_clause = " ORDER BY $form->{sort} $sort_order";
437 $limit_clause = " LIMIT 100" if $form->{top100};
438 $limit_clause = " LIMIT " . $form->{limit} * 1 if $form->{limit} * 1;
440 #=== joins and complicated filters ========#
442 my $bsooqr = any { $form->{$_} } @oe_flags;
443 my @bsooqr_tokens = ();
445 push @select_tokens, @qsooqr_flags, 'record_type', 'cv', 'ioi.id', 'ioi.ioi' if $bsooqr;
446 push @select_tokens, @deliverydate_flags if $bsooqr && $form->{l_deliverydate};
447 push @select_tokens, $q_assembly_lastcost if $form->{l_assembly} && $form->{l_lastcost};
448 push @bsooqr_tokens, q|module = 'ir' AND NOT ioi.assemblyitem| if $form->{bought};
449 push @bsooqr_tokens, q|module = 'is' AND NOT ioi.assemblyitem| if $form->{sold};
450 push @bsooqr_tokens, q|module = 'oe' AND record_type = 'sales_order'| if $form->{ordered};
451 push @bsooqr_tokens, q|module = 'oe' AND record_type = 'purchase_order'| if $form->{onorder};
452 push @bsooqr_tokens, q|module = 'oe' AND record_type = 'sales_quotation'| if $form->{quoted};
453 push @bsooqr_tokens, q|module = 'oe' AND record_type = 'request_quotation'| if $form->{rfq};
454 push @where_tokens, join ' OR ', map { "($_)" } @bsooqr_tokens if $bsooqr;
456 $joins_needed{partsgroup} = 1;
457 $joins_needed{pfac} = 1;
458 $joins_needed{project} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @project_filters;
459 $joins_needed{makemodel} = 1 if grep { $form->{$_} || $form->{"l_$_"} } @makemodel_filters;
460 $joins_needed{cv} = 1 if $bsooqr;
461 $joins_needed{apoe} = 1 if $joins_needed{project} || $joins_needed{cv} || grep { $form->{$_} || $form->{"l_$_"} } @apoe_filters;
462 $joins_needed{invoice_oi} = 1 if $joins_needed{project} || $joins_needed{apoe} || grep { $form->{$_} || $form->{"l_$_"} } @invoice_oi_filters;
463 $joins_needed{bin} = 1 if $form->{l_bin};
464 $joins_needed{warehouse} = 1 if $form->{l_warehouse};
466 # special case for description search.
467 # up in the simple filter section the description filter got interpreted as something like: WHERE description ILIKE '%$form->{description}%'
468 # now we'd like to search also for the masked description entered in orderitems and invoice, so...
469 # find the old entries in of @where_tokens and @bind_vars, and adjust them
470 if ($joins_needed{invoice_oi}) {
471 for (my ($wi, $bi) = (0)x2; $wi <= $#where_tokens; $bi++ if $where_tokens[$wi++] =~ /\?/) {
472 next unless $where_tokens[$wi] =~ /\bdescription ILIKE/;
473 splice @where_tokens, $wi, 1, 'p.description ILIKE ? OR ioi.description ILIKE ?';
474 splice @bind_vars, $bi, 0, $bind_vars[$bi];
479 # now the master trick: soldtotal.
480 if ($form->{l_soldtotal}) {
481 push @where_tokens, 'NOT ioi.qty = 0';
482 push @group_tokens, @select_tokens;
483 map { s/.*\sAS\s+//si } @group_tokens;
484 push @select_tokens, 'SUM(ioi.qty)';
487 #============= build query ================#
489 my $token_builder = $make_token_builder->(\%joins_needed);
491 my @sort_cols = (@simple_filters, qw(id onhand invnumber ordnumber quonumber name serialnumber soldtotal deliverydate insertdate shop));
492 $form->{sort} = 'id' unless grep { $form->{"l_$_"} } grep { $form->{sort} eq $_ } @sort_cols; # sort by id if unknown or invisible column
493 my $sort_order = ($form->{revers} ? ' DESC' : ' ASC');
494 my $order_clause = " ORDER BY " . $token_builder->($form->{sort}) . ($form->{revers} ? ' DESC' : ' ASC');
496 my $select_clause = join ', ', map { $token_builder->($_, 1) } @select_tokens;
497 my $join_clause = join ' ', @joins{ grep $joins_needed{$_}, @join_order };
498 my $where_clause = join ' AND ', map { "($_)" } @where_tokens;
499 my $group_clause = @group_tokens ? ' GROUP BY ' . join ', ', map { $token_builder->($_) } @group_tokens : '';
501 # key of %no_simple_l_switch is the logical l_switch.
502 # the assigned value is the 'not so simple
504 my $no_simple_select_clause;
505 foreach my $no_simple_l_switch (keys %no_simple_l_switches) {
506 next unless $form->{"l_${no_simple_l_switch}"};
507 $no_simple_select_clause .= ', '. $no_simple_l_switches{$no_simple_l_switch};
509 $select_clause .= $no_simple_select_clause;
511 my %oe_flag_to_cvar = (
514 onorder => 'orderitems',
515 ordered => 'orderitems',
517 quoted => 'orderitems',
520 my ($cvar_where, @cvar_values) = CVar->build_filter_query(
522 trans_id_field => $bsooqr ? 'ioi.id': 'p.id',
524 sub_module => $bsooqr ? [ uniq grep { $oe_flag_to_cvar{$form->{$_}} } @oe_flags ] : undef,
528 $where_clause .= qq| AND ($cvar_where)|;
529 push @bind_vars, @cvar_values;
532 # simple search for assemblies by items used in assemblies
533 if ($form->{bom} eq '2' && $form->{l_assembly}) {
534 # assembly_qty is the column name
535 $form->{l_assembly_qty} = 1;
536 # nuke where clause and bind vars
537 $where_clause = ' 1=1 AND p.id in (SELECT id from assembly where parts_id IN ' .
538 ' (select id from parts where 1=1';
540 # use only like filter for items used in assemblies
541 foreach (@like_filters) {
542 next unless $form->{$_};
543 $form->{"l_$_"} = '1'; # show the column
544 $where_clause .= " AND $_ ILIKE ? ";
545 push @bind_vars, like($form->{$_});
547 $where_clause .='))';
550 my $query = <<" SQL";
551 SELECT DISTINCT $select_clause
559 $form->{parts} = selectall_hashref_query($form, $dbh, $query, @bind_vars);
561 map { $_->{onhand} *= 1 } @{ $form->{parts} };
563 # fix qty sign in ap. those are saved negative
564 if ($bsooqr && $form->{bought}) {
565 for my $row (@{ $form->{parts} }) {
566 $row->{qty} *= -1 if $row->{module} eq 'ir';
570 # post processing for assembly parts lists (bom)
571 # for each part get the assembly parts and add them into the partlist.
573 if ($form->{l_assembly} && $form->{bom}) {
575 qq|SELECT p.id, p.partnumber, p.description, a.qty AS assembly_qty,
576 p.unit, p.notes, p.itime::DATE as insertdate,
577 p.sellprice, p.listprice, p.lastcost,
579 p.image, p.drawing, p.microfiche,
582 INNER JOIN assembly a ON (p.id = a.parts_id)
585 my $sth = prepare_query($form, $dbh, $query);
587 foreach my $item (@{ $form->{parts} }) {
588 push(@assemblies, $item);
589 do_statement($form, $sth, $query, conv_i($item->{id}));
591 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
592 $ref->{assemblyitem} = 1;
593 map { $ref->{$_} /= $ref->{factor} || 1 } qw(sellprice listprice lastcost);
594 push(@assemblies, $ref);
599 # copy assemblies to $form->{parts}
600 $form->{parts} = \@assemblies;
603 if ($form->{l_pricegroups} ) {
605 SELECT parts_id, price, pricegroup_id
610 my $sth = prepare_query($form, $dbh, $query);
612 foreach my $part (@{ $form->{parts} }) {
613 do_statement($form, $sth, $query, conv_i($part->{id}));
615 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
616 $part->{"pricegroup_$ref->{pricegroup_id}"} = $ref->{price};
622 $main::lxdebug->leave_sub();
624 return $form->{parts};
627 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
629 $main::lxdebug->enter_sub();
631 my ($self, $myconfig, $form, $sortorder) = @_;
632 my $dbh = $form->get_standard_dbh;
633 my $order = qq| p.partnumber|;
634 my $where = qq|1 = 1|;
637 if ($sortorder eq "all") {
638 $where .= qq| AND (partnumber ILIKE ?) AND (description ILIKE ?)|;
639 push(@values, like($form->{partnumber}), like($form->{description}));
641 } elsif ($sortorder eq "partnumber") {
642 $where .= qq| AND (partnumber ILIKE ?)|;
643 push(@values, like($form->{partnumber}));
645 } elsif ($sortorder eq "description") {
646 $where .= qq| AND (description ILIKE ?)|;
647 push(@values, like($form->{description}));
648 $order = "description";
653 qq|SELECT id, partnumber, description, unit, sellprice,
656 WHERE $where ORDER BY $order|;
658 my $sth = prepare_execute_query($form, $dbh, $query, @values);
661 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
662 if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
667 $form->{"type_and_classific_$j"} = type_abbreviation($ref->{part_type}).
668 classification_abbreviation($ref->{classification_id});
669 $form->{"id_$j"} = $ref->{id};
670 $form->{"partnumber_$j"} = $ref->{partnumber};
671 $form->{"description_$j"} = $ref->{description};
672 $form->{"unit_$j"} = $ref->{unit};
673 $form->{"sellprice_$j"} = $ref->{sellprice};
674 $form->{"soldtotal_$j"} = get_soldtotal($dbh, $ref->{id});
679 $main::lxdebug->leave_sub();
684 # gets sum of sold part with part_id
686 $main::lxdebug->enter_sub();
690 my $query = qq|SELECT sum(qty) FROM invoice WHERE parts_id = ?|;
691 my ($sum) = selectrow_query($main::form, $dbh, $query, conv_i($id));
694 $main::lxdebug->leave_sub();
699 sub follow_account_chain {
700 $main::lxdebug->enter_sub(2);
702 my ($self, $form, $dbh, $transdate, $accno_id, $accno) = @_;
704 my @visited_accno_ids = ($accno_id);
708 $form->{ACCOUNT_CHAIN_BY_ID} ||= {
709 map { $_->{id} => $_ }
710 selectall_hashref_query($form, $dbh, <<SQL, $transdate) };
711 SELECT c.id, c.new_chart_id, date(?) >= c.valid_from AS is_valid, cnew.accno
713 LEFT JOIN chart cnew ON c.new_chart_id = cnew.id
714 WHERE NOT c.new_chart_id IS NULL AND (c.new_chart_id > 0)
718 my $ref = $form->{ACCOUNT_CHAIN_BY_ID}->{$accno_id};
719 last unless ($ref && $ref->{"is_valid"} &&
720 !grep({ $_ == $ref->{"new_chart_id"} } @visited_accno_ids));
721 $accno_id = $ref->{"new_chart_id"};
722 $accno = $ref->{"accno"};
723 push(@visited_accno_ids, $accno_id);
726 $main::lxdebug->leave_sub(2);
728 return ($accno_id, $accno);
731 sub retrieve_accounts {
732 $main::lxdebug->enter_sub;
735 my $myconfig = shift;
737 my $dbh = $form->get_standard_dbh;
738 my %args = @_; # index => part_id
740 $form->{taxzone_id} *= 1;
742 return unless grep $_, values %args; # shortfuse if no part_id supplied
746 if ( (any {$form->{type} eq $_} qw(invoice credit_note invoice_for_advance_payment final_invoice)) or ($form->{script} eq 'ir.pl') ) {
747 # use deliverydate for sales and purchase invoice, if it exists
748 # also use deliverydate for credit notes
749 $transdate = $form->{tax_point} || $form->{deliverydate} || $form->{invdate};
752 $deliverydate = $form->{reqdate} if any { $_ eq $form->{type} } qw(sales_order request_quotation purchase_order);
753 $transdate = $form->{tax_point} || $deliverydate || $form->{transdate};
756 if ($transdate eq "") {
757 $transdate = DateTime->today_local->to_lxoffice;
759 $transdate = $dbh->quote($transdate);
762 my $inc_exp = $form->{"vc"} eq "customer" ? "income_accno_id" : "expense_accno_id";
764 my @part_ids = grep { $_ } values %args;
765 my $in = join ',', ('?') x @part_ids;
767 my %accno_by_part = map { $_->{id} => $_ }
768 selectall_hashref_query($form, $dbh, <<SQL, @part_ids);
771 bg.inventory_accno_id,
772 tc.income_accno_id AS income_accno_id,
773 tc.expense_accno_id AS expense_accno_id,
774 c1.accno AS inventory_accno,
775 c2.accno AS income_accno,
776 c3.accno AS expense_accno
778 LEFT JOIN buchungsgruppen bg ON p.buchungsgruppen_id = bg.id
779 LEFT JOIN taxzone_charts tc on bg.id = tc.buchungsgruppen_id
780 LEFT JOIN chart c1 ON bg.inventory_accno_id = c1.id
781 LEFT JOIN chart c2 ON tc.income_accno_id = c2.id
782 LEFT JOIN chart c3 ON tc.expense_accno_id = c3.id
784 tc.taxzone_id = '$form->{taxzone_id}'
789 my $query_tax = <<SQL;
790 SELECT c.accno, t.taxdescription AS description, t.id as tax_id, t.rate,
793 LEFT JOIN chart c ON c.id = t.chart_id
797 WHERE tk.chart_id = ? AND startdate <= ?
798 ORDER BY startdate DESC LIMIT 1)
800 my $sth_tax = prepare_query($::form, $dbh, $query_tax);
802 while (my ($index => $part_id) = each %args) {
803 my $ref = $accno_by_part{$part_id} or next;
805 $ref->{"inventory_accno_id"} = undef unless $ref->{"part_type"} eq 'part';
808 for my $type (qw(inventory income expense)) {
809 next unless $ref->{"${type}_accno_id"};
810 ($accounts{"${type}_accno_id"}, $accounts{"${type}_accno"}) =
811 $self->follow_account_chain($form, $dbh, $transdate, $ref->{"${type}_accno_id"}, $ref->{"${type}_accno"});
814 $form->{"${_}_accno_$index"} = $accounts{"${_}_accno"} for qw(inventory income expense);
815 $form->{"${_}_accno_id_$index"} = $accounts{"${_}_accno_id"} for qw(inventory expense); # only for purchase_invoice
817 $sth_tax->execute($accounts{$inc_exp}, quote_db_date($transdate)) || $::form->dberror($query_tax);
819 $tax_ref = $sth_tax->fetchrow_hashref or next;
821 $form->{"expense_accno_tax_id_$index"} = $tax_ref->{tax_id}; # only for purchase_invoice
823 $form->{"taxaccounts_$index"} = $tax_ref->{"accno"};
824 $form->{"taxaccounts"} .= "$tax_ref->{accno} "if $form->{"taxaccounts"} !~ /$tax_ref->{accno}/;
826 $form->{"$tax_ref->{accno}_${_}"} = $tax_ref->{$_} for qw(rate description taxnumber tax_id);
831 $::lxdebug->leave_sub;
834 sub get_basic_part_info {
835 $main::lxdebug->enter_sub();
840 Common::check_params(\%params, qw(id));
842 my @ids = 'ARRAY' eq ref $params{id} ? @{ $params{id} } : ($params{id});
845 $main::lxdebug->leave_sub();
849 my $myconfig = \%main::myconfig;
850 my $form = $main::form;
852 my $dbh = $form->get_standard_dbh($myconfig);
854 my $query = qq|SELECT * FROM parts WHERE id IN (| . join(', ', ('?') x scalar(@ids)) . qq|)|;
856 my $info = selectall_hashref_query($form, $dbh, $query, map { conv_i($_) } @ids);
858 if ('' eq ref $params{id}) {
859 $info = $info->[0] || { };
861 $main::lxdebug->leave_sub();
865 my %info_map = map { $_->{id} => $_ } @{ $info };
867 $main::lxdebug->leave_sub();
872 sub prepare_parts_for_printing {
873 $main::lxdebug->enter_sub();
878 my $myconfig = $params{myconfig} || \%main::myconfig;
879 my $form = $params{form} || $main::form;
881 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
883 my $prefix = $params{prefix} || 'id_';
884 my $rowcount = defined $params{rowcount} ? $params{rowcount} : $form->{rowcount};
886 my @part_ids = keys %{ { map { $_ => 1 } grep { $_ } map { $form->{"${prefix}${_}"} } (1 .. $rowcount) } };
889 $main::lxdebug->leave_sub();
893 my $placeholders = join ', ', ('?') x scalar(@part_ids);
894 my $query = qq|SELECT mm.parts_id, mm.model,
895 mm.part_description AS mm_part_description,
896 mm.part_longdescription AS mm_part_longdescription,
897 mm.lastcost, v.name AS make
899 LEFT JOIN vendor v ON (mm.make = v.id)
900 WHERE mm.parts_id IN ($placeholders)|;
904 my $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
906 while (my $ref = $sth->fetchrow_hashref()) {
907 $makemodel{$ref->{parts_id}} ||= [];
908 push @{ $makemodel{$ref->{parts_id}} }, $ref;
914 $query = qq|SELECT bm.parts_id,
915 bm.model AS business_model,
916 bm.part_description AS bm_part_description,
917 bm.part_longdescription AS bm_part_longdescription,
918 b.description AS business_make
919 FROM business_models bm
920 LEFT JOIN business b ON (bm.business_id = b.id)
921 WHERE bm.parts_id IN ($placeholders)|;
923 my %businessmodel = ();
925 $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
927 while (my $ref = $sth->fetchrow_hashref()) {
928 $businessmodel{$ref->{parts_id}} ||= [];
929 push @{ $businessmodel{$ref->{parts_id}} }, $ref;
936 cp.customer_partnumber AS customer_model,
937 cp.part_description AS cm_part_description,
938 cp.part_longdescription AS cm_part_longdescription,
939 c.name AS customer_make
940 FROM part_customer_prices cp
941 LEFT JOIN customer c ON (cp.customer_id = c.id)
942 WHERE cp.parts_id IN ($placeholders)|;
944 my %customermodel = ();
946 $sth = prepare_execute_query($form, $dbh, $query, @part_ids);
948 while (my $ref = $sth->fetchrow_hashref()) {
949 $customermodel{$ref->{parts_id}} ||= [];
950 push @{ $customermodel{$ref->{parts_id}} }, $ref;
955 my @columns = qw(ean image microfiche drawing tariff_code);
957 $query = qq|SELECT id, | . join(', ', @columns) . qq|
959 WHERE id IN ($placeholders)|;
961 my %data = selectall_as_map($form, $dbh, $query, 'id', \@columns, @part_ids);
964 map { $template_arrays{$_} = [] } (qw(make model mm_part_description mm_part_longdescription business_make business_model bm_part_description bm_part_longdescription customer_make customer_model cm_part_description cm_part_longdescription), @columns);
966 foreach my $i (1 .. $rowcount) {
967 my $id = $form->{"${prefix}${i}"};
972 push @{ $template_arrays{$_} }, $data{$id}->{$_};
975 push @{ $template_arrays{make} }, [];
976 push @{ $template_arrays{model} }, [];
977 push @{ $template_arrays{mm_part_description} }, [];
978 push @{ $template_arrays{mm_part_longdescription} }, [];
980 if ($makemodel{$id}) {
981 foreach my $ref (@{ $makemodel{$id} }) {
982 map { push @{ $template_arrays{$_}->[-1] }, $ref->{$_} } qw(make model mm_part_description mm_part_longdescription);
986 push @{ $template_arrays{business_make} }, [];
987 push @{ $template_arrays{business_model} }, [];
988 push @{ $template_arrays{bm_part_description} }, [];
989 push @{ $template_arrays{bm_part_longdescription} }, [];
991 if ($businessmodel{$id}) {
992 foreach my $ref (@{ $businessmodel{$id} }) {
993 map { push @{ $template_arrays{$_}->[-1] }, $ref->{$_} } qw(business_make business_model bm_part_description bm_part_longdescription);
997 push @{ $template_arrays{customer_make} }, [];
998 push @{ $template_arrays{customer_model} }, [];
999 push @{ $template_arrays{cm_part_description} }, [];
1000 push @{ $template_arrays{cm_part_longdescription} }, [];
1002 if ($customermodel{$id}) {
1003 foreach my $ref (@{ $customermodel{$id} }) {
1004 push @{ $template_arrays{$_}->[-1] }, $ref->{$_} for qw(customer_make customer_model cm_part_description cm_part_longdescription);
1010 my $parts = SL::DB::Manager::Part->get_all(query => [ id => \@part_ids ]);
1011 my %parts_by_id = map { $_->id => $_ } @$parts;
1013 for my $i (1..$rowcount) {
1014 my $id = $form->{"${prefix}${i}"};
1016 my $prt = $parts_by_id{$id};
1017 my $type_abbr = type_abbreviation($prt->part_type);
1018 push @{ $template_arrays{part_type} }, $prt->part_type;
1019 push @{ $template_arrays{part_abbreviation} }, $type_abbr;
1020 push @{ $template_arrays{type_and_classific}}, $type_abbr . classification_abbreviation($prt->classification_id);
1021 push @{ $template_arrays{separate} }, separate_abbreviation($prt->classification_id);
1024 $main::lxdebug->leave_sub();
1025 return %template_arrays;