Projekt

Allgemein

Profil

Herunterladen (90,9 KB) Statistiken
| Zweig: | Markierung: | Revision:
d319704a Moritz Bunkus
#=====================================================================
# LX-Office ERP
# Copyright (C) 2004
# Based on SQL-Ledger Version 2.1.9
# Web http://www.lx-office.org
#############################################################################
4091b37c Geoffrey Richardson
# Changelog: Wann - Wer - Was
6ac037ce Sven Schöling
# Veraendert 2005-01-05 - Marco Welter <mawe@linux-studio.de> - Neue Optik
# 08.11.2008 - information@richardson-bueren.de jb - Backport von Revision 7339 xplace - E-Mail-Vorlage automatisch auswählen
4091b37c Geoffrey Richardson
# 02.02.2009 - information@richardson-bueren.de jb - Backport von Revision 8535 xplace - Erweiterung der Waren bei Lieferantenauftrag um den Eintrag Mindestlagerbestand. Offen: Auswahlliste auf Lieferantenaufträge einschränken -> Erledigt 2.2.09 Prüfung wie das Skript heisst (oe.pl) -> das ist nur die halbe Miete, nochmal mb fragen -> mb gefragt und es gibt die variable is_purchase
d319704a Moritz Bunkus
#############################################################################
# SQL-Ledger, Accounting
# Copyright (c) 1998-2002
#
# Author: Dieter Simader
# Email: dsimader@sql-ledger.org
# Web: http://www.sql-ledger.org
#
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
f7b15d43 Christian Wittmer
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1335, USA.
d319704a Moritz Bunkus
#
#######################################################################
#
# common routines used in is, ir, oe
#
#######################################################################

cb253140 Moritz Bunkus
use Carp;
d9c9bc22 Moritz Bunkus
use CGI;
eebe8e90 Sven Schöling
use List::MoreUtils qw(any uniq apply);
50fb51d9 Moritz Bunkus
use List::Util qw(sum min max first);
dd33cbec Moritz Bunkus
use List::UtilsBy qw(sort_by uniq_by);
d9c9bc22 Moritz Bunkus
5bc87ade Moritz Bunkus
use SL::ClientJS;
8688e71e Moritz Bunkus
use SL::CVar;
6d1df9ca Moritz Bunkus
use SL::Common;
5bc87ade Moritz Bunkus
use SL::Controller::Base;
e492c53b Moritz Bunkus
use SL::CT;
049e49fe Sven Schöling
use SL::Locale::String qw(t8);
b3501bdf Moritz Bunkus
use SL::IC;
8c7e4493 Moritz Bunkus
use SL::IO;
a40f0c2f Martin Helmling
use SL::File;
eebe8e90 Sven Schöling
use SL::PriceSource;
0aa885f4 Sven Schöling
use SL::Presenter::Part;
fc3b49d6 Tamino Steinert
use SL::Presenter::Chart;
use SL::Presenter::Tag;
c48270dd Bernd Bleßmann
use SL::Util qw(trim);
b3501bdf Moritz Bunkus
c48270dd Bernd Bleßmann
use SL::DB::AuthUser;
22bcb6b1 Moritz Bunkus
use SL::DB::Contact;
598383b3 Bernd Bleßmann
use SL::DB::Currency;
361a37a3 Moritz Bunkus
use SL::DB::Customer;
a32fcad2 Sven Schöling
use SL::DB::DeliveryOrder::TypeData qw();
2e66dde5 Moritz Bunkus
use SL::DB::Default;
64084bfa Sven Schöling
use SL::DB::Language;
use SL::DB::Printer;
361a37a3 Moritz Bunkus
use SL::DB::Vendor;
a0516348 Moritz Bunkus
use SL::Helper::CreatePDF;
a40f0c2f Martin Helmling
use SL::Helper::Flash;
22bcb6b1 Moritz Bunkus
use SL::Helper::PrintOptions;
e80aa4c8 Sven Schöling
use SL::Helper::ShippedQty;
64084bfa Sven Schöling
d629acd8 Sven Schöling
require "bin/mozilla/common.pl";
acc2b53b Moritz Bunkus
9da3e39b Sven Schöling
use strict;

d319704a Moritz Bunkus
# any custom scripts for this one
d629acd8 Sven Schöling
if (-f "bin/mozilla/custom_io.pl") {
eval { require "bin/mozilla/custom_io.pl"; };
d319704a Moritz Bunkus
}
4bd1e2f8 Sven Schöling
if (-f "bin/mozilla/$::myconfig{login}_io.pl") {
eval { require "bin/mozilla/$::myconfig{login}_io.pl"; };
d319704a Moritz Bunkus
}

1;

# end of main

# this is for our long dates
# $locale->text('January')
# $locale->text('February')
# $locale->text('March')
# $locale->text('April')
# $locale->text('May ')
# $locale->text('June')
# $locale->text('July')
# $locale->text('August')
# $locale->text('September')
# $locale->text('October')
# $locale->text('November')
# $locale->text('December')

# this is for our short month
# $locale->text('Jan')
# $locale->text('Feb')
# $locale->text('Mar')
# $locale->text('Apr')
# $locale->text('May')
# $locale->text('Jun')
# $locale->text('Jul')
# $locale->text('Aug')
# $locale->text('Sep')
# $locale->text('Oct')
# $locale->text('Nov')
# $locale->text('Dec')
07d71c33 Stephan Köhler
use SL::IS;
54e4131e Moritz Bunkus
use SL::AM;
d319704a Moritz Bunkus
use Data::Dumper;
12ce5ee7 Moritz Bunkus
sub _check_io_auth {
5fc3e9ba Sven Schöling
$main::auth->assert('part_service_assembly_edit | vendor_invoice_edit | sales_order_edit | invoice_edit |' .
12ce5ee7 Moritz Bunkus
'request_quotation_edit | sales_quotation_edit | purchase_order_edit | ' .
db9a3208 Niclas Zimmermann
'purchase_delivery_order_edit | sales_delivery_order_edit | part_service_assembly_details');
12ce5ee7 Moritz Bunkus
}

d319704a Moritz Bunkus
########################################
# Eintrag fuer Version 2.2.0 geaendert #
# neue Optik im Rechnungsformular #
########################################
91ab1ef6 Sven Schöling
sub display_row {
9da3e39b Sven Schöling
$main::lxdebug->enter_sub();
8c7e4493 Moritz Bunkus
9da3e39b Sven Schöling
my $form = $main::form;
my %myconfig = %main::myconfig;
my $locale = $main::locale;
5494f687 Sven Schöling
my $cgi = $::request->{cgi};
9da3e39b Sven Schöling
91ab1ef6 Sven Schöling
my $numrows = shift;

1ed28475 Jan Büren
my ($stock_in_out, $stock_in_out_title);
8c7e4493 Moritz Bunkus
fe6275f8 Niclas Zimmermann
my $defaults = AM->get_defaults();
$form->{show_weight} = $defaults->{show_weight};
$form->{weightunit} = $defaults->{weightunit};

d707f7ac Moritz Bunkus
my $is_purchase = (first { $_ eq $form->{type} } qw(request_quotation purchase_order purchase_delivery_order)) || ($form->{script} eq 'ir.pl');
my $is_delivery_order = $form->{type} =~ /_delivery_order$/;
8f3f4aa6 Jan Büren
my $is_quotation = $form->{type} =~ /_quotation$/;
my $is_invoice = $form->{type} =~ /invoice/;
74959706 Sven Schöling
my $is_credit_note = $form->{type} =~ /credit_note/;
480d9a56 Moritz Bunkus
my $is_s_p_order = (first { $_ eq $form->{type} } qw(sales_order purchase_order));
317450cb Moritz Bunkus
my $show_ship_missing = $is_s_p_order && $::instance_conf->get_sales_purchase_order_ship_missing_column;
74959706 Sven Schöling
my $show_marge = (!$is_purchase || $is_invoice || $is_credit_note) && !$is_delivery_order;
d707f7ac Moritz Bunkus
if ($is_delivery_order) {
if ($form->{type} eq 'sales_delivery_order') {
$stock_in_out_title = $locale->text('Release From Stock');
$stock_in_out = 'out';
} else {
$stock_in_out_title = $locale->text('Transfer To Stock');
$stock_in_out = 'in';
}
137c9df3 Moritz Bunkus
retrieve_partunits();
d707f7ac Moritz Bunkus
}
8c7e4493 Moritz Bunkus
91ab1ef6 Sven Schöling
# column_index
74959706 Sven Schöling
my @header_sort = qw(
aa184cd2 Jan Büren
runningnumber partnumber vendor_partnumber type_and_classific description ship ship_missing qty price_factor
74959706 Sven Schöling
unit weight price_source sellprice discount linetotal
bin stock_in_out
6ac037ce Sven Schöling
);
65f0bba8 Tamino Steinert
# position of serialnr is used below!
74959706 Sven Schöling
my @row2_sort = qw(
8865cc74 Tamino Steinert
tax_chart tax serialnr projectnr reqdate subtotal recurring_billing_mode marge listprice lastcost onhand
ebd668c1 Tamino Steinert
orderer
74959706 Sven Schöling
);
cbb3aa42 Jan Büren
# serialnr is important for delivery_orders
if ($form->{type} eq 'sales_delivery_order') {
65f0bba8 Tamino Steinert
splice @row2_sort, 0, 3;
096113b3 Jan Büren
splice @header_sort, 4, 0, "serialnr";
cbb3aa42 Jan Büren
}

74959706 Sven Schöling
my %column_def = (
runningnumber => { width => 5, value => $locale->text('No.'), display => 1, },
partnumber => { width => 8, value => $locale->text('Number'), display => 1, },
65d2537d Martin Helmling
type_and_classific
=> { width => 2, value => $locale->text('Type'), display => 1, },
74959706 Sven Schöling
description => { width => 30, value => $locale->text('Part Description'), display => 1, },
ship => { width => 5, value => $locale->text('Delivered'), display => $is_s_p_order, },
ship_missing => { width => 5, value => $locale->text('Not delivered'), display => $show_ship_missing, },
qty => { width => 5, value => $locale->text('Qty'), display => 1, },
price_factor => { width => 5, value => $locale->text('Price Factor'), display => !$is_delivery_order, },
unit => { width => 5, value => $locale->text('Unit'), display => 1, },
weight => { width => 5, value => $locale->text('Weight'), display => $defaults->{show_weight}, },
serialnr => { width => 10, value => $locale->text('Serial No.'), display => !$is_quotation },
projectnr => { width => 10, value => $locale->text('Project'), display => 1, },
price_source => { width => 5, value => $locale->text('Price Source'), display => !$is_delivery_order, },
sellprice => { width => 15, value => $locale->text('Price'), display => !$is_delivery_order, },
discount => { width => 5, value => $locale->text('Discount'), display => !$is_delivery_order, },
linetotal => { width => 10, value => $locale->text('Extended'), display => !$is_delivery_order, },
bin => { width => 10, value => $locale->text('Bin'), display => 0, },
stock_in_out => { width => 10, value => $stock_in_out_title, display => $is_delivery_order, },
reqdate => { value => $locale->text('Reqdate'), display => $is_s_p_order || $is_delivery_order || $is_invoice, },
subtotal => { value => $locale->text('Subtotal'), display => 1, },
8e927544 Moritz Bunkus
recurring_billing_mode => { value => $locale->text('Recurring billing'), display => $form->{type} eq 'sales_order', },
74959706 Sven Schöling
marge => { value => $locale->text('Ertrag'), display => $show_marge, },
listprice => { value => $locale->text('LP'), display => $show_marge, },
lastcost => { value => $locale->text('EK'), display => $show_marge, },
onhand => { value => $locale->text('On Hand'), display => 1, },
aa184cd2 Jan Büren
vendor_partnumber => { width => 8, value => $locale->text('Vendor Part Number'), display => $is_delivery_order && $is_purchase, },
8865cc74 Tamino Steinert
tax_chart => { value => "", display => $is_purchase && $is_invoice },
fc3b49d6 Tamino Steinert
tax => { value => $locale->text('Tax'), display => $is_purchase && $is_invoice },
ebd668c1 Tamino Steinert
orderer => { width => 10, value => $locale->text('Orderer'), display => 1, },
74959706 Sven Schöling
);
my @HEADER = map { $column_def{$_} } @header_sort;
da804bf2 Geoffrey Richardson
91ab1ef6 Sven Schöling
# cache units
my $all_units = AM->retrieve_units(\%myconfig, $form);

59d350af Moritz Bunkus
my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };

91ab1ef6 Sven Schöling
$form->{invsubtotal} = 0;
map { $form->{"${_}_base"} = 0 } (split(/ /, $form->{taxaccounts}));

6ac037ce Sven Schöling
# about details
91ab1ef6 Sven Schöling
$myconfig{show_form_details} = 1 unless (defined($myconfig{show_form_details}));
$form->{show_details} = $myconfig{show_form_details} unless (defined($form->{show_details}));
# /about details

# translations, unused commented out
9da3e39b Sven Schöling
my $deliverydate = $locale->text('Required by');
91ab1ef6 Sven Schöling
# special alignings
317450cb Moritz Bunkus
my %align = map { $_ => 'right' } qw(qty ship right discount linetotal stock_in_out weight ship_missing);
2dfa3a4c Sven Schöling
my %nowrap = map { $_ => 1 } qw(description unit price_source);
91ab1ef6 Sven Schöling
$form->{marge_total} = 0;
$form->{sellprice_total} = 0;
$form->{lastcost_total} = 0;
a7ecfa38 Niclas Zimmermann
$form->{totalweight} = 0;
91ab1ef6 Sven Schöling
my %projectnumber_labels = ();
my @projectnumber_values = ("");

foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
push(@projectnumber_values, $item->{"id"});
$projectnumber_labels{$item->{"id"}} = $item->{"projectnumber"};
}

480d9a56 Moritz Bunkus
_update_part_information();
_update_ship() if ($is_s_p_order);
ef220490 Moritz Bunkus
_update_custom_variables();
480d9a56 Moritz Bunkus
a7ecfa38 Niclas Zimmermann
my $totalweight = 0;
2de7b1da Niclas Zimmermann
0409db7c Sven Schöling
my $record = _make_record();
91ab1ef6 Sven Schöling
# rows
9da3e39b Sven Schöling
my @ROWS;
for my $i (1 .. $numrows) {
32394d82 Moritz Bunkus
my %column_data = ();
91ab1ef6 Sven Schöling
89b26688 Sven Schöling
my $record_item = $record->id && $record->items ? $record->items->[$i-1] : _make_record_item($i);

91ab1ef6 Sven Schöling
# undo formatting
a590a651 Sven Schöling
map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) }
qw(qty discount sellprice lastcost price_new price_old)
da804bf2 Geoffrey Richardson
unless ($form->{simple_save});
91ab1ef6 Sven Schöling
6573d4a4 Bernd Bleßmann
if ($form->{"prices_$i"} && ($form->{"new_pricegroup_$i"} != $form->{"old_pricegroup_$i"})) {
$form->{"sellprice_$i"} = $form->{"price_new_$i"};
}

91ab1ef6 Sven Schöling
# unit begin
$form->{"unit_old_$i"} ||= $form->{"unit_$i"};
$form->{"selected_unit_$i"} ||= $form->{"unit_$i"};

07948c34 Moritz Bunkus
if ( !$all_units->{$form->{"selected_unit_$i"}} # Die ausgewaehlte Einheit ist fuer diesen Artikel nicht gueltig
91ab1ef6 Sven Schöling
|| !AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units)) { # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber
$form->{"unit_old_$i"} = $form->{"selected_unit_$i"} = $form->{"unit_$i"}; # um eine Dienstleistung). Dann keinerlei Umrechnung vornehmen.
}
eebe8e90 Sven Schöling
$form->{"sellprice_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1;
$form->{"lastcost_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"unit_old_$i"}, $all_units) || 1;
$form->{"unit_old_$i"} = $form->{"selected_unit_$i"};

91ab1ef6 Sven Schöling
my $this_unit = $form->{"unit_$i"};
$this_unit = $form->{"selected_unit_$i"} if AM->convert_unit($this_unit, $form->{"selected_unit_$i"}, $all_units);

59d350af Moritz Bunkus
if (0 < scalar @{ $form->{ALL_PRICE_FACTORS} }) {
my @values = ('', map { $_->{id} } @{ $form->{ALL_PRICE_FACTORS} });
my %labels = map { $_->{id} => $_->{description} } @{ $form->{ALL_PRICE_FACTORS} };

8c7e4493 Moritz Bunkus
$column_data{price_factor} =
59d350af Moritz Bunkus
NTI($cgi->popup_menu('-name' => "price_factor_id_$i",
'-default' => $form->{"price_factor_id_$i"},
'-values' => \@values,
'-labels' => \%labels,
8c7e4493 Moritz Bunkus
'-style' => 'width:90px'));
} else {
$column_data{price_factor} = '&nbsp;';
59d350af Moritz Bunkus
}
2de7b1da Niclas Zimmermann
$form->{"weight_$i"} *= AM->convert_unit($form->{"selected_unit_$i"}, $form->{"partunit_$i"}, $all_units) || 1;
59d350af Moritz Bunkus
07948c34 Moritz Bunkus
$column_data{"unit"} = AM->unit_select_html($all_units, "unit_$i", $this_unit, $form->{"id_$i"} ? $form->{"unit_$i"} : undef);
91ab1ef6 Sven Schöling
# / unit ending

e2b15672 Niclas Zimmermann
#count the max of decimalplaces of sellprice and lastcost, so the same number of decimalplaces
#is shown for lastcost and sellprice.
5e579516 Sven Schöling
my $decimalplaces = ($form->{"sellprice_$i"} =~ /\.(\d+)/) ? max 2, length $1 : 2;
e2b15672 Niclas Zimmermann
$decimalplaces = ($form->{"lastcost_$i"} =~ /\.(\d+)/) ? max $decimalplaces, length $1 : $decimalplaces;
91ab1ef6 Sven Schöling
9da3e39b Sven Schöling
my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || 1;
my $discount = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} * $form->{"discount_$i"} / 100 / $price_factor, 2);
my $linetotal = $form->round_amount($form->{"qty_$i"} * $form->{"sellprice_$i"} * (100 - $form->{"discount_$i"}) / 100 / $price_factor, 2);
my $rows = $form->numtextrows($form->{"description_$i"}, 30, 6);
91ab1ef6 Sven Schöling
cd2dd28b Jan Büren
# quick delete single row
65d2537d Martin Helmling
$column_data{runningnumber} = q|<a onclick= "$('#partnumber_| . $i . q|').val(''); $('#update_button').click();">| .
717b8076 Sven Schöling
q|<img class="icon-delete" alt="| . $locale->text('Remove') . q|"></a> |;
cd2dd28b Jan Büren
$column_data{runningnumber} .= $cgi->textfield(-name => "runningnumber_$i", -id => "runningnumber_$i", -size => 5, -value => $i); # HuT


8d72d404 Moritz Bunkus
$column_data{partnumber} = $cgi->textfield(-name => "partnumber_$i", -id => "partnumber_$i", -size => 12, -value => $form->{"partnumber_$i"});
aa184cd2 Jan Büren
$column_data{vendor_partnumber} = $form->{"vendor_partnumber_$i"};
0aa885f4 Sven Schöling
$column_data{type_and_classific} = SL::Presenter::Part::type_abbreviation($form->{"part_type_$i"}).
SL::Presenter::Part::classification_abbreviation($form->{"classification_id_$i"}) if $form->{"id_$i"};
9da3e39b Sven Schöling
$column_data{description} = (($rows > 1) # if description is too large, use a textbox instead
8d72d404 Moritz Bunkus
? $cgi->textarea( -name => "description_$i", -id => "description_$i", -default => $form->{"description_$i"}, -rows => $rows, -columns => 30)
: $cgi->textfield(-name => "description_$i", -id => "description_$i", -value => $form->{"description_$i"}, -size => 30))
. $cgi->button(-value => $locale->text('L'), -onClick => "kivi.SalesPurchase.edit_longdescription($i)");
91ab1ef6 Sven Schöling
5e579516 Sven Schöling
my $qty_dec = ($form->{"qty_$i"} =~ /\.(\d+)/) ? length $1 : 2;
91ab1ef6 Sven Schöling
18c72e9a Bernd Bleßmann
$column_data{qty} = $cgi->textfield(-name => "qty_$i", -size => 5, -class => "numeric", -value => $form->format_amount(\%myconfig, $form->{"qty_$i"}, $qty_dec));
6770b19a Bernd Bleßmann
$column_data{qty} .= $cgi->button(-onclick => "calculate_qty_selection_dialog('qty_$i', '', 'formel_$i', '')", -value => $locale->text('*/'))
b92bc207 Bernd Bleßmann
. $cgi->hidden(-name => "formel_$i", -value => $form->{"formel_$i"})
91ab1ef6 Sven Schöling
if $form->{"formel_$i"};
c66624d0 Moritz Bunkus
$column_data{ship} = '';
if ($form->{"id_$i"}) {
my $ship_qty = $form->{"ship_$i"} * 1;
$ship_qty *= $all_units->{$form->{"partunit_$i"}}->{factor};
f7a568a1 Sven Schöling
$ship_qty /= ( $all_units->{$form->{"unit_$i"}}->{factor} || 1 );
c66624d0 Moritz Bunkus
d814a525 Martin Helmling
$column_data{ship} = $form->format_amount(\%myconfig, $form->round_amount($ship_qty, 2) * 1) . ' ' . $form->{"unit_$i"}
becf01a3 Moritz Bunkus
. $cgi->hidden(-name => "ship_$i", -value => $form->{"ship_$i"}, $qty_dec);
317450cb Moritz Bunkus
my $ship_missing_qty = $form->{"qty_$i"} - $ship_qty;
my $ship_missing_amount = $form->round_amount($ship_missing_qty * $form->{"sellprice_$i"} * (100 - $form->{"discount_$i"}) / 100 / $price_factor, 2);

$column_data{ship_missing} = $form->format_amount(\%myconfig, $ship_missing_qty) . ' ' . $form->{"unit_$i"} . '; ' . $form->format_amount(\%myconfig, $ship_missing_amount, $decimalplaces);
c66624d0 Moritz Bunkus
}
91ab1ef6 Sven Schöling
$column_data{linetotal} = $form->format_amount(\%myconfig, $linetotal, 2);
$column_data{bin} = $form->{"bin_$i"};

fe6275f8 Niclas Zimmermann
$column_data{weight} = $form->format_amount(\%myconfig, $form->{"qty_$i"} * $form->{"weight_$i"}, 3) . ' ' . $defaults->{weightunit} if $defaults->{show_weight};
a7ecfa38 Niclas Zimmermann
2dfa3a4c Sven Schöling
my $sellprice_value = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
my $discount_value = $form->format_amount(\%myconfig, $form->{"discount_$i"});

my $price;
47bded0e Sven Schöling
if ($form->{"id_${i}"} && !$is_delivery_order) {
7991ed2b Sven Schöling
my $price_source = SL::PriceSource->new(record_item => $record_item, record => $record);
2dfa3a4c Sven Schöling
$price = $price_source->price_from_source($::form->{"active_price_source_$i"});
e1c3b6b7 Bernd Bleßmann
my $discount = $price_source->discount_from_source($::form->{"active_discount_source_$i"});
7991ed2b Sven Schöling
my $best_price = $price_source->best_price;
my $best_discount = $price_source->best_discount;
cf63992e Sven Schöling
$column_data{price_source} .= $cgi->button(-value => $price->source_description, -onClick => "kivi.io.price_chooser($i)");
049e49fe Sven Schöling
if ($price->source) {
$column_data{price_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $price->invalid, title => $price->invalid }) if $price->invalid;
$column_data{price_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $price->missing, title => $price->missing }) if $price->missing;
89b26688 Sven Schöling
if (!$price->missing && !$price->invalid) {
0153e51a Sven Schöling
$column_data{price_source} .= ' ' . $cgi->img({src => 'image/up.png', alt => t8('This price has since gone up'), title => t8('This price has since gone up' ) }) if $price->price - $record_item->sellprice > 0.01;
$column_data{price_source} .= ' ' . $cgi->img({src => 'image/down.png', alt => t8('This price has since gone down'), title => t8('This price has since gone down') }) if $price->price - $record_item->sellprice < -0.01;
7991ed2b Sven Schöling
$column_data{price_source} .= ' ' . $cgi->img({src => 'image/ok.png', alt => t8('There is a better price available'), title => t8('There is a better price available') }) if $best_price && $price->source ne $price_source->best_price->source;
89b26688 Sven Schöling
}
}
if ($discount->source) {
$column_data{discount_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $discount->invalid, title => $discount->invalid }) if $discount->invalid;
$column_data{discount_source} .= ' ' . $cgi->img({src => 'image/flag-red.png', alt => $discount->missing, title => $discount->missing }) if $discount->missing;
if (!$discount->missing && !$discount->invalid) {
0153e51a Sven Schöling
$column_data{price_source} .= ' ' . $cgi->img({src => 'image/up.png', alt => t8('This discount has since gone up'), title => t8('This discount has since gone up') }) if $discount->discount * 100 - $record_item->discount > 0.01;
$column_data{price_source} .= ' ' . $cgi->img({src => 'image/down.png', alt => t8('This discount has since gone down'), title => t8('This discount has since gone down') }) if $discount->discount * 100 - $record_item->discount < -0.01;
7991ed2b Sven Schöling
$column_data{price_source} .= ' ' . $cgi->img({src => 'image/ok.png', alt => t8('There is a better discount available'), title => t8('There is a better discount available') }) if $best_discount && $discount->source ne $price_source->best_discount->source;
89b26688 Sven Schöling
}
049e49fe Sven Schöling
}
eebe8e90 Sven Schöling
}

0d060ae4 Bernd Bleßmann
my $right_to_edit_prices = (!$is_purchase && $main::auth->assert('sales_edit_prices', 1)) || ($is_purchase && $main::auth->assert('purchase_edit_prices', 1));
my $edit_prices = $right_to_edit_prices && (!$::form->{"active_price_source_$i"} || !$price || $price->editable);
my $edit_discounts = $right_to_edit_prices && !$::form->{"active_discount_source_$i"};
2dfa3a4c Sven Schöling
$column_data{sellprice} = (!$edit_prices)
? $cgi->hidden( -name => "sellprice_$i", -id => "sellprice_$i", -value => $sellprice_value) . $sellprice_value
18c72e9a Bernd Bleßmann
: $cgi->textfield(-name => "sellprice_$i", -id => "sellprice_$i", -size => 10, -class => "numeric", -value => $sellprice_value);
2dfa3a4c Sven Schöling
$column_data{discount} = (!$edit_discounts)
? $cgi->hidden( -name => "discount_$i", -id => "discount_$i", -value => $discount_value) . $discount_value . ' %'
3f264030 Sven Schöling
: $cgi->textfield(-name => "discount_$i", -id => "discount_$i", -size => 3, -"data-validate" => "number", -class => "numeric", -value => $discount_value);
2dfa3a4c Sven Schöling
d707f7ac Moritz Bunkus
if ($is_delivery_order) {
dc6e7f0d Geoffrey Richardson
$column_data{stock_in_out} = calculate_stock_in_out($i);
d707f7ac Moritz Bunkus
}

82eea3be Tamino Steinert
# tax_chart and tax
if ($is_purchase && $is_invoice) { #only calc if used
my ($tax_chart_id, $chart_title, $chart_picker);
if ($record_item && $record_item->part && ($record_item->part->type eq 'part')) {
my $tax_chart_type = $form->{"tax_chart_type_$i"};
$tax_chart_type ||=
$::instance_conf->get_inventory_system eq 'periodic' ? 'expense'
: 'inventory';
$tax_chart_id = $form->{"${tax_chart_type}_chart_id_$i"};

$chart_title = SL::Presenter::Tag::select_tag("tax_chart_type_$i", [
{value => 'expense', title => $locale->text('Expense Account')},
{value => 'inventory', title => $locale->text('Inventory Account')},
],
value_key => 'value', title_key => 'title',
default => $tax_chart_type,
onchange => "kivi.io.update_tax_chart_picker(this.value, $i)",
8865cc74 Tamino Steinert
);
82eea3be Tamino Steinert
$chart_picker =
SL::Presenter::Tag::html_tag('span',
SL::Presenter::Chart::chart_picker(
"expense_chart_id_$i", $form->{"expense_chart_id_$i"},
type => "AP_amount", style => "width: 150px"),
id => "expense_chart_span_$i",
style => $tax_chart_type eq 'expense' ? '' : 'display:none',
)
.
SL::Presenter::Tag::html_tag('span',
SL::Presenter::Chart::chart_picker(
"inventory_chart_id_$i", $form->{"inventory_chart_id_$i"},
type => "IC", style => "width: 150px"),
id => "inventory_chart_span_$i",
style => $tax_chart_type eq 'inventory' ? '' : 'display:none',
);
} else {
$tax_chart_id = $form->{"expense_chart_id_$i"};
$chart_title = $locale->text('Expense Account');
$chart_picker = SL::Presenter::Chart::chart_picker(
"expense_chart_id_$i", $form->{"expense_chart_id_$i"},
type => "AP_amount", style => "width: 150px");
}
# change tax dropdown after change
my $js_set_on_select_item = '<script type="text/javascript">
<!--
$(document).ready(function() {
$("#expense_chart_id_' . $i . '").on("set_item:ChartPicker", function(e, item) {
kivi.io.update_tax_ids(this);
});
$("#inventory_chart_id_' . $i . '").on("set_item:ChartPicker", function(e, item) {
kivi.io.update_tax_ids(this);
});
fc3b49d6 Tamino Steinert
});
82eea3be Tamino Steinert
-->
</script>
';
$column_data{tax_chart} = SL::Presenter::Tag::html_tag('span',
$chart_title . $chart_picker . $js_set_on_select_item);

my $tax_value_title_sub = sub {
my $item = shift;
return [
$item->{id},
$item->{taxkey} . ' - ' . $item->{taxdescription} .' '. ($item->{rate} * 100) .' %',
];
};

my @taxes = ();
if ($form->{"expense_chart_id_$i"}) {
@taxes = IO->get_active_taxes_for_chart($tax_chart_id,
$form->{"reqdate_$i"} // $form->{deliverydate} // $form->{transdate});
}
# tax_id_ is used in io.js->update_tax_ids
$column_data{tax} = SL::Presenter::Tag::select_tag(
"tax_id_$i", \@taxes, default => $form->{"tax_id_$i"},
value_title_sub => $tax_value_title_sub,
style => "width: 100px");
fc3b49d6 Tamino Steinert
}

f2463a51 Tamino Steinert
$column_data{serialnr} = qq|<input name="serialnumber_$i" size="15" value="$form->{"serialnumber_$i"}" data-validate="trimmed_whitespaces">|;
74959706 Sven Schöling
$column_data{projectnr} = NTI($cgi->popup_menu(
'-name' => "project_id_$i",
'-values' => \@projectnumber_values,
'-labels' => \%projectnumber_labels,
'-default' => $form->{"project_id_$i"}
));
58eece5d Sven Schöling
$column_data{reqdate} = qq|<input name="reqdate_$i" size="11" data-validate="date" value="$form->{"reqdate_$i"}">|;
74959706 Sven Schöling
$column_data{subtotal} = sprintf qq|<input type="checkbox" name="subtotal_$i" value="1" %s>|, $form->{"subtotal_$i"} ? 'checked' : '';
8e927544 Moritz Bunkus
$column_data{recurring_billing_mode} = SL::Presenter::Tag::select_tag(
"recurring_billing_mode_$i",
[[ 'always', $::locale->text('always') ], [ 'once', $::locale->text('once') ], [ 'never', $::locale->text('never') ]],
default => $::form->{"recurring_billing_mode_$i"} || 'always',
);
91ab1ef6 Sven Schöling
ebd668c1 Tamino Steinert
# Orderer
$column_data{orderer} = qq|: $form->{"orderer_$i"}|;

8e927544 Moritz Bunkus
# begin marge calculations
6a41eac6 Sven Schöling
$form->{"lastcost_$i"} *= 1;
91ab1ef6 Sven Schöling
$form->{"marge_percent_$i"} = 0;

6a41eac6 Sven Schöling
my $marge_color;
1ee0a247 Geoffrey Richardson
my $real_sellprice;
if ( $form->{taxincluded} and $form->{"qty_$i"} * 1 and $form->{$form->{"taxaccounts_$i"} . "_rate"} * 1) {
# if we use taxincluded we need to calculate the marge from the net_value
# all the marge calculations are based on linetotal which we need to
# convert to net first

# there is no direct form value for the tax_rate of the item, but
# form->{taxaccounts_$i} gives the tax account (e.g. 3806) and 3806_rate
# gives the tax percentage (e.g. 0.19)
$real_sellprice = $linetotal / (1 + $form->{$form->{"taxaccounts_$i"} . "_rate"});
} else {
$real_sellprice = $linetotal;
};
b82722d0 Bernd Bleßmann
my $real_lastcost = $form->round_amount($form->{"lastcost_$i"} * $form->{"qty_$i"}, 2);
6a41eac6 Sven Schöling
my $marge_percent_warn = $myconfig{marge_percent_warn} * 1 || 15;
my $marge_adjust_credit_note = $form->{type} eq 'credit_note' ? -1 : 1;

if ($real_sellprice * 1 && ($form->{"qty_$i"} * 1)) {
$form->{"marge_percent_$i"} = ($real_sellprice - $real_lastcost) * 100 / $real_sellprice;
$marge_color = 'color="#ff0000"' if $form->{"id_$i"} && $form->{"marge_percent_$i"} < $marge_percent_warn;
91ab1ef6 Sven Schöling
}

6a41eac6 Sven Schöling
$form->{"marge_absolut_$i"} = ($real_sellprice - $real_lastcost) * $marge_adjust_credit_note;
91ab1ef6 Sven Schöling
$form->{"marge_total"} += $form->{"marge_absolut_$i"};
6a41eac6 Sven Schöling
$form->{"lastcost_total"} += $real_lastcost;
$form->{"sellprice_total"} += $real_sellprice;
91ab1ef6 Sven Schöling
map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2) } qw(marge_absolut marge_percent);

74959706 Sven Schöling
$column_data{marge} = sprintf qq|<font %s>%s &nbsp;%s%%</font>|,
$marge_color, $form->{"marge_absolut_$i"}, $form->{"marge_percent_$i"};
$column_data{listprice} = $form->format_amount(\%myconfig, $form->{"listprice_$i"}, 2);
$column_data{lastcost} = sprintf qq|<input size="5" name="lastcost_$i" value="%s">|, $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
91ab1ef6 Sven Schöling
# / marge calculations ending

a7ecfa38 Niclas Zimmermann
# Calculate total weight
$totalweight += ($form->{"qty_$i"} * $form->{"weight_$i"});

cc3a0a33 Sven Schöling
# calculate onhand
if ($form->{"id_$i"}) {
my $part = IC->get_basic_part_info(id => $form->{"id_$i"});
74fca575 Sven Schöling
my $onhand_color = $part->{onhand} < $part->{rop} ? 'color="#ff0000"' : '';
74959706 Sven Schöling
$column_data{onhand} = sprintf "<font %s>%s %s</font>",
cc3a0a33 Sven Schöling
$onhand_color,
$form->format_amount(\%myconfig, $part->{onhand}, 2),
74959706 Sven Schöling
$part->{unit};
cc3a0a33 Sven Schöling
}
# / calculate onhand

74959706 Sven Schöling
my @ROW1 = map { { value => $column_data{$_}, align => $align{$_}, nowrap => $nowrap{$_} } } grep { $column_def{$_}{display} } @header_sort;
my @ROW2 = map { { value => sprintf "<b>%s</b> %s", $column_def{$_}{value}, $column_data{$_} } } grep { $column_def{$_}{display} } @row2_sort;

8c7e4493 Moritz Bunkus
my @hidden_vars;
8f3f4aa6 Jan Büren
# add hidden ids for persistent (item|invoice)_ids and previous (converted_from*) ids
if ($is_quotation) {
991d16bb Jan Büren
push @hidden_vars, qw(orderitems_id converted_from_orderitems_id);
8f3f4aa6 Jan Büren
}
if ($is_s_p_order) {
2f9a5220 Jan Büren
push @hidden_vars, qw(orderitems_id converted_from_orderitems_id converted_from_invoice_id);
8f3f4aa6 Jan Büren
}
if ($is_invoice) {
b8125c17 Bernd Bleßmann
push @hidden_vars, qw(invoice_id converted_from_orderitems_id converted_from_delivery_order_items_id converted_from_invoice_id);
8f3f4aa6 Jan Büren
}
f087c373 Jan Büren
if ($::form->{type} =~ /credit_note/) {
748ce36f Tamino Steinert
push @hidden_vars, qw(invoice_id converted_from_invoice_id converted_from_reclamation_items_id);
f087c373 Jan Büren
}
8f3f4aa6 Jan Büren
if ($is_delivery_order) {
da804bf2 Geoffrey Richardson
map { $form->{"${_}_${i}"} = $form->format_amount(\%myconfig, $form->{"${_}_${i}"}) } qw(sellprice discount lastcost);
eebe8e90 Sven Schöling
push @hidden_vars, grep { defined $form->{"${_}_${i}"} } qw(sellprice discount not_discountable price_factor_id lastcost);
d707f7ac Moritz Bunkus
push @hidden_vars, "stock_${stock_in_out}_sum_qty", "stock_${stock_in_out}";
ac24d564 Jan Büren
push @hidden_vars, qw(delivery_order_items_id converted_from_orderitems_id converted_from_delivery_order_items_id has_sernumber);
d707f7ac Moritz Bunkus
}

91ab1ef6 Sven Schöling
my @HIDDENS = map { value => $_}, (
$cgi->hidden("-name" => "unit_old_$i", "-value" => $form->{"selected_unit_$i"}),
$cgi->hidden("-name" => "price_new_$i", "-value" => $form->format_amount(\%myconfig, $form->{"price_new_$i"})),
8d72d404 Moritz Bunkus
map { ($cgi->hidden("-name" => $_, "-id" => $_, "-value" => $form->{$_})); } map { $_."_$i" }
8f3f4aa6 Jan Büren
(qw(bo price_old id inventory_accno bin partsgroup partnotes active_price_source active_discount_source
ebd668c1 Tamino Steinert
orderer_id
5bc5af9f Geoffrey Richardson
income_accno expense_accno listprice part_type taxaccounts ordnumber donumber transdate cusordnumber
fe6275f8 Niclas Zimmermann
longdescription basefactor marge_absolut marge_percent marge_price_factor weight), @hidden_vars)
91ab1ef6 Sven Schöling
);

map { $form->{"${_}_base"} += $linetotal } (split(/ /, $form->{"taxaccounts_$i"}));

$form->{invsubtotal} += $linetotal;

ef220490 Moritz Bunkus
# Benutzerdefinierte Variablen für Waren/Dienstleistungen/Erzeugnisse
6988b41a Sven Schöling
_render_custom_variables_inputs(ROW2 => \@ROW2, row => $i, part_id => $form->{"id_$i"});
ef220490 Moritz Bunkus
74959706 Sven Schöling
my $colspan = scalar @ROW1;
eebe8e90 Sven Schöling
push @ROWS, { ROW1 => \@ROW1, ROW2 => \@ROW2, HIDDENS => \@HIDDENS, colspan => $colspan, error => $form->{"row_error_$i"}, obj => $record_item };
91ab1ef6 Sven Schöling
}

a7ecfa38 Niclas Zimmermann
$form->{totalweight} = $totalweight;

91ab1ef6 Sven Schöling
print $form->parse_html_template('oe/sales_order', { ROWS => \@ROWS,
HEADER => \@HEADER,
});

76466336 Waldemar Toews
if (abs($form->{sellprice_total} * 1) >= 0.01) {
91ab1ef6 Sven Schöling
$form->{marge_percent} = ($form->{sellprice_total} - $form->{lastcost_total}) / $form->{sellprice_total} * 100;
}

9da3e39b Sven Schöling
$main::lxdebug->leave_sub();
91ab1ef6 Sven Schöling
}
d319704a Moritz Bunkus
fb1da87c Moritz Bunkus
sub setup_io_select_item_action_bar {
my %params = @_;

for my $bar ($::request->layout->get('actionbar')) {
$bar->add(
action => [
t8('Continue'),
submit => [ '#form' ],
accesskey => 'enter',
],
);
}
}

07d71c33 Stephan Köhler
sub select_item {
9da3e39b Sven Schöling
$main::lxdebug->enter_sub();

461b6311 Moritz Bunkus
my %params = @_;
6ea1dd9b Bernd Bleßmann
my $mode = $params{mode} || croak "Missing parameter 'mode'";
my $pre_entered_qty = $params{pre_entered_qty} || 1;
12ce5ee7 Moritz Bunkus
_check_io_auth();
8c7e4493 Moritz Bunkus
fb1da87c Moritz Bunkus
setup_io_select_item_action_bar();

7f1ff6c8 Moritz Bunkus
my $previous_form = $::auth->save_form_in_session(form => $::form);
a14368a2 Martin Helmling
$::form->{title} = $::myconfig{item_multiselect} ?
$::locale->text('Set count for one or more of the items to select them'):
$::locale->text('Select from one of the items below');
461b6311 Moritz Bunkus
$::form->header;
cb253140 Moritz Bunkus
461b6311 Moritz Bunkus
my @item_list = map {
d68f336a Jan Büren
# maybe there is a better backend function or way to calc
$_->{display_sellprice} = ($_->{price_factor}) ? $_->{sellprice} / $_->{price_factor} : $_->{sellprice};
461b6311 Moritz Bunkus
$_;
} @{ $::form->{item_list} };
d319704a Moritz Bunkus
# delete action variable
e66d5e5a Sven Schöling
delete @{$::form}{qw(action item_list)};
d319704a Moritz Bunkus
6ea1dd9b Bernd Bleßmann
print $::form->parse_html_template('io/select_item', { PREVIOUS_FORM => $previous_form,
MODE => $mode,
ITEM_LIST => \@item_list,
IS_ASSEMBLY => $mode eq 'IC',
IS_PURCHASE => $mode eq 'IS',
PRE_ENTERED_QTY => $pre_entered_qty, });
d319704a Moritz Bunkus
9da3e39b Sven Schöling
$main::lxdebug->leave_sub();
d319704a Moritz Bunkus
}

sub item_selected {
fd041aff Geoffrey Richardson
# this function is used for adding parts to records (mode = IR/IS)
# and to assemblies (mode = IC)

9da3e39b Sven Schöling
$main::lxdebug->enter_sub();

my $form = $main::form;
my %myconfig = %main::myconfig;
ef73414c Stephan Köhler
12ce5ee7 Moritz Bunkus
_check_io_auth();
8c7e4493 Moritz Bunkus
cb253140 Moritz Bunkus
$::auth->restore_form_from_session($form->{select_item_previous_form} || croak('Missing previous form ID'), form => $form);
d319704a Moritz Bunkus
6ea1dd9b Bernd Bleßmann
my $mode = delete($form->{select_item_mode}) || croak 'Missing item selection mode';
my $row_key = $mode eq 'IC' ? 'assembly_rows' : 'rowcount';
my $curr_row = $form->{ $row_key };

my $row = $curr_row;

if ($myconfig{item_multiselect}) {
288a0f42 Sven Schöling
my %multi_items;
for (keys %$form) {
6ea1dd9b Bernd Bleßmann
next unless $form->{$_};
288a0f42 Sven Schöling
next unless /^select_qty_(\d+)/;
$multi_items{"id_${row}"} = $1;
$multi_items{"qty_${row}"} = $form->{$_};
6ea1dd9b Bernd Bleßmann
$row++;
}
288a0f42 Sven Schöling
$form->{$_} = $multi_items{$_} for keys %multi_items;
6ea1dd9b Bernd Bleßmann
} else {
$form->{"id_${row}"} = delete($form->{select_item_id}) || croak 'Missing item selection ID';
$row++;
}

map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
2f6636f6 Bernd Bleßmann
qw(sellprice weight);
cb253140 Moritz Bunkus
fd041aff Geoffrey Richardson
if ( $mode eq 'IC' ) {
# assembly mode:
6ea1dd9b Bernd Bleßmann
# the qty variables of the existing assembly items are all still formatted, so we parse them here
# including the qty of the just added part
$form->{"qty_$_"} = $form->parse_amount(\%myconfig, $form->{"qty_$_"}) for (1 .. $row - 1);
} else {
if ($myconfig{item_multiselect}) {
# other modes and multiselection:
# parse all newly entered qtys
$form->{"qty_$_"} = $form->parse_amount(\%myconfig, $form->{"qty_$_"}) for ($curr_row .. $row - 1);
}
644eb8e4 Bernd Bleßmann
}
fd041aff Geoffrey Richardson
6ea1dd9b Bernd Bleßmann
for my $i ($curr_row .. $row - 1) {
$form->{ $row_key } = $i;

my $id = $form->{"id_${i}"};

delete $form->{item_list};
cb253140 Moritz Bunkus
14dca9b8 Bernd Bleßmann
if ($mode eq 'IS') {
IS->retrieve_item(\%myconfig, \%$form);
} elsif ($mode eq 'IR') {
IR->retrieve_item(\%myconfig, \%$form);
} elsif ($mode eq 'IC') {
IC->assembly_item(\%myconfig, \%$form);
} else {
croak "Invalid item selection mode '${mode}'";
}
d319704a Moritz Bunkus
14dca9b8 Bernd Bleßmann
my $new_item = $form->{item_list}->[0] || croak "No item found for mode '${mode}' and ID '${id}'";
07d71c33 Stephan Köhler
14dca9b8 Bernd Bleßmann
# if there was a price entered, override it
my $sellprice;
unless ( $mode eq 'IC' ) {
$sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
};
d319704a Moritz Bunkus
14dca9b8 Bernd Bleßmann
my @new_fields =
qw(id partnumber description sellprice listprice inventory_accno
98b64fe1 Geoffrey Richardson
income_accno expense_accno bin unit weight part_type taxaccounts
14dca9b8 Bernd Bleßmann
partsgroup formel longdescription not_discountable partnotes lastcost
price_factor_id price_factor);
1e251313 Moritz Bunkus
14dca9b8 Bernd Bleßmann
my $ic_cvar_configs = CVar->get_configs(module => 'IC');
push @new_fields, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
ef220490 Moritz Bunkus
14dca9b8 Bernd Bleßmann
map { $form->{"${_}_$i"} = $new_item->{$_} } @new_fields;
1e251313 Moritz Bunkus
14dca9b8 Bernd Bleßmann
if (my $record = _make_record()) {
my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
my $best_price = $price_source->best_price;
df1b03d5 Sven Schöling
14dca9b8 Bernd Bleßmann
if ($best_price) {
$::form->{"sellprice_$i"} = $best_price->price;
$::form->{"active_price_source_$i"} = $best_price->source;
}
df1b03d5 Sven Schöling
14dca9b8 Bernd Bleßmann
my $best_discount = $price_source->best_discount;
89b26688 Sven Schöling
14dca9b8 Bernd Bleßmann
if ($best_discount) {
$::form->{"discount_$i"} = $best_discount->discount;
$::form->{"active_discount_source_$i"} = $best_discount->source;
}
c14eb2d1 Sven Schöling
}
89b26688 Sven Schöling
14dca9b8 Bernd Bleßmann
$form->{"marge_price_factor_$i"} = $new_item->{price_factor};
1e251313 Moritz Bunkus
14dca9b8 Bernd Bleßmann
if ($form->{"part_payment_id_$i"} ne "") {
$form->{payment_id} = $form->{"part_payment_id_$i"};
}
d319704a Moritz Bunkus
14dca9b8 Bernd Bleßmann
my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
$dec = length $dec;
my $decimalplaces = ($dec > 2) ? $dec : 2;
d319704a Moritz Bunkus
14dca9b8 Bernd Bleßmann
if ($sellprice) {
$form->{"sellprice_$i"} = $sellprice;
} else {
d319704a Moritz Bunkus
14dca9b8 Bernd Bleßmann
# if there is an exchange rate adjust sellprice
if (($form->{exchangerate} * 1) != 0) {
$form->{"sellprice_$i"} /= $form->{exchangerate};
$form->{"sellprice_$i"} =
$form->round_amount($form->{"sellprice_$i"}, $decimalplaces);
}
d319704a Moritz Bunkus
}

14dca9b8 Bernd Bleßmann
# at this stage qty of newly added part needs to be have been parsed
$form->{weight} += ($form->{"weight_$i"} * $form->{"qty_$i"});
6ac037ce Sven Schöling
14dca9b8 Bernd Bleßmann
if ($form->{"not_discountable_$i"}) {
$form->{"discount_$i"} = 0;
}
d319704a Moritz Bunkus
14dca9b8 Bernd Bleßmann
my $amount =
$form->{"sellprice_$i"} * (1 - $form->{"discount_$i"}) * $form->{"qty_$i"};
map { $form->{"${_}_base"} += $amount } (split / /, $form->{"taxaccounts_$i"});
map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
d319704a Moritz Bunkus
14dca9b8 Bernd Bleßmann
$form->{creditremaining} -= $amount;
$form->{"runningnumber_$i"} = $i;
d319704a Moritz Bunkus
14dca9b8 Bernd Bleßmann
# format amounts
map {
$form->{"${_}_$i"} =
$form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces)
f5abed86 Geoffrey Richardson
} qw(sellprice lastcost qty) if $form->{part_type} ne 'assembly';
$form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0) if $form->{part_type} ne 'assembly';
d319704a Moritz Bunkus
14dca9b8 Bernd Bleßmann
delete $form->{nextsub};
6ea1dd9b Bernd Bleßmann
}

d319704a Moritz Bunkus
&display_form;

9da3e39b Sven Schöling
$main::lxdebug->leave_sub();
d319704a Moritz Bunkus
}

sub new_item {
9c76baca Sven Schöling
_check_io_auth();
9da3e39b Sven Schöling
9c76baca Sven Schöling
my $price = $::form->{vc} eq 'customer' ? 'sellprice_as_number' : 'lastcost_as_number';
my $previousform = $::auth->save_form_in_session;
my $callback = build_std_url("action=return_from_new_item", "previousform=$previousform");
my $i = $::form->{rowcount};
d319704a Moritz Bunkus
ce904bd6 Geoffrey Richardson
my $parts_classification_type = $::form->{vc} eq 'customer' ? 'sales' : 'purchases';

9c76baca Sven Schöling
my @HIDDENS;
push @HIDDENS, { 'name' => 'callback', 'value' => $callback };
push @HIDDENS, map +{ 'name' => $_, 'value' => $::form->{$_} }, qw(rowcount vc);
push @HIDDENS, map +{ 'name' => "part.$_", 'value' => $::form->{"${_}_$i"} }, qw(partnumber description unit price_factor_id);
push @HIDDENS, { 'name' => "part.$price", 'value' => $::form->{"sellprice_$i"} };
push @HIDDENS, { 'name' => "part.notes", 'value' => $::form->{"longdescription_$i"} };
8c7e4493 Moritz Bunkus
ce904bd6 Geoffrey Richardson
push @HIDDENS, { 'name' => "parts_classification_type", 'value' => $parts_classification_type };

9c76baca Sven Schöling
$::form->header;
print $::form->parse_html_template("generic/new_item", { HIDDENS => [ sort { $a->{name} cmp $b->{name} } @HIDDENS ] } );
}
77903c6c Moritz Bunkus
9c76baca Sven Schöling
sub return_from_new_item {
_check_io_auth();
d319704a Moritz Bunkus
9c76baca Sven Schöling
my $part = SL::DB::Manager::Part->find_by(id => delete $::form->{new_parts_id}) or die 'can not find part that was just saved!';
d319704a Moritz Bunkus
9c76baca Sven Schöling
$::auth->restore_form_from_session(delete $::form->{previousform}, form => $::form);
d319704a Moritz Bunkus
9c76baca Sven Schöling
$::form->{"id_$::form->{rowcount}"} = $part->id;
d319704a Moritz Bunkus
9c76baca Sven Schöling
my $url = build_std_url("script=$::form->{script}", "RESTORE_FORM_FROM_SESSION_ID=" . $::auth->save_form_in_session);
print $::request->{cgi}->redirect($url);
d319704a Moritz Bunkus
}

sub check_form {
9da3e39b Sven Schöling
$main::lxdebug->enter_sub();

my $form = $main::form;
my %myconfig = %main::myconfig;
8c7e4493 Moritz Bunkus
12ce5ee7 Moritz Bunkus
_check_io_auth();
8c7e4493 Moritz Bunkus
d319704a Moritz Bunkus
my @a = ();
my $count = 0;
8c7e4493 Moritz Bunkus
d319704a Moritz Bunkus
# remove any makes or model rows
f5abed86 Geoffrey Richardson
if ($form->{part_type} eq 'assembly') {
d319704a Moritz Bunkus
ca48cabb Geoffrey Richardson
# fuer assemblies auskommentiert. seiteneffekte? ;-) wird die woanders benoetigt?
#$form->{sellprice} = 0;
d319704a Moritz Bunkus
$form->{weight} = 0;
map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
2f6636f6 Bernd Bleßmann
qw(sellprice rop stock);
d319704a Moritz Bunkus
ef220490 Moritz Bunkus
my @flds = qw(id qty unit bom partnumber description sellprice weight runningnumber partsgroup lastcost);
d319704a Moritz Bunkus
for my $i (1 .. ($form->{assembly_rows} - 1)) {
if ($form->{"qty_$i"}) {
push @a, {};
my $j = $#a;

$form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});

map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;

07d71c33 Stephan Köhler
#($form->{"sellprice_$i"},$form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};

ca48cabb Geoffrey Richardson
# fuer assemblies auskommentiert. siehe oben
b65a230d Sven Schöling
# $form->{sellprice} += ($form->{"qty_$i"} * $form->{"sellprice_$i"} / ($form->{"price_factor_$i"} || 1));
bfa7bf60 Sven Schöling
$form->{weight} += ($form->{"qty_$i"} * $form->{"weight_$i"} / ($form->{"price_factor_$i"} || 1));
d319704a Moritz Bunkus
$count++;
}
}
ca48cabb Geoffrey Richardson
# kann das hier auch weg? s.o. jb
d319704a Moritz Bunkus
$form->{sellprice} = $form->round_amount($form->{sellprice}, 2);

$form->redo_rows(\@flds, \@a, $count, $form->{assembly_rows});
$form->{assembly_rows} = $count;

f5abed86 Geoffrey Richardson
} elsif ($form->{part_type} !~ m{^(?:part|service)$}) {
0a5317e7 Moritz Bunkus
remove_emptied_rows(1);
d319704a Moritz Bunkus
0a5317e7 Moritz Bunkus
$form->{creditremaining} -= &invoicetotal;
d319704a Moritz Bunkus
}
ef73414c Stephan Köhler
d319704a Moritz Bunkus
&display_form;

9da3e39b Sven Schöling
$main::lxdebug->leave_sub();
d319704a Moritz Bunkus
}

0a5317e7 Moritz Bunkus
sub remove_emptied_rows {
my $dont_add_empty = shift;
my $form = $::form;

return unless $form->{rowcount};

my @flds = qw(id partnumber description qty ship sellprice unit
discount inventory_accno income_accno expense_accno listprice
taxaccounts bin assembly weight projectnumber project_id
oldprojectnumber runningnumber serialnumber partsgroup payment_id
not_discountable shop ve gv buchungsgruppen_id language_values
eebe8e90 Sven Schöling
price_old price_new unit_old ordnumber donumber
0a5317e7 Moritz Bunkus
transdate longdescription basefactor marge_total marge_percent
marge_price_factor lastcost price_factor_id partnotes
049e49fe Sven Schöling
stock_out stock_in has_sernumber reqdate orderitems_id
8f3f4aa6 Jan Büren
active_price_source active_discount_source delivery_order_items_id
2f9a5220 Jan Büren
invoice_id converted_from_orderitems_id
748ce36f Tamino Steinert
converted_from_delivery_order_items_id converted_from_invoice_id
7df596f9 Tamino Steinert
converted_from_reclamation_items_id recurring_billing_mode
608ac7e2 Moritz Bunkus
expense_chart_id inventory_chart_id tax_id tax_chart_type subtotal
7df596f9 Tamino Steinert
);
0a5317e7 Moritz Bunkus
my $ic_cvar_configs = CVar->get_configs(module => 'IC');
push @flds, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };

my @new_rows;
for my $i (1 .. $form->{rowcount} - 1) {
next unless $form->{"partnumber_$i"};

push @new_rows, { map { $_ => $form->{"${_}_$i" } } @flds };
}

my $new_rowcount = scalar @new_rows;
$form->redo_rows(\@flds, \@new_rows, $new_rowcount, $form->{rowcount});
$form->{rowcount} = $new_rowcount + ($dont_add_empty ? 0 : 1);
}

d319704a Moritz Bunkus
sub invoicetotal {
9da3e39b Sven Schöling
$main::lxdebug->enter_sub();

my $form = $main::form;
my %myconfig = %main::myconfig;
d319704a Moritz Bunkus
12ce5ee7 Moritz Bunkus
_check_io_auth();
8c7e4493 Moritz Bunkus
d319704a Moritz Bunkus
$form->{oldinvtotal} = 0;

# add all parts and deduct paid
map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};

my ($amount, $sellprice, $discount, $qty);

for my $i (1 .. $form->{rowcount}) {
$sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
$discount = $form->parse_amount(\%myconfig, $form->{"discount_$i"});
$qty = $form->parse_amount(\%myconfig, $form->{"qty_$i"});

07d71c33 Stephan Köhler
#($form->{"sellprice_$i"}, $form->{"$pricegroup_old_$i"}) = split /--/, $form->{"sellprice_$i"};

d319704a Moritz Bunkus
$amount = $sellprice * (1 - $discount / 100) * $qty;
map { $form->{"${_}_base"} += $amount }
2b89ec97 Thomas Kasulke
(split (/ /, $form->{"taxaccounts_$i"}));
d319704a Moritz Bunkus
$form->{oldinvtotal} += $amount;
}

map { $form->{oldinvtotal} += ($form->{"${_}_base"} * $form->{"${_}_rate"}) }
2b89ec97 Thomas Kasulke
split(/ /, $form->{taxaccounts})
d319704a Moritz Bunkus
if !$form->{taxincluded};

$form->{oldtotalpaid} = 0;
9da3e39b Sven Schöling
for my $i (1 .. $form->{paidaccounts}) {
d319704a Moritz Bunkus
$form->{oldtotalpaid} += $form->{"paid_$i"};
}

9da3e39b Sven Schöling
$main::lxdebug->leave_sub();
d319704a Moritz Bunkus
# return total
return ($form->{oldinvtotal} - $form->{oldtotalpaid});
}

sub validate_items {
9da3e39b Sven Schöling
$main::lxdebug->enter_sub();

my $form = $main::form;
my $locale = $main::locale;
ef73414c Stephan Köhler
12ce5ee7 Moritz Bunkus
_check_io_auth();
8c7e4493 Moritz Bunkus
d319704a Moritz Bunkus
# check if items are valid
8750748a Thomas Kasulke
if ($form->{rowcount} == 1) {
d638ae94 Moritz Bunkus
flash('warning', $::locale->text('The action you\'ve chosen has not been executed because the document does not contain any item yet.'));
d319704a Moritz Bunkus
&update;
09479f02 Moritz Bunkus
$::dispatcher->end_request;
d319704a Moritz Bunkus
}

9da3e39b Sven Schöling
for my $i (1 .. $form->{rowcount} - 1) {
d319704a Moritz Bunkus
$form->isblank("partnumber_$i",
$locale->text('Number missing in Row') . " $i");
}

9da3e39b Sven Schöling
$main::lxdebug->leave_sub();
d319704a Moritz Bunkus
}

sub order {
9da3e39b Sven Schöling
$main::lxdebug->enter_sub();

505f6be3 Tamino Steinert
$::form->{email_journal_id} = delete $::form->{workflow_email_journal_id};
$::form->{email_attachment_id} = delete $::form->{workflow_email_attachment_id};
e68a2521 Tamino Steinert
$::form->{callback} = delete $::form->{workflow_email_callback};
505f6be3 Tamino Steinert
9aa58dc1 Bernd Bleßmann
_order();

5f4faab9 Niklas Schmidt
# At this point, the record is saved and the exchangerate contains
# an unformatted value. _make_record uses RDBO attributes (i.e. _as_number)
# to assign values and thus expects an formatted value.
$::form->{exchangerate} = $::form->format_amount(\%::myconfig, $::form->{exchangerate});

my $order = _make_record();

$order->currency(SL::DB::Currency->new(name => $::form->{currency})->load) if $::form->{currency};
$order->globalproject_id(undef) if !$order->globalproject_id;
$order->payment_id(undef) if !$order->payment_id;

my $row = 1;
foreach my $item (@{$order->items_sorted}) {
$item->custom_variables([]);

$item->price_factor_id(undef) if !$item->price_factor_id;
$item->project_id(undef) if !$item->project_id;

# autovivify all cvars that are not in the form (cvars_by_config can do it).
# workaround to pre-parse number-cvars (parse_custom_variable_values does not parse number values).
foreach my $var (@{ $item->cvars_by_config }) {
my $key = 'ic_cvar_' . $var->config->name . '_' . $row;
$var->unparsed_value($::form->{$key});
$var->unparsed_value($::form->parse_amount(\%::myconfig, $var->{__unparsed_value})) if ($var->config->type eq 'number' && exists($var->{__unparsed_value}));
9aa58dc1 Bernd Bleßmann
}
5f4faab9 Niklas Schmidt
$item->parse_custom_variable_values;
9aa58dc1 Bernd Bleßmann
5f4faab9 Niklas Schmidt
$row++;
9aa58dc1 Bernd Bleßmann
}

5f4faab9 Niklas Schmidt
require SL::Controller::Order;
my $c = SL::Controller::Order->new(order => $order);
$c->reinit_after_new_order();
$c->action_add();

$main::lxdebug->leave_sub();
$::dispatcher->end_request;

9aa58dc1 Bernd Bleßmann
&display_form;

$main::lxdebug->leave_sub();
}

sub _order {
9da3e39b Sven Schöling
my $form = $main::form;
my %myconfig = %main::myconfig;
my $locale = $main::locale;
8c7e4493 Moritz Bunkus
12ce5ee7 Moritz Bunkus
_check_io_auth();
8c7e4493 Moritz Bunkus
07d71c33 Stephan Köhler
if ($form->{second_run}) {
$form->{print_and_post} = 0;
}
d319704a Moritz Bunkus
$form->{ordnumber} = $form->{invnumber};

d6bf475a Moritz Bunkus
$form->{old_employee_id} = $form->{employee_id};
$form->{old_salesman_id} = $form->{salesman_id};

b535245e Jan Büren
delete $form->{$_} foreach (qw(id printed emailed queued));
c2688215 Geoffrey Richardson
# When creating a new sales order from a saved sales invoice, reset id,
# ordnumber, transdate and deliverydate as we are creating a new order. This
# workflow is probably mainly used as a template mechanism for creating new
# orders from existing invoices, so we probably don't want to link the items.
# Is this order function called anywhere else?
# The worksflows in oe already call sales_order and purchase_order in oe, not
# this general function which now only seems to be called from saved sales
# invoices
# Why is ordnumber set to invnumber above, does this ever make sense?

if ( $form->{script} eq 'is.pl' && $form->{type} eq 'invoice' ) {
delete $form->{$_} foreach (qw(ordnumber id transdate deliverydate));
};

9da3e39b Sven Schöling
my $buysell;
d319704a Moritz Bunkus
if ($form->{script} eq 'ir.pl' || $form->{type} eq 'request_quotation') {
$form->{title} = $locale->text('Add Purchase Order');
$form->{vc} = 'vendor';
$form->{type} = 'purchase_order';
$buysell = 'sell';
}
if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_quotation') {
$form->{title} = $locale->text('Add Sales Order');
$form->{vc} = 'customer';
$form->{type} = 'sales_order';
$buysell = 'buy';
}
$form->{script} = 'oe.pl';

$form->{rowcount}--;

$form->{cp_id} *= 1;

d629acd8 Sven Schöling
require "bin/mozilla/$form->{script}";
ac23cb3b Moritz Bunkus
my $script = $form->{"script"};
$script =~ s|.*/||;
$script =~ s|.pl$||;
c607fb40 Sven Schöling
$locale = Locale->new($::lx_office_conf{system}->{language}, $script);
d319704a Moritz Bunkus
5114d0d5 Sven Schöling
map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
d319704a Moritz Bunkus
9da3e39b Sven Schöling
my $currency = $form->{currency};
d319704a Moritz Bunkus
&order_links;

$form->{currency} = $currency;
a53233e5 Sven Schöling
$form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{transdate}, $buysell);
$form->{exchangerate} = $form->{forex} || '';
d319704a Moritz Bunkus
9da3e39b Sven Schöling
for my $i (1 .. $form->{rowcount}) {
a53233e5 Sven Schöling
map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig, $form->{"${_}_${i}"})
57fae76e Moritz Bunkus
if ($form->{"${_}_${i}"}) }
2f6636f6 Bernd Bleßmann
qw(ship qty sellprice basefactor discount));
991d16bb Jan Büren
$form->{"converted_from_invoice_id_$i"} = delete $form->{"invoice_id_$i"};
57fae76e Moritz Bunkus
}

d319704a Moritz Bunkus
&prepare_order;
}

sub quotation {
9da3e39b Sven Schöling
$main::lxdebug->enter_sub();

my $form = $main::form;
my %myconfig = %main::myconfig;
my $locale = $main::locale;
8c7e4493 Moritz Bunkus
12ce5ee7 Moritz Bunkus
_check_io_auth();
8c7e4493 Moritz Bunkus
02022dc2 Jan Büren
# we are coming from *_order and convert to quotation
# it seems that quotation is only called if we have a existing order
if ($form->{type} =~ /(sales|purchase)_order/) {
991d16bb Jan Büren
$form->{"converted_from_orderitems_id_$_"} = delete $form->{"orderitems_id_$_"} for 1 .. $form->{"rowcount"};
02022dc2 Jan Büren
}
07d71c33 Stephan Köhler
if ($form->{second_run}) {
$form->{print_and_post} = 0;
}
5b69ef31 Jan Büren
delete $form->{$_} foreach (qw(id printed emailed queued quonumber transaction_description));
d319704a Moritz Bunkus
9da3e39b Sven Schöling
my $buysell;
d319704a Moritz Bunkus
if ($form->{script} eq 'ir.pl' || $form->{type} eq 'purchase_order') {
$form->{title} = $locale->text('Add Request for Quotation');
$form->{vc} = 'vendor';
$form->{type} = 'request_quotation';
$buysell = 'sell';
}
if ($form->{script} eq 'is.pl' || $form->{type} eq 'sales_order') {
$form->{title} = $locale->text('Add Quotation');
$form->{vc} = 'customer';
$form->{type} = 'sales_quotation';
$buysell = 'buy';
}

$form->{cp_id} *= 1;

$form->{script} = 'oe.pl';

$form->{rowcount}--;

d629acd8 Sven Schöling
require "bin/mozilla/$form->{script}";
d319704a Moritz Bunkus
5fc3e9ba Sven Schöling
map { $form->{"select$_"} = "" } ($form->{vc}, "currency");
d319704a Moritz Bunkus
9da3e39b Sven Schöling
my $currency = $form->{currency};
d319704a Moritz Bunkus
&order_links;

$form->{currency} = $currency;
a53233e5 Sven Schöling
$form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, $buysell);
$form->{exchangerate} = $form->{forex} || '';
d319704a Moritz Bunkus
9da3e39b Sven Schöling
for my $i (1 .. $form->{rowcount}) {
57fae76e Moritz Bunkus
map({ $form->{"${_}_${i}"} = $form->parse_amount(\%myconfig,
$form->{"${_}_${i}"})
if ($form->{"${_}_${i}"}) }
2f6636f6 Bernd Bleßmann
qw(ship qty sellprice basefactor discount lastcost));
57fae76e Moritz Bunkus
}

d319704a Moritz Bunkus
&prepare_order;
&display_form;

9da3e39b Sven Schöling
$main::lxdebug->leave_sub();
d319704a Moritz Bunkus
}

0ba6b37c Moritz Bunkus
sub request_for_quotation {
quotation();
}

fab2b3f1 Tamino Steinert
sub sales_reclamation {
my $id = $::form->{id};
4cff1777 Tamino Steinert
my $type = $::form->{type};
fab2b3f1 Tamino Steinert
require SL::Controller::Reclamation;
my $c = SL::Controller::Reclamation->new();
$c->redirect_to(
controller => 'Reclamation',
4cff1777 Tamino Steinert
action => 'add_from_record',
type => 'sales_reclamation',
505f6be3 Tamino Steinert
email_journal_id => $::form->{workflow_email_journal_id},
email_attachment_id => $::form->{workflow_email_attachment_id},
e68a2521 Tamino Steinert
callback => $::form->{workflow_email_callback},
4cff1777 Tamino Steinert
from_id => $id,
from_type => $type,
fab2b3f1 Tamino Steinert
);
}

sub purchase_reclamation {
my $id = $::form->{id};
4cff1777 Tamino Steinert
my $type = $::form->{type};
fab2b3f1 Tamino Steinert
require SL::Controller::Reclamation;
my $c = SL::Controller::Reclamation->new();
$c->redirect_to(
controller => 'Reclamation',
4cff1777 Tamino Steinert
action => 'add_from_record',
type => 'purchase_reclamation',
505f6be3 Tamino Steinert
email_journal_id => $::form->{workflow_email_journal_id},
email_attachment_id => $::form->{workflow_email_attachment_id},
e68a2521 Tamino Steinert
callback => $::form->{workflow_email_callback},
4cff1777 Tamino Steinert
from_id => $id,
from_type => $type,
fab2b3f1 Tamino Steinert
);
}

69ad8bec Thomas Kasulke
sub print_options {
2500bc30 Bernd Bleßmann
$::lxdebug->enter_sub();
9da3e39b Sven Schöling
2500bc30 Bernd Bleßmann
my (%options) = @_;
a4f92ff1 Moritz Bunkus
12ce5ee7 Moritz Bunkus
_check_io_auth();
8c7e4493 Moritz Bunkus
2500bc30 Bernd Bleßmann
my $inline = delete $options{inline};
a4f92ff1 Moritz Bunkus
2500bc30 Bernd Bleßmann
require SL::Helper::PrintOptions;
my $print_options = SL::Helper::PrintOptions->get_print_options(
form => $::form,
myconfig => \%::myconfig,
locale => $::locale,
options => \%options);
69ad8bec Thomas Kasulke
2500bc30 Bernd Bleßmann
if ($inline) {
$::lxdebug->leave_sub();
1adc3d65 Moritz Bunkus
return $print_options;
69ad8bec Thomas Kasulke
}
1adc3d65 Moritz Bunkus
print $print_options;
2500bc30 Bernd Bleßmann
$::lxdebug->leave_sub();
69ad8bec Thomas Kasulke
}

2500bc30 Bernd Bleßmann
69ad8bec Thomas Kasulke
sub print {
9da3e39b Sven Schöling
$main::lxdebug->enter_sub();

my $form = $main::form;
my $locale = $main::locale;
69ad8bec Thomas Kasulke
12ce5ee7 Moritz Bunkus
_check_io_auth();
8c7e4493 Moritz Bunkus
232a9153 Moritz Bunkus
if ($form->{print_nextsub}) {
call_sub($form->{print_nextsub});
9da3e39b Sven Schöling
$main::lxdebug->leave_sub();
232a9153 Moritz Bunkus
return;
}

69ad8bec Thomas Kasulke
# if this goes to the printer pass through
9da3e39b Sven Schöling
my $old_form;
69ad8bec Thomas Kasulke
if ($form->{media} eq 'printer' || $form->{media} eq 'queue') {
$form->error($locale->text('Select postscript or PDF!'))
if ($form->{format} !~ /(postscript|pdf)/);

c607fb40 Sven Schöling
$old_form = Form->new;
69ad8bec Thomas Kasulke
map { $old_form->{$_} = $form->{$_} } keys %$form;
}

if (!$form->{id} || (($form->{formname} eq "proforma") && !$form->{proforma} && (($form->{type} =~ /_order$/) || ($form->{type} =~ /_quotation$/)))) {
if ($form->{formname} eq "proforma") {
$form->{proforma} = 1;
}
$form->{print_and_save} = 1;
my $formname = $form->{formname};
33dc2fcd Jan Büren
&save();
69ad8bec Thomas Kasulke
$form->{formname} = $formname;
33dc2fcd Jan Büren
&edit();
25652024 Moritz Bunkus
$::lxdebug->leave_sub();
09479f02 Moritz Bunkus
$::dispatcher->end_request;
69ad8bec Thomas Kasulke
}

&print_form($old_form);

9da3e39b Sven Schöling
$main::lxdebug->leave_sub();
69ad8bec Thomas Kasulke
}

sub print_form {
9da3e39b Sven Schöling
$main::lxdebug->enter_sub();

my $form = $main::form;
my %myconfig = %main::myconfig;
my $locale = $main::locale;
8c7e4493 Moritz Bunkus
12ce5ee7 Moritz Bunkus
_check_io_auth();
8c7e4493 Moritz Bunkus
2e66dde5 Moritz Bunkus
my $defaults = SL::DB::Default->get;
$form->error($::locale->text('No print templates have been created for this client yet. Please do so in the client configuration.')) if !$defaults->templates;
$form->{templates} = $defaults->templates;

663a3643 Sven Schöling
my ($old_form, %params) = @_;
69ad8bec Thomas Kasulke
9da3e39b Sven Schöling
my $inv = "inv";
my $due = "due";
my $numberfld = "invnumber";
my $order;
69ad8bec Thomas Kasulke
9da3e39b Sven Schöling
my $display_form =
69ad8bec Thomas Kasulke
($form->{display_form}) ? $form->{display_form} : "display_form";

# $form->{"notes"} will be overridden by the customer's/vendor's "notes" field. So save it here.
$form->{ $form->{"formname"} . "notes" } = $form->{"notes"};

if ($form->{formname} eq "invoice") {
$form->{label} = $locale->text('Invoice');
}
726a9fae Bernd Bleßmann
if ($form->{formname} eq "invoice_for_advance_payment") {
$form->{label} = $locale->text('Invoice for Advance Payment');
}

475b7a3f Bernd Bleßmann
if ($form->{formname} eq "final_invoice") {
$form->{label} = $locale->text('Final Invoice');
}

69ad8bec Thomas Kasulke
if ($form->{formname} eq 'sales_order') {
$inv = "ord";
$due = "req";
$form->{"${inv}date"} = $form->{transdate};
299606e3 Moritz Bunkus
$form->{label} = $locale->text('Confirmation');
69ad8bec Thomas Kasulke
$numberfld = "sonumber";
$order = 1;
}

if (($form->{type} eq 'invoice') && ($form->{formname} eq 'proforma') ) {
$inv = "inv";
$due = "due";
$form->{"${inv}date"} = $form->{invdate};
$form->{label} = $locale->text('Proforma Invoice');
$numberfld = "sonumber";
$order = 0;
}

if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'proforma') ) {
$inv = "inv";
$due = "due";
$form->{"${inv}date"} = $form->{transdate};
$form->{"invdate"} = $form->{transdate};
$form->{invnumber} = $form->{ordnumber};
$form->{label} = $locale->text('Proforma Invoice');
$numberfld = "sonumber";
$order = 1;
}

if ($form->{formname} eq 'purchase_order') {
$inv = "ord";
$due = "req";
$form->{"${inv}date"} = $form->{transdate};
$form->{label} = $locale->text('Purchase Order');
$numberfld = "ponumber";
$order = 1;
}
if ($form->{formname} eq 'bin_list') {
$inv = "ord";
$due = "req";
$form->{"${inv}date"} = $form->{transdate};
$form->{label} = $locale->text('Bin List');
$order = 1;
}
if ($form->{formname} eq 'sales_quotation') {
$inv = "quo";
$due = "req";
$form->{"${inv}date"} = $form->{transdate};
$form->{label} = $locale->text('Quotation');
$numberfld = "sqnumber";
$order = 1;
}

if (($form->{type} eq 'sales_quotation') && ($form->{formname} eq 'proforma') ) {
$inv = "quo";
$due = "req";
$form->{"${inv}date"} = $form->{transdate};
$form->{"invdate"} = $form->{transdate};
$form->{label} = $locale->text('Proforma Invoice');
$numberfld = "sqnumber";
$order = 1;
}

32421f9a Jan Büren
if (($form->{type} eq 'sales_order') && ($form->{formname} eq 'ic_supply') ) {
$inv = "inv";
$due = "due";
$form->{"${inv}date"} = $form->{transdate};
$form->{"invdate"} = $form->{transdate};
$form->{invnumber} = $form->{ordnumber};
$form->{label} = $locale->text('Intra-Community supply');
$numberfld = "sonumber";
$order = 1;
}

69ad8bec Thomas Kasulke
if ($form->{formname} eq 'request_quotation') {
$inv = "quo";
$due = "req";
$form->{"${inv}date"} = $form->{transdate};
299606e3 Moritz Bunkus
$form->{label} = $locale->text('RFQ');
69ad8bec Thomas Kasulke
$numberfld = "rfqnumber";
$order = 1;
}

d707f7ac Moritz Bunkus
if ($form->{type} =~ /_delivery_order$/) {
undef $due;
$inv = "do";
$form->{"${inv}date"} = $form->{transdate};
$numberfld = $form->{type} =~ /^sales/ ? 'sdonumber' : 'pdonumber';
$form->{label} = $form->{formname} eq 'pick_list' ? $locale->text('Pick List') : $locale->text('Delivery Order');
}
faea2c48 Jan Büren
if ($form->{type} =~ /letter/) {
undef $due;
undef $inv;
$form->{label} = $locale->text('Letter');
}
d707f7ac Moritz Bunkus
3b32e1dd Moritz Bunkus
$form->{TEMPLATE_DRIVER_OPTIONS} = { };
475b7a3f Bernd Bleßmann
if (any { $form->{type} eq $_ } qw(sales_quotation sales_order sales_delivery_order invoice invoice_for_advance_payment final_invoice request_quotation purchase_order purchase_delivery_order credit_note)) {
54ce5144 Martin Helmling
$form->{TEMPLATE_DRIVER_OPTIONS}->{variable_content_types} = $form->get_variable_content_types();
3b32e1dd Moritz Bunkus
}

cf0455f5 Moritz Bunkus
if ($form->{format} =~ m{pdf}) {
_maybe_attach_zugferd_data($form);
}

69ad8bec Thomas Kasulke
$form->isblank("email", $locale->text('E-mail address missing!'))
if ($form->{media} eq 'email');
$form->isblank("${inv}date",
6ac037ce Sven Schöling
$locale->text($form->{label})
69ad8bec Thomas Kasulke
. ": "
. $locale->text(' Date missing!'));

# $locale->text('Invoice Number missing!')
# $locale->text('Invoice Date missing!')
# $locale->text('Order Number missing!')
# $locale->text('Order Date missing!')
# $locale->text('Quotation Number missing!')
# $locale->text('Quotation Date missing!')

$form->{what_done} = $form->{formname};

&validate_items;

# Save the email address given in the form because it should override the setting saved for the customer/vendor.
my ($saved_email, $saved_cc, $saved_bcc) =
($form->{"email"}, $form->{"cc"}, $form->{"bcc"});

9da3e39b Sven Schöling
my $language_saved = $form->{language_id};
my $payment_id_saved = $form->{payment_id};
03d3d025 Bernd Bleßmann
my $delivery_term_id_saved = $form->{delivery_term_id};
9da3e39b Sven Schöling
my $salesman_id_saved = $form->{salesman_id};
my $cp_id_saved = $form->{cp_id};
9c228f16 Bernd Bleßmann
my $taxzone_id_saved = $form->{taxzone_id};
94802c79 Bernd Bleßmann
my $currency_saved = $form->{currency};
69ad8bec Thomas Kasulke
8c7e4493 Moritz Bunkus
call_sub("$form->{vc}_details") if ($form->{vc});
69ad8bec Thomas Kasulke
$form->{language_id} = $language_saved;
$form->{payment_id} = $payment_id_saved;
03d3d025 Bernd Bleßmann
$form->{delivery_term_id} = $delivery_term_id_saved;
9c228f16 Bernd Bleßmann
$form->{taxzone_id} = $taxzone_id_saved;
94802c79 Bernd Bleßmann
$form->{currency} = $currency_saved;
69ad8bec Thomas Kasulke
$form->{"email"} = $saved_email if ($saved_email);
$form->{"cc"} = $saved_cc if ($saved_cc);
$form->{"bcc"} = $saved_bcc if ($saved_bcc);

9caaa245 Moritz Bunkus
if (!$cp_id_saved) {
# No contact was selected. Delete all contact variables because
# IS->customer_details() and IR->vendor_details() get the default
# contact anyway.
map({ delete($form->{$_}); } grep(/^cp_/, keys(%{ $form })));
}

69ad8bec Thomas Kasulke
my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
if ($form->{"language_id"}) {
($language_tc, $output_numberformat, $output_dateformat, $output_longdates) =
AM->get_language_details(\%myconfig, $form, $form->{language_id});
} else {
$output_dateformat = $myconfig{"dateformat"};
$output_numberformat = $myconfig{"numberformat"};
$output_longdates = 1;
}

ac9bfb42 Moritz Bunkus
# Store the output number format so that the template modules know
# how to parse the amounts back if requested.
588aa1eb Moritz Bunkus
$myconfig{output_numberformat} = $output_numberformat || $myconfig{numberformat};
ac9bfb42 Moritz Bunkus
69ad8bec Thomas Kasulke
($form->{employee}) = split /--/, $form->{employee};

# create the form variables
690a3bac Moritz Bunkus
if ($form->{type} =~ /_delivery_order$/) {
c5651754 Bernd Bleßmann
DO->order_details(\%myconfig, \%$form);
8c7e4493 Moritz Bunkus
} elsif ($order) {
69ad8bec Thomas Kasulke
OE->order_details(\%myconfig, \%$form);
faea2c48 Jan Büren
} elsif ($form->{type} eq 'letter') {
# right now, no details are needed
# but i do not want to break the bad default (invoice)
69ad8bec Thomas Kasulke
} else {
IS->invoice_details(\%myconfig, \%$form, $locale);
}

6c56877d Moritz Bunkus
$form->get_employee_data('prefix' => 'employee', 'id' => $form->{employee_id});
$form->get_employee_data('prefix' => 'salesman', 'id' => $salesman_id_saved);
afe8a81b Moritz Bunkus
69ad8bec Thomas Kasulke
if ($form->{shipto_id}) {
$form->get_shipto(\%myconfig);
}

00177fae Moritz Bunkus
$form->set_addition_billing_address_print_variables;

69ad8bec Thomas Kasulke
$form->{notes} =~ s/^\s+//g;

e1e19a48 Moritz Bunkus
delete $form->{printer_command};

69ad8bec Thomas Kasulke
$form->{language} = $form->get_template_language(\%myconfig);
7dfa1c0a Moritz Bunkus
my $printer_code;
if ($form->{media} ne 'email') {
$printer_code = $form->get_printer_code(\%myconfig);
if ($printer_code ne "") {
$printer_code = "_" . $printer_code;
}
}
69ad8bec Thomas Kasulke
if ($form->{language} ne "") {
d7558f2b Moritz Bunkus
my $template_arrays = $form->{TEMPLATE_ARRAYS} || $form;
map { $template_arrays->{unit}->[$_] = AM->translate_units($form, $form->{language}, $template_arrays->{unit}->[$_], $template_arrays->{qty}->[$_]); } (0..scalar(@{ $template_arrays->{unit} }) - 1);

69ad8bec Thomas Kasulke
$form->{language} = "_" . $form->{language};
}

d707f7ac Moritz Bunkus
# Format dates.
69ad8bec Thomas Kasulke
format_dates($output_dateformat, $output_longdates,
0b36b225 Moritz Bunkus
qw(invdate orddate quodate pldate duedate reqdate transdate tax_point
69ad8bec Thomas Kasulke
shippingdate deliverydate validitydate paymentdate
c1ec3f4f Geoffrey Richardson
datepaid transdate_oe transdate_do transdate_quo deliverydate_oe dodate
69ad8bec Thomas Kasulke
employee_startdate employee_enddate
),
grep({ /^datepaid_\d+$/ ||
/^transdate_oe_\d+$/ ||
c1ec3f4f Geoffrey Richardson
/^transdate_do_\d+$/ ||
/^transdate_quo_\d+$/ ||
69ad8bec Thomas Kasulke
/^deliverydate_oe_\d+$/ ||
/^reqdate_\d+$/ ||
/^deliverydate_\d+$/ ||
/^transdate_\d+$/
} keys(%{$form})));

reformat_numbers($output_numberformat, 2,
qw(invtotal ordtotal quototal subtotal linetotal
listprice sellprice netprice discount
7fa6b0a8 Moritz Bunkus
tax taxbase total paid payment),
5d43bf8e Moritz Bunkus
grep({ /^(?:linetotal|nodiscount_linetotal|listprice|sellprice|netprice|taxbase|discount|p_discount|discount_sub|nodiscount_sub|paid|subtotal|total|tax)_\d+$/ } keys(%{$form})));
69ad8bec Thomas Kasulke
reformat_numbers($output_numberformat, undef,
1e251313 Moritz Bunkus
qw(qty price_factor),
69ad8bec Thomas Kasulke
grep({ /^qty_\d+$/
} keys(%{$form})));

8688e71e Moritz Bunkus
my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');

if (scalar @{ $cvar_date_fields }) {
format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
}

while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
reformat_numbers($output_numberformat, $precision, @{ $field_list });
}

710ebb28 Sven Schöling
my $extension = 'html';
69ad8bec Thomas Kasulke
if ($form->{format} eq 'postscript') {
611a3dd3 Moritz Bunkus
$form->{postscript} = 1;
$extension = 'tex';

69ad8bec Thomas Kasulke
} elsif ($form->{"format"} =~ /pdf/) {
611a3dd3 Moritz Bunkus
$form->{pdf} = 1;
$extension = $form->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';

69ad8bec Thomas Kasulke
} elsif ($form->{"format"} =~ /opendocument/) {
611a3dd3 Moritz Bunkus
$form->{opendocument} = 1;
$extension = 'odt';
90815a31 Joachim Zach
} elsif ($form->{"format"} =~ /excel/) {
$form->{excel} = 1;
$extension = 'xls';
69ad8bec Thomas Kasulke
}

64084bfa Sven Schöling
# search for the template
a0516348 Moritz Bunkus
my ($template_file, @template_files) = SL::Helper::CreatePDF->find_template(
name => $form->{formname},
email => $form->{media} eq 'email',
language_id => $form->{language_id},
printer_id => $form->{printer_id},
extension => $extension,
);

if (!defined $template_file) {
64084bfa Sven Schöling
$::form->error($::locale->text('Cannot find matching template for this print request. Please contact your template maintainer. I tried these: #1.', join ', ', map { "'$_'"} @template_files));
}
611a3dd3 Moritz Bunkus
a0516348 Moritz Bunkus
$form->{IN} = $template_file;

e1e19a48 Moritz Bunkus
delete $form->{OUT};

69ad8bec Thomas Kasulke
if ($form->{media} eq 'printer') {
6ff1674f Sven Schöling
$form->{OUT} = $form->{printer_command};
$form->{OUT_MODE} = '|-';
69ad8bec Thomas Kasulke
$form->{printed} .= " $form->{formname}";
6ff1674f Sven Schöling
$form->{printed} =~ s/^ //;
69ad8bec Thomas Kasulke
}
9da3e39b Sven Schöling
my $printed = $form->{printed};
69ad8bec Thomas Kasulke
if ($form->{media} eq 'email') {
$form->{subject} = qq|$form->{label} $form->{"${inv}number"}|
unless $form->{subject};

$form->{emailed} .= " $form->{formname}";
$form->{emailed} =~ s/^ //;
3d8c8e2f Martin Helmling
$form->{addition} = "MAILED";
69ad8bec Thomas Kasulke
}
9da3e39b Sven Schöling
my $emailed = $form->{emailed};
69ad8bec Thomas Kasulke
if ($form->{media} eq 'queue') {
947583f5 Moritz Bunkus
my %queued = map { s|.*[/\\]||; $_ } split / /, $form->{queued};
69ad8bec Thomas Kasulke
9da3e39b Sven Schöling
my $filename;
9b0a9214 Geoffrey Richardson
my $suffix = ($form->{postscript}) ? '.ps' : '.pdf';
69ad8bec Thomas Kasulke
if ($filename = $queued{ $form->{formname} }) {
8cd05ad6 Moritz Bunkus
unlink $::lx_office_conf{paths}->{spool} . "/$filename";
f4b68a78 Moritz Bunkus
delete $queued{ $form->{formname} };

$form->{queued} = join ' ', %queued;
$filename =~ s/\..*$//g;
$filename .= $suffix;
$form->{OUT} = $::lx_office_conf{paths}->{spool} . "/$filename";
$form->{OUT_MODE} = '>';

69ad8bec Thomas Kasulke
} else {
9b0a9214 Geoffrey Richardson
my $temp_fh;
($temp_fh, $filename) = File::Temp::tempfile(
'kivitendo-spoolXXXXXX',
SUFFIX => "$suffix",
f4b68a78 Moritz Bunkus
DIR => $::lx_office_conf{paths}->{spool},
5d0aec66 Moritz Bunkus
UNLINK => 0,
9b0a9214 Geoffrey Richardson
);
close $temp_fh;
$form->{OUT} = "$filename";
# use >> for OUT_MODE because file is already created by File::Temp
$form->{OUT_MODE} = '>>';
# strip directory so that only filename is stored in table status
($filename) = $filename =~ /^$::lx_office_conf{paths}->{spool}\/(.*)/;
69ad8bec Thomas Kasulke
}

# add type
$form->{queued} .= " $form->{formname} $filename";
$form->{queued} =~ s/^ //;
}
9da3e39b Sven Schöling
my $queued = $form->{queued};
69ad8bec Thomas Kasulke
# saving the history
if(!exists $form->{addition}) {
c322b02a Geoffrey Richardson
$form->{snumbers} = "${inv}number" . "_" . $form->{"${inv}number"};
69ad8bec Thomas Kasulke
if($form->{media} =~ /printer/) {
b65a230d Sven Schöling
$form->{addition} = "PRINTED";
69ad8bec Thomas Kasulke
}
elsif($form->{media} =~ /email/) {
b65a230d Sven Schöling
$form->{addition} = "MAILED";
69ad8bec Thomas Kasulke
}
elsif($form->{media} =~ /queue/) {
b65a230d Sven Schöling
$form->{addition} = "QUEUED";
69ad8bec Thomas Kasulke
}
elsif($form->{media} =~ /screen/) {
b65a230d Sven Schöling
$form->{addition} = "SCREENED";
69ad8bec Thomas Kasulke
}
a590a651 Sven Schöling
$form->save_history;
69ad8bec Thomas Kasulke
}
# /saving the history

64084bfa Sven Schöling
# prepare meta information for template introspection
$form->{template_meta} = {
formname => $form->{formname},
cb575f7d Moritz Bunkus
language => SL::DB::Manager::Language->find_by_or_create(id => $form->{language_id} || undef),
64084bfa Sven Schöling
format => $form->{format},
media => $form->{media},
extension => $extension,
cb575f7d Moritz Bunkus
printer => SL::DB::Manager::Printer->find_by_or_create(id => $form->{printer_id} || undef),
4bc7f0aa Sven Schöling
today => DateTime->today,
64084bfa Sven Schöling
};

46f9d91b Moritz Bunkus
if ($defaults->print_interpolate_variables_in_positions) {
$form->substitute_placeholders_in_template_arrays({ field => 'description', type => 'text' }, { field => 'longdescription', type => 'html' });
}

8cd05ad6 Moritz Bunkus
$form->parse_template(\%myconfig);
69ad8bec Thomas Kasulke
$form->{callback} = "";

if ($form->{media} eq 'email') {
$form->{message} = $locale->text('sent') unless $form->{message};
}
9da3e39b Sven Schöling
my $message = $form->{message};
69ad8bec Thomas Kasulke
# if we got back here restore the previous form
if ($form->{media} =~ /(printer|email|queue)/) {

$form->update_status(\%myconfig)
if ($form->{media} eq 'queue' && $form->{id});

9da3e39b Sven Schöling
return $main::lxdebug->leave_sub() if ($old_form eq "return");
ffea1346 Moritz Bunkus
69ad8bec Thomas Kasulke
if ($old_form) {

$old_form->{"${inv}number"} = $form->{"${inv}number"};

# restore and display form
map { $form->{$_} = $old_form->{$_} } keys %$old_form;

$form->{queued} = $queued;
$form->{printed} = $printed;
$form->{emailed} = $emailed;
$form->{message} = $message;

$form->{rowcount}--;
map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
qw(exchangerate creditlimit creditremaining);

9da3e39b Sven Schöling
for my $i (1 .. $form->{paidaccounts}) {
69ad8bec Thomas Kasulke
map {
$form->{"${_}_$i"} =
$form->parse_amount(\%myconfig, $form->{"${_}_$i"})
} qw(paid exchangerate);
}

40782548 Moritz Bunkus
call_sub($display_form);
09479f02 Moritz Bunkus
$::dispatcher->end_request;
69ad8bec Thomas Kasulke
}

9da3e39b Sven Schöling
my $msg =
69ad8bec Thomas Kasulke
($form->{media} eq 'printer')
? $locale->text('sent to printer')
: $locale->text('emailed to') . " $form->{email}";
663a3643 Sven Schöling
if (!$params{no_redirect}) {
$form->redirect(qq|$form->{label} $form->{"${inv}number"} $msg|);
}
69ad8bec Thomas Kasulke
}
if ($form->{printing}) {
40782548 Moritz Bunkus
call_sub($display_form);
09479f02 Moritz Bunkus
$::dispatcher->end_request;
69ad8bec Thomas Kasulke
}

9da3e39b Sven Schöling
$main::lxdebug->leave_sub();
69ad8bec Thomas Kasulke
}

sub customer_details {
9da3e39b Sven Schöling
$main::lxdebug->enter_sub();

my $form = $main::form;
my %myconfig = %main::myconfig;
12ce5ee7 Moritz Bunkus
69ad8bec Thomas Kasulke
IS->customer_details(\%myconfig, \%$form, @_);
12ce5ee7 Moritz Bunkus
9da3e39b Sven Schöling
$main::lxdebug->leave_sub();
69ad8bec Thomas Kasulke
}

sub vendor_details {
9da3e39b Sven Schöling
$main::lxdebug->enter_sub();

my $form = $main::form;
my %myconfig = %main::myconfig;
69ad8bec Thomas Kasulke
IR->vendor_details(\%myconfig, \%$form, @_);

9da3e39b Sven Schöling
$main::lxdebug->leave_sub();
69ad8bec Thomas Kasulke
}

sub relink_accounts {
9da3e39b Sven Schöling
$main::lxdebug->enter_sub();

my $form = $main::form;
my %myconfig = %main::myconfig;
69ad8bec Thomas Kasulke
$form->{"taxaccounts"} =~ s/\s*$//;
$form->{"taxaccounts"} =~ s/^\s*//;
foreach my $accno (split(/\s*/, $form->{"taxaccounts"})) {
4e8e33e9 Geoffrey Richardson
map({ delete($form->{"${accno}_${_}"}); } qw(rate description taxnumber tax_id)); # add tax_id ?
69ad8bec Thomas Kasulke
}
$form->{"taxaccounts"} = "";

a87dd0ec Sven Schöling
IC->retrieve_accounts(\%myconfig, $form, map { $_ => $form->{"id_$_"} } 1 .. $form->{rowcount});
69ad8bec Thomas Kasulke
9da3e39b Sven Schöling
$main::lxdebug->leave_sub();
69ad8bec Thomas Kasulke
}

5bc87ade Moritz Bunkus
sub get_payment_terms_for_invoice {
my $terms = $::form->{payment_id} ? SL::DB::PaymentTerm->new(id => $::form->{payment_id}) ->load
: $::form->{customer_id} ? SL::DB::Customer ->new(id => $::form->{customer_id})->load->payment
: $::form->{vendor_id} ? SL::DB::Vendor ->new(id => $::form->{vendor_id}) ->load->payment
: undef;
9da3e39b Sven Schöling
5bc87ade Moritz Bunkus
return $terms;
}
69ad8bec Thomas Kasulke
5bc87ade Moritz Bunkus
sub set_duedate {
12ce5ee7 Moritz Bunkus
_check_io_auth();
8c7e4493 Moritz Bunkus
5bc87ade Moritz Bunkus
my $js = SL::ClientJS->new(controller => SL::Controller::Base->new);
my $terms = get_payment_terms_for_invoice();
my $invdate = $::form->{invdate} eq 'undefined' ? DateTime->today_local : DateTime->from_kivitendo($::form->{invdate});
my $duedate = $terms ? $terms->calc_date(reference_date => $invdate, due_date => $::form->{duedate})->to_kivitendo : ($::form->{duedate} || $invdate->to_kivitendo);
69ad8bec Thomas Kasulke
5bc87ade Moritz Bunkus
if ($terms && $terms->auto_calculation) {
$js->hide('#duedate_container')
->show('#duedate_fixed')
->html('#duedate_fixed', $duedate);
69ad8bec Thomas Kasulke
5bc87ade Moritz Bunkus
} else {
$js->show('#duedate_container')
->hide('#duedate_fixed');
}

$js->val('#duedate', $duedate)
->render;
69ad8bec Thomas Kasulke
}

480d9a56 Moritz Bunkus
sub _update_part_information {
9da3e39b Sven Schöling
$main::lxdebug->enter_sub();

my $form = $main::form;
480d9a56 Moritz Bunkus
781dbd51 Moritz Bunkus
my %part_information = IC->get_basic_part_info('id' => [ grep { $_ } map { $form->{"id_${_}"} } (1..$form->{rowcount}) ]);
480d9a56 Moritz Bunkus
$form->{PART_INFORMATION} = \%part_information;

foreach my $i (1..$form->{rowcount}) {
next unless ($form->{"id_${i}"});

65d2537d Martin Helmling
my $info = $form->{PART_INFORMATION}->{$form->{"id_${i}"}} || { };
$form->{"partunit_${i}"} = $info->{unit};
$form->{"weight_$i"} = $info->{weight};
$form->{"part_type_$i"} = $info->{part_type};
$form->{"classification_id_$i"} = $info->{classification_id};
ac24d564 Jan Büren
$form->{"has_sernumber_$i"} = $info->{has_sernumber};
480d9a56 Moritz Bunkus
}

9da3e39b Sven Schöling
$main::lxdebug->leave_sub();
480d9a56 Moritz Bunkus
}

sub _update_ship {
86a253d0 Jan Büren
return unless $::form->{id};
e80aa4c8 Sven Schöling
my $helper = SL::Helper::ShippedQty->new->calculate($::form->{id});
480d9a56 Moritz Bunkus
e80aa4c8 Sven Schöling
for my $i (1..$::form->{rowcount}) {
if (my $oid = $::form->{"orderitems_id_$i"}) {
$::form->{"ship_$i"} = $helper->shipped_qty->{$oid};
}
480d9a56 Moritz Bunkus
}
}
ef220490 Moritz Bunkus
sub _update_custom_variables {
9da3e39b Sven Schöling
$main::lxdebug->enter_sub();

my $form = $main::form;
ef220490 Moritz Bunkus
2bb587b7 Moritz Bunkus
$form->{CVAR_CONFIGS} = { } unless ref $form->{CVAR_CONFIGS} eq 'HASH';
ad2e3220 Sven Schöling
$form->{CVAR_CONFIGS}->{IC} ||= CVar->get_configs(module => 'IC');
ef220490 Moritz Bunkus
9da3e39b Sven Schöling
$main::lxdebug->leave_sub();
ef220490 Moritz Bunkus
}

sub _render_custom_variables_inputs {
0bbd98ca Sven Schöling
$main::lxdebug->enter_sub(2);
9da3e39b Sven Schöling
my $form = $main::form;
ef220490 Moritz Bunkus
my %params = @_;

if (!$form->{CVAR_CONFIGS}->{IC}) {
9da3e39b Sven Schöling
$main::lxdebug->leave_sub();
ef220490 Moritz Bunkus
return;
}

ad2e3220 Sven Schöling
my $valid = CVar->custom_variables_validity_by_trans_id(trans_id => $params{part_id});

36703a86 Bernd Bleßmann
# get partsgroup_id from part
my $partsgroup_id;
if ($params{part_id}) {
$partsgroup_id = SL::DB::Part->new(id => $params{part_id})->load->partsgroup_id;
}

ef220490 Moritz Bunkus
my $num_visible_cvars = 0;
foreach my $cvar (@{ $form->{CVAR_CONFIGS}->{IC} }) {
ad2e3220 Sven Schöling
$cvar->{valid} = $params{part_id} && $valid->($cvar->{id});
7dd8ee36 Sven Schöling
36703a86 Bernd Bleßmann
# set partsgroup filter
my $partsgroup_filtered = 0;
if ($cvar->{flag_partsgroup_filter}) {
if (!$partsgroup_id || (!grep {$partsgroup_id == $_} @{ $cvar->{partsgroups} })) {
$partsgroup_filtered = 1;
}
}

43a1ccc8 Bernd Bleßmann
my $hide_non_editable = 1;

25b85515 Bernd Bleßmann
my $show = 0;
ef220490 Moritz Bunkus
my $description = '';
43a1ccc8 Bernd Bleßmann
if (( ($cvar->{flag_editable} || !$hide_non_editable) && $cvar->{valid}) && !$partsgroup_filtered) {
ef220490 Moritz Bunkus
$num_visible_cvars++;
$description = $cvar->{description} . ' ';
25b85515 Bernd Bleßmann
$show = 1;
ef220490 Moritz Bunkus
}

db7c3a52 Sven Schöling
my $form_key = "ic_cvar_" . $cvar->{name} . "_$params{row}";

7dd8ee36 Sven Schöling
push @{ $params{ROW2} }, {
0cb6e3af Bernd Bleßmann
line_break => $show && !(($num_visible_cvars - 1) % ($::myconfig{form_cvars_nr_cols}*1 || 3)),
7dd8ee36 Sven Schöling
description => $description,
cvar => 1,
render_options => {
43a1ccc8 Bernd Bleßmann
hide_non_editable => $hide_non_editable,
7dd8ee36 Sven Schöling
var => $cvar,
name_prefix => 'ic_',
name_postfix => "_$params{row}",
valid => $cvar->{valid},
db7c3a52 Sven Schöling
value => CVar->parse($::form->{$form_key}, $cvar),
36703a86 Bernd Bleßmann
partsgroup_filtered => $partsgroup_filtered,
7dd8ee36 Sven Schöling
}
};
ef220490 Moritz Bunkus
}

0bbd98ca Sven Schöling
$main::lxdebug->leave_sub(2);
ef220490 Moritz Bunkus
}
a2820962 Moritz Bunkus
sub _remove_billed_or_delivered_rows {
my (%params) = @_;

croak "Missing parameter 'quantities'" if !$params{quantities};

my @fields = map { s/_1$//; $_ } grep { m/_1$/ } keys %{ $::form };
my @new_rows;

1beca8de Moritz Bunkus
my $make_key = sub {
my ($row) = @_;
return $::form->{"id_${row}"} unless $::form->{"serialnumber_${row}"};
my $key = $::form->{"id_${row}"} . ':' . $::form->{"serialnumber_${row}"};
return exists $params{quantities}->{$key} ? $key : $::form->{"id_${row}"};
};

a2820962 Moritz Bunkus
my $removed_rows = 0;
my $row = 0;
while ($row < $::form->{rowcount}) {
$row++;
next unless $::form->{"id_$row"};

my $parts_id = $::form->{"id_$row"};
my $base_qty = $::form->parse_amount(\%::myconfig, $::form->{"qty_$row"}) * SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor;

1beca8de Moritz Bunkus
my $key = $make_key->($row);
my $sub_qty = min($base_qty, $params{quantities}->{$key});
$params{quantities}->{$key} -= $sub_qty;
a2820962 Moritz Bunkus
if (!$sub_qty || ($sub_qty != $base_qty)) {
$::form->{"qty_${row}"} = $::form->format_amount(\%::myconfig, ($base_qty - $sub_qty) / SL::DB::Manager::Unit->find_by(name => $::form->{"unit_$row"})->base_factor);
push @new_rows, { map { $_ => $::form->{"${_}_${row}"} } @fields };

} else {
$removed_rows++;
}
}

$::form->redo_rows(\@fields, \@new_rows, scalar(@new_rows), $::form->{rowcount});
$::form->{rowcount} -= $removed_rows;
}
eebe8e90 Sven Schöling
0409db7c Sven Schöling
# TODO: both of these are makeshift so that price sources can operate on rdbo objects. if
# this ever gets rewritten in controller style, throw this out
eebe8e90 Sven Schöling
sub _make_record_item {
50fb51d9 Moritz Bunkus
my ($row, %params) = @_;
eebe8e90 Sven Schöling
my $class = {
sales_order => 'OrderItem',
349f3287 Sven Schöling
purchase_order => 'OrderItem',
eebe8e90 Sven Schöling
sales_quotation => 'OrderItem',
request_quotation => 'OrderItem',
invoice => 'InvoiceItem',
cae81a93 Bernd Bleßmann
invoice_for_advance_payment => 'InvoiceItem',
475b7a3f Bernd Bleßmann
final_invoice => 'InvoiceItem',
bc0f2d41 Bernd Bleßmann
credit_note => 'InvoiceItem',
eebe8e90 Sven Schöling
purchase_invoice => 'InvoiceItem',
purchase_delivery_order => 'DeliveryOrderItem',
sales_delivery_order => 'DeliveryOrderItem',
}->{$::form->{type}};

return unless $class;

$class = 'SL::DB::' . $class;

61a56bb4 Sven Schöling
my %translated_methods = (
'SL::DB::OrderItem' => {
id => 'parts_id',
orderitems_id => 'id',
},
'SL::DB::DeliveryOrderItem' => {
id => 'parts_id',
delivery_order_items_id => 'id',
},
'SL::DB::InvoiceItem' => {
id => 'parts_id',
invoice_id => 'id',
},
);

eebe8e90 Sven Schöling
eval "require $class";

my $obj = $::form->{"orderitems_id_$row"}
? $class->meta->convention_manager->auto_manager_class_name->find_by(id => $::form->{"orderitems_id_$row"})
: $class->new;

61a56bb4 Sven Schöling
for my $key (grep { /_$row$/ } keys %$::form) {
my $method = $key;
$method =~ s/_$row$//;
$method = $translated_methods{$class}{$method} // $method;
my $value = $::form->{$key};
b81ceec0 Sven Schöling
if ($obj->meta->column($method)) {
if ($obj->meta->column($method)->isa('Rose::DB::Object::Metadata::Column::Date')) {
61a56bb4 Sven Schöling
$obj->${\"$method\_as_date"}($value);
b81ceec0 Sven Schöling
} elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Numeric|Float|DoublePrecsion)$/) {
2ae70bd4 Moritz Bunkus
$obj->${\"$method\_as_number"}(($value // '') eq '' ? undef : $value);
b81ceec0 Sven Schöling
} elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::Boolean$/) {
61a56bb4 Sven Schöling
$obj->$method(!!$value);
2ae70bd4 Moritz Bunkus
} elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Big)?(?:Int(?:eger)?|Serial)$/) {
$obj->$method(($value // '') eq '' ? undef : $value * 1);
b81ceec0 Sven Schöling
} else {
61a56bb4 Sven Schöling
$obj->$method($value);
b81ceec0 Sven Schöling
}
cd6bfeee Moritz Bunkus
if ($method eq 'discount') {
$obj->discount($obj->discount / 100.0);
}

eebe8e90 Sven Schöling
} else {
61a56bb4 Sven Schöling
$obj->{__additional_form_attributes}{$method} = $value;
eebe8e90 Sven Schöling
}
}

if ($::form->{"id_$row"}) {
$obj->part(SL::DB::Part->load_cached($::form->{"id_$row"}));
}

50fb51d9 Moritz Bunkus
if ($obj->can('qty')) {
$obj->qty( $obj->qty * $params{factor});
$obj->base_qty($obj->base_qty * $params{factor});
}

eebe8e90 Sven Schöling
return $obj;
}
0409db7c Sven Schöling
sub _make_record {
my $class = {
sales_order => 'Order',
f712349f Sven Schöling
purchase_order => 'Order',
0409db7c Sven Schöling
sales_quotation => 'Order',
request_quotation => 'Order',
purchase_delivery_order => 'DeliveryOrder',
sales_delivery_order => 'DeliveryOrder',
}->{$::form->{type}};

fe7ad402 Bernd Bleßmann
if ($::form->{type} =~ /invoice|credit_note/) {
df1b03d5 Sven Schöling
$class = $::form->{vc} eq 'customer' ? 'Invoice'
: $::form->{vc} eq 'vendor' ? 'PurchaseInvoice'
: do { die 'unknown invoice type' };
}

50fb51d9 Moritz Bunkus
my $factor = $::form->{type} =~ m{credit_note} ? -1 : 1;

0409db7c Sven Schöling
return unless $class;

$class = 'SL::DB::' . $class;

eval "require $class";

my $obj = $::form->{id}
? $class->meta->convention_manager->auto_manager_class_name->find_by(id => $::form->{id})
: $class->new;

for my $method (keys %$::form) {
next unless $obj->can($method);
next unless $obj->meta->column($method);

if ($obj->meta->column($method)->isa('Rose::DB::Object::Metadata::Column::Date')) {
$obj->${\"$method\_as_date"}($::form->{$method});
} elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Numeric|Float|DoublePrecsion)$/) {
2ae70bd4 Moritz Bunkus
$obj->${\"$method\_as_number"}(($::form->{$method} // '') eq '' ? undef : $::form->{$method});
a6433753 Sven Schöling
} elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::Boolean$/) {
$obj->$method(!!$::form->{$method});
2ae70bd4 Moritz Bunkus
} elsif ((ref $obj->meta->column($method)) =~ /^Rose::DB::Object::Metadata::Column::(?:Big)?(?:Int(?:eger)?|Serial)$/) {
$obj->$method(($::form->{$method} // '') eq '' ? undef : $::form->{$method} * 1);
0409db7c Sven Schöling
} else {
$obj->$method($::form->{$method});
}
}

my @items;
for my $i (1 .. $::form->{rowcount}) {
next unless $::form->{"id_$i"};
50fb51d9 Moritz Bunkus
push @items, _make_record_item($i, factor => $factor);
0409db7c Sven Schöling
}

df1b03d5 Sven Schöling
$obj->items(@items) if @items;
a32fcad2 Sven Schöling
682aab29 Tamino Steinert
if ($class eq 'SL::DB::DeliveryOrder' && !$obj->record_type) {
$obj->record_type(SL::DB::DeliveryOrder::TypeData::validate_type($::form->{type}));
a32fcad2 Sven Schöling
}
0409db7c Sven Schöling
46d3e453 Werner Hahn
if ($class eq 'SL::DB::Order' && !$obj->record_type) {
$obj->record_type(SL::DB::Order::TypeData::validate_type($::form->{type}));
}

50fb51d9 Moritz Bunkus
if ($class eq 'SL::DB::Invoice') {
my $paid = $factor *
sum
map { $::form->parse_amount(\%::myconfig, $::form->{$_}) }
grep { m{^paid_\d+$} }
keys %{ $::form };
$obj->paid($paid);
}

0409db7c Sven Schöling
return $obj;
}
22bcb6b1 Moritz Bunkus
sub setup_sales_purchase_print_options {
my $print_form = Form->new('');
$print_form->{printers} = SL::DB::Manager::Printer->get_all_sorted;

7aafc9d0 Bernd Bleßmann
$print_form->{$_} = $::form->{$_} for qw(type media printer_id storno storno_id formname groupitems);
22bcb6b1 Moritz Bunkus
return SL::Helper::PrintOptions->get_print_options(
form => $print_form,
options => {
show_headers => 1,
},
);
}

dd33cbec Moritz Bunkus
sub _get_files_for_email_dialog {
bc0386a4 Jan Büren
my %files = map { ($_ => []) } qw(versions files vc_files part_files project_files);
dd33cbec Moritz Bunkus
return %files if !$::instance_conf->get_doc_storage;

8864a76c Sven Schöling
if ($::form->{id}) {
$files{versions} = [ SL::File->get_all_versions(object_id => $::form->{id}, object_type => $::form->{type}, file_type => 'document') ];
$files{files} = [ SL::File->get_all( object_id => $::form->{id}, object_type => $::form->{type}, file_type => 'attachment') ];
$files{vc_files} = [ SL::File->get_all( object_id => $::form->{vc_id}, object_type => $::form->{vc}, file_type => 'attachment') ]
if $::form->{vc} && $::form->{"vc_id"};
bc0386a4 Jan Büren
$files{project_files} = [ SL::File->get_all(object_id => $::form->{project_id}, object_type => 'project',file_type => 'attachment') ]
if $::form->{project_id};
8864a76c Sven Schöling
}
dd33cbec Moritz Bunkus
my @parts =
uniq_by { $_->{id} }
grep { $_->{id} }
map {
+{ id => $::form->{"id_$_"},
partnumber => $::form->{"partnumber_$_"},
}
} (1 .. $::form->{rowcount});

foreach my $part (@parts) {
my @pfiles = SL::File->get_all(object_id => $part->{id}, object_type => 'part');
push @{ $files{part_files} }, map { +{ %{ $_ }, partnumber => $part->{partnumber} } } @pfiles;
}

foreach my $key (keys %files) {
$files{$key} = [ sort_by { lc $_->{db_file}->{file_name} } @{ $files{$key} } ];
}

return %files;
}

22bcb6b1 Moritz Bunkus
sub show_sales_purchase_email_dialog {
c476418e Sven Schöling
my $email = '';
6170db24 Jan Büren
my $email_cc = '';
47da14db Jan Büren
my $record_email;
6eea98ae Jan Büren
my $is_invoice_mail = $::form->{type} =~ m{final_invoice|credit_note|invoice_for_advance_payment|invoice};

c476418e Sven Schöling
if ($::form->{cp_id}) {
$email = SL::DB::Contact->load_cached($::form->{cp_id})->cp_email;
103d03fb Moritz Bunkus
}
47da14db Jan Büren
# write a dispatch table if a third type enters
# check record mail for sales_invoice
6eea98ae Jan Büren
if ($is_invoice_mail && (!$email || $::instance_conf->get_invoice_mail_settings ne 'cp')) {
6170db24 Jan Büren
# check for invoice_mail if defined (vc.invoice_email)
47da14db Jan Büren
$record_email = SL::DB::Customer->load_cached($::form->{vc_id})->invoice_mail;
if ($record_email) {
6170db24 Jan Büren
# check if cc for contact is also wanted
$email_cc = $email if ($::instance_conf->get_invoice_mail_settings eq 'invoice_mail_cc_cp');
47da14db Jan Büren
$email = $record_email;
}
}
# check record mail for sales_delivery_order
if ($::form->{type} eq 'sales_delivery_order') {
# check for deliver_order_mail if defined (vc.delivery_order_mail)
$record_email = SL::DB::Customer->load_cached($::form->{vc_id})->delivery_order_mail;
if ($record_email) {
# check if cc for contact is also wanted
$email_cc = $email; # always cc to cp
$email = $record_email;
6170db24 Jan Büren
}
c1ef3aff Jan Büren
}
6170db24 Jan Büren
# still no email? use general mail (vc.email)
103d03fb Moritz Bunkus
if (!$email && $::form->{vc} && $::form->{vc_id}) {
c476418e Sven Schöling
$email = SL::DB::Customer->load_cached($::form->{vc_id})->email if 'customer' eq $::form->{vc};
$email = SL::DB::Vendor ->load_cached($::form->{vc_id})->email if 'vendor' eq $::form->{vc};
}

a9866c42 Moritz Bunkus
$email = '' if $::form->{type} eq 'purchase_delivery_order';
20e572be Moritz Bunkus
69bb392d Bernd Bleßmann
$::form->{language} = $::form->get_template_language(\%::myconfig);
$::form->{language} = "_" . $::form->{language};

d9ff130d Moritz Bunkus
my %body_params = (record_email => $record_email);
if (($::form->{type} eq 'invoice') && $::form->{direct_debit}) {
$body_params{translation_type} = "preset_text_invoice_direct_debit";
$body_params{fallback_translation_type} = "preset_text_invoice";
}

c48270dd Bernd Bleßmann
my @employees_with_email = grep {
my $user = SL::DB::Manager::AuthUser->find_by(login => $_->login);
$user && !!trim($user->get_config_value('email'));
} @{ SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]) };
26993da6 Bernd Bleßmann
22bcb6b1 Moritz Bunkus
my $email_form = {
c476418e Sven Schöling
to => $email,
6170db24 Jan Büren
cc => $email_cc,
22bcb6b1 Moritz Bunkus
subject => $::form->generate_email_subject,
d9ff130d Moritz Bunkus
message => $::form->generate_email_body(%body_params),
22bcb6b1 Moritz Bunkus
attachment_filename => $::form->generate_attachment_filename,
0f8e74b8 Bernd Bleßmann
js_send_function => 'kivi.SalesPurchase.send_email()',
22bcb6b1 Moritz Bunkus
};

dd33cbec Moritz Bunkus
my %files = _get_files_for_email_dialog();
5a07eafc Bernd Bleßmann
my $all_partner_email_addresses;
$all_partner_email_addresses = SL::DB::Customer->load_cached($::form->{vc_id})->get_all_email_addresses() if 'customer' eq $::form->{vc};
$all_partner_email_addresses = SL::DB::Vendor ->load_cached($::form->{vc_id})->get_all_email_addresses() if 'vendor' eq $::form->{vc};

dd33cbec Moritz Bunkus
my $html = $::form->parse_html_template("common/_send_email_dialog", {
26993da6 Bernd Bleßmann
email_form => $email_form,
show_bcc => $::auth->assert('email_bcc', 'may fail'),
FILES => \%files,
is_customer => $::form->{vc} eq 'customer',
6eea98ae Jan Büren
is_invoice_mail => ($record_email && $is_invoice_mail),
c48270dd Bernd Bleßmann
ALL_EMPLOYEES => \@employees_with_email,
5a07eafc Bernd Bleßmann
ALL_PARTNER_EMAIL_ADDRESSES => $all_partner_email_addresses,
22bcb6b1 Moritz Bunkus
});

print $::form->ajax_response_header, $html;
}

sub send_sales_purchase_email {
my $type = $::form->{type};
my $id = $::form->{id};
my $script = $type =~ m{sales_order|purchase_order|quotation} ? 'oe.pl'
: $type =~ m{delivery_} ? 'do.pl'
: 'is.pl';

my $email_form = delete $::form->{email_form};
5a07eafc Bernd Bleßmann
if ($email_form->{additional_to}) {
$email_form->{to} = join ', ', grep { $_ } $email_form->{to}, @{$email_form->{additional_to}};
delete $email_form->{additional_to};
}

22bcb6b1 Moritz Bunkus
my %field_names = (to => 'email');

$::form->{ $field_names{$_} // $_ } = $email_form->{$_} for keys %{ $email_form };

$::form->{media} = 'email';

1efa86b1 Bernd Bleßmann
$::form->{attachment_policy} //= '';

# Is an old file version available?
my $attfile;
if ($::form->{attachment_policy} eq 'old_file') {
0631649c Bernd Bleßmann
$attfile = SL::File->get_all(object_id => $id,
object_type => $type,
file_type => 'document',
print_variant => $::form->{formname},);
1efa86b1 Bernd Bleßmann
}

if ($::form->{attachment_policy} eq 'no_file' || ($::form->{attachment_policy} eq 'old_file' && $attfile)) {
dd33cbec Moritz Bunkus
$::form->send_email(\%::myconfig, 'pdf');

} else {
print_form("return");
7d96fb79 Jan Büren
Common->save_email_status(\%::myconfig, $::form) unless ($::instance_conf->get_email_journal);
dd33cbec Moritz Bunkus
}
22bcb6b1 Moritz Bunkus
flash_later('info', $::locale->text('The email has been sent.'));

print $::form->redirect_header($script . '?action=edit&id=' . $::form->escape($id) . '&type=' . $::form->escape($type));
}
cf0455f5 Moritz Bunkus
sub _maybe_attach_zugferd_data {
my ($form) = @_;

my $record = _make_record();

5da10e01 Moritz Bunkus
return if !$record
|| !$record->can('customer')
|| !$record->customer
|| !$record->can('create_pdf_a_print_options')
|| !$record->can('create_zugferd_data')
|| !$record->customer->create_zugferd_invoices_for_this_customer;
cf0455f5 Moritz Bunkus
333003d3 Moritz Bunkus
eval {
my $xmlfile = File::Temp->new;
$xmlfile->print($record->create_zugferd_data);
$xmlfile->close;

$form->{TEMPLATE_DRIVER_OPTIONS}->{pdf_a} = $record->create_pdf_a_print_options(zugferd_xmp_data => $record->create_zugferd_xmp_data);
$form->{TEMPLATE_DRIVER_OPTIONS}->{pdf_attachments} = [
{ source => $xmlfile,
ba40069b Moritz Bunkus
name => 'factur-x.xml',
description => $::locale->text('Factur-X/ZUGFeRD invoice'),
333003d3 Moritz Bunkus
relationship => '/Alternative',
mime_type => 'text/xml',
}
];
};

if (my $e = SL::X::ZUGFeRDValidation->caught) {
$::form->error($e->message);
}
cf0455f5 Moritz Bunkus
}
d8d90989 Moritz Bunkus
sub download_factur_x_xml {
my ($form) = @_;

my $record = _make_record();

die if !$record
|| !$record->can('customer')
|| !$record->customer
|| !$record->can('create_pdf_a_print_options')
|| !$record->can('create_zugferd_data')
|| !$record->customer->create_zugferd_invoices_for_this_customer;

my $xml_content = eval { $record->create_zugferd_data };

if (my $e = SL::X::ZUGFeRDValidation->caught) {
$::form->error($e->message);
}

27cf8a41 Moritz Bunkus
my $attachment_filename = "factur-x_" . $::form->generate_attachment_filename;
d8d90989 Moritz Bunkus
$attachment_filename =~ s{\.[^.]+$}{.xml};
my %headers = (
'-type' => 'application/xml',
'-connection' => 'close',
'-attachment' => $attachment_filename,
'-content-length' => length($xml_content),
);

print $::request->cgi->header(%headers);

$::locale->with_raw_io(\*STDOUT, sub { print $xml_content });
}
fc3b49d6 Tamino Steinert
sub get_taxes_dropdown {
my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
my $deliverydate = $::form->{deliverydate} ? DateTime->from_kivitendo($::form->{deliverydate}) : undef;
my $item_deliverydate = $::form->{item_deliverydate} ? DateTime->from_kivitendo($::form->{item_deliverydate}) : undef;

my @taxes = IO->get_active_taxes_for_chart($::form->{chart_id},
$item_deliverydate // $deliverydate // $transdate);
my $html = $::form->parse_html_template("ir/update_taxes", { TAXES => \@taxes });

print $::form->ajax_response_header, $html;
}

1;