1 package SL::Controller::CustomerVendor;
4 use parent qw(SL::Controller::Base);
6 use List::MoreUtils qw(any);
10 use SL::Helper::Flash;
11 use SL::Locale::String;
12 use SL::Util qw(trim);
16 use SL::Controller::Helper::GetModels;
17 use SL::Controller::Helper::ReportGenerator;
18 use SL::Controller::Helper::ParseFilter;
20 use SL::DB::AuthGroup;
24 use SL::DB::ContactDepartment;
25 use SL::DB::ContactTitle;
31 use SL::DB::PaymentTerm;
32 use SL::DB::Pricegroup;
36 use SL::DB::FollowUpLink;
40 use SL::DB::PurchaseInvoice;
45 use Rose::Object::MakeMethods::Generic (
46 scalar => [ qw(user_has_edit_rights) ],
47 'scalar --get_set_init' => [ qw(customer_models vendor_models zugferd_settings) ],
51 __PACKAGE__->run_before(
55 'save_and_ap_transaction',
56 'save_and_ar_transaction',
65 'delete_additional_billing_address',
69 __PACKAGE__->run_before(
70 '_load_customer_vendor',
76 'ajaj_get_additional_billing_address',
82 # make sure this comes after _load_customer_vendor
83 __PACKAGE__->run_before('_check_auth');
85 __PACKAGE__->run_before(
86 '_create_customer_vendor',
92 __PACKAGE__->run_before('normalize_name');
94 my @ADDITIONAL_BILLING_ADDRESS_COLUMNS = qw(name department_1 department_2 contact street zipcode city country gln email phone fax default_address);
101 if ($self->{cv}->is_customer) {
102 $self->{cv}->assign_attributes(hourly_rate => $::instance_conf->get_customer_hourly_rate);
103 $self->{cv}->salesman_id(SL::DB::Manager::Employee->current->id) if !$::auth->assert('customer_vendor_all_edit', 1);
107 'customer_vendor/form',
108 title => ($self->is_vendor() ? $::locale->text('Add Vendor') : $::locale->text('Add Customer')),
109 %{$self->{template_args}}
116 $self->_pre_render();
118 'customer_vendor/form',
119 title => ($self->is_vendor() ? $::locale->text('Edit Vendor') : $::locale->text('Edit Customer')),
120 %{$self->{template_args}}
127 if ($::request->type eq 'json') {
132 $cv_hash = $self->{cv}->as_tree;
133 $cv_hash->{cvars} = $self->{cv}->cvar_as_hashref;
136 $self->render(\ SL::JSON::to_json($cv_hash), { layout => 0, type => 'json', process => 0 });
140 sub _check_ustid_taxnumber_unique {
144 if ($self->is_vendor()) {
145 %cfg = (should_check => $::instance_conf->get_vendor_ustid_taxnummer_unique,
146 manager_class => 'SL::DB::Manager::Vendor',
147 err_ustid => t8('A vendor with the same VAT ID already exists.'),
148 err_taxnumber => t8('A vendor with the same taxnumber already exists.'),
151 } elsif ($self->is_customer()) {
152 %cfg = (should_check => $::instance_conf->get_customer_ustid_taxnummer_unique,
153 manager_class => 'SL::DB::Manager::Customer',
154 err_ustid => t8('A customer with the same VAT ID already exists.'),
155 err_taxnumber => t8('A customer with the same taxnumber already exists.'),
164 if ($cfg{should_check}) {
165 my $do_clean_taxnumber = sub { my $n = $_[0]; $n //= ''; $n =~ s{[[:space:].-]+}{}g; return $n};
167 my $clean_ustid = SL::VATIDNr->clean($self->{cv}->ustid);
168 my $clean_taxnumber = $do_clean_taxnumber->($self->{cv}->taxnumber);
170 if (!($clean_ustid || $clean_taxnumber)) {
171 return t8('VAT ID and/or taxnumber must be given.');
174 my $clean_number = $clean_ustid;
176 my $entries = $cfg{manager_class}->get_all(query => ['!id' => $self->{cv}->id, '!ustid' => undef, '!ustid' => ''], select => ['ustid'], distinct => 1);
177 if (any { $clean_number eq SL::VATIDNr->clean($_->ustid) } @$entries) {
178 push @errors, $cfg{err_ustid};
182 $clean_number = $clean_taxnumber;
184 my $entries = $cfg{manager_class}->get_all(query => ['!id' => $self->{cv}->id, '!taxnumber' => undef, '!taxnumber' => ''], select => ['taxnumber'], distinct => 1);
185 if (any { $clean_number eq $do_clean_taxnumber->($_->taxnumber) } @$entries) {
186 push @errors, $cfg{err_taxnumber};
192 return join "\n", @errors if @errors;
199 my @errors = $self->{cv}->validate;
201 flash('error', @errors);
202 $self->_pre_render();
204 'customer_vendor/form',
205 title => ($self->is_vendor() ? t8('Edit Vendor') : t8('Edit Customer')),
206 %{$self->{template_args}}
208 $::dispatcher->end_request;
211 $self->{cv}->greeting(trim $self->{cv}->greeting);
212 my $save_greeting = $self->{cv}->greeting
213 && $::instance_conf->get_vc_greetings_use_textfield
214 && SL::DB::Manager::Greeting->get_all_count(where => [description => $self->{cv}->greeting]) == 0;
216 $self->{contact}->cp_title(trim($self->{contact}->cp_title));
217 my $save_contact_title = $self->{contact}->cp_title
218 && $::instance_conf->get_contact_titles_use_textfield
219 && SL::DB::Manager::ContactTitle->get_all_count(where => [description => $self->{contact}->cp_title]) == 0;
221 $self->{contact}->cp_abteilung(trim($self->{contact}->cp_abteilung));
222 my $save_contact_department = $self->{contact}->cp_abteilung
223 && $::instance_conf->get_contact_departments_use_textfield
224 && SL::DB::Manager::ContactDepartment->get_all_count(where => [description => $self->{contact}->cp_abteilung]) == 0;
226 my $db = $self->{cv}->db;
228 $db->with_transaction(sub {
230 if ( $self->is_vendor() ) {
231 if ( $self->{cv}->vendornumber ) {
232 $cvs_by_nr = SL::DB::Manager::Vendor->get_all(query => [vendornumber => $self->{cv}->vendornumber]);
235 if ( $self->{cv}->customernumber ) {
236 $cvs_by_nr = SL::DB::Manager::Customer->get_all(query => [customernumber => $self->{cv}->customernumber]);
240 foreach my $entry (@{$cvs_by_nr}) {
241 if( $entry->id != $self->{cv}->id ) {
243 $self->is_vendor() ? $::locale->text('This vendor number is already in use.') : $::locale->text('This customer number is already in use.');
245 $::form->error($msg);
249 my $ustid_taxnumber_error = $self->_check_ustid_taxnumber_unique;
250 $::form->error($ustid_taxnumber_error) if $ustid_taxnumber_error;
252 $self->{cv}->save(cascade => 1);
254 SL::DB::Greeting->new(description => $self->{cv}->greeting)->save if $save_greeting;
256 $self->{contact}->cp_cv_id($self->{cv}->id);
257 if( $self->{contact}->cp_name ne '' || $self->{contact}->cp_givenname ne '' ) {
258 SL::DB::ContactTitle ->new(description => $self->{contact}->cp_title) ->save if $save_contact_title;
259 SL::DB::ContactDepartment->new(description => $self->{contact}->cp_abteilung)->save if $save_contact_department;
261 $self->{contact}->save(cascade => 1);
264 if( $self->{note}->subject ne '' && $self->{note}->body ne '' ) {
266 if ( !$self->{note_followup}->follow_up_date ) {
267 $::form->error($::locale->text('Date missing!'));
269 if (!$self->{note_followup}->{created_for_employees}) {
270 $::form->error($::locale->text('You must chose a user.'));
273 $self->{note}->trans_id($self->{cv}->id);
274 $self->{note}->save();
276 if (delete $self->{note_followup}->{not_done}) {
277 $self->{note_followup}->done->delete if $self->{note_followup}->done;
279 $self->{note_followup}->save();
281 $self->{note_followup_link}->follow_up_id($self->{note_followup}->id);
282 $self->{note_followup_link}->trans_id($self->{cv}->id);
283 $self->{note_followup_link}->save();
285 SL::Helper::Flash::flash_later('info', $::locale->text('Follow-Up saved.'));
288 $self->{shipto}->trans_id($self->{cv}->id);
289 if(any { $self->{shipto}->$_ ne '' } qw(shiptoname shiptodepartment_1 shiptodepartment_2 shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax shiptoemail)) {
290 $self->{shipto}->save(cascade => 1);
293 if ($self->is_customer && any { $self->{additional_billing_address}->$_ ne '' } grep { $_ ne 'default_address' } @ADDITIONAL_BILLING_ADDRESS_COLUMNS) {
294 $self->{additional_billing_address}->customer_id($self->{cv}->id);
295 $self->{additional_billing_address}->save(cascade => 1);
297 # Make sure only one address per customer has "default address" set.
298 if ($self->{additional_billing_address}->default_address) {
299 SL::DB::Manager::AdditionalBillingAddress->update_all(
300 set => { default_address => 0, },
302 customer_id => $self->{cv}->id,
303 '!id' => $self->{additional_billing_address}->id,
308 my $snumbers = $self->is_vendor() ? 'vendornumber_'. $self->{cv}->vendornumber : 'customernumber_'. $self->{cv}->customernumber;
309 SL::DB::History->new(
310 trans_id => $self->{cv}->id,
311 snumbers => $snumbers,
312 employee_id => SL::DB::Manager::Employee->current->id,
316 if ( $::form->{delete_notes} ) {
317 foreach my $note_id (@{ $::form->{delete_notes} }) {
318 my $note = SL::DB::Note->new(id => $note_id)->load();
319 if ( $note->follow_up ) {
320 if ( $note->follow_up->follow_up_link ) {
321 $note->follow_up->follow_up_link->delete(cascade => 'delete');
323 $note->follow_up->delete(cascade => 'delete');
325 $note->delete(cascade => 'delete');
330 }) || die($db->error);
339 my @redirect_params = (
341 id => $self->{cv}->id,
342 db => ($self->is_vendor() ? 'vendor' : 'customer'),
345 if ( $self->{contact}->cp_id ) {
346 push(@redirect_params, contact_id => $self->{contact}->cp_id);
349 if ( $self->{shipto}->shipto_id ) {
350 push(@redirect_params, shipto_id => $self->{shipto}->shipto_id);
353 if ( $self->is_customer && $self->{additional_billing_address}->id ) {
354 push(@redirect_params, additional_billing_address_id => $self->{additional_billing_address}->id);
357 $self->redirect_to(@redirect_params);
360 sub action_save_and_close {
365 my $msg = $self->is_vendor() ? $::locale->text('Vendor saved') : $::locale->text('Customer saved');
366 $::form->redirect($msg);
370 my ($self, $script) = @_;
372 $::auth->assert('gl_transactions | ap_transactions | ar_transactions'.
373 '| invoice_edit | vendor_invoice_edit | ' .
374 ' request_quotation_edit | sales_quotation_edit | sales_order_edit | purchase_order_edit');
378 my $name = $::form->escape($self->{cv}->name, 1);
379 my $db = $self->is_vendor() ? 'vendor' : 'customer';
382 if ('oe.pl' eq $script) {
383 $script = 'controller.pl';
384 $action = 'Order/' . $action;
387 my $url = $self->url_for(
388 controller => $script,
391 $db .'_id' => $self->{cv}->id,
393 type => $::form->{type},
394 callback => $::form->{callback},
397 print $::form->redirect_header($url);
400 sub action_save_and_ar_transaction {
403 $main::auth->assert('ar_transactions');
405 $self->_transaction('ar.pl');
408 sub action_save_and_ap_transaction {
411 $main::auth->assert('ap_transactions');
413 $self->_transaction('ap.pl');
416 sub action_save_and_invoice {
419 if ( $self->is_vendor() ) {
420 $::auth->assert('vendor_invoice_edit');
422 $::auth->assert('invoice_edit');
425 $::form->{type} = 'invoice';
426 $self->_transaction($self->is_vendor() ? 'ir.pl' : 'is.pl');
429 sub action_save_and_order {
432 if ( $self->is_vendor() ) {
433 $::auth->assert('purchase_order_edit');
435 $::auth->assert('sales_order_edit');
438 $::form->{type} = $self->is_vendor() ? 'purchase_order' : 'sales_order';
439 $self->_transaction('oe.pl');
442 sub action_save_and_rfq {
445 $::auth->assert('request_quotation_edit');
447 $::form->{type} = 'request_quotation';
448 $self->_transaction('oe.pl');
451 sub action_save_and_quotation {
454 $::auth->assert('sales_quotation_edit');
456 $::form->{type} = 'sales_quotation';
457 $self->_transaction('oe.pl');
463 my $db = $self->{cv}->db;
465 if( !$self->is_orphaned() ) {
466 $self->action_edit();
469 $db->with_transaction(sub {
470 $self->{cv}->delete(cascade => 1);
472 my $snumbers = $self->is_vendor() ? 'vendornumber_'. $self->{cv}->vendornumber : 'customernumber_'. $self->{cv}->customernumber;
473 SL::DB::History->new(
474 trans_id => $self->{cv}->id,
475 snumbers => $snumbers,
476 employee_id => SL::DB::Manager::Employee->current->id,
477 addition => 'DELETED',
479 }) || die($db->error);
481 my $msg = $self->is_vendor() ? $::locale->text('Vendor deleted!') : $::locale->text('Customer deleted!');
482 $::form->redirect($msg);
488 sub action_delete_contact {
491 my $db = $self->{contact}->db;
493 if ( !$self->{contact}->cp_id ) {
494 SL::Helper::Flash::flash('error', $::locale->text('No contact selected to delete'));
497 $db->with_transaction(sub {
498 if ( $self->{contact}->used ) {
499 $self->{contact}->detach();
500 $self->{contact}->save();
501 SL::Helper::Flash::flash('info', $::locale->text('Contact is in use and was flagged invalid.'));
503 $self->{contact}->delete(cascade => 1);
504 SL::Helper::Flash::flash('info', $::locale->text('Contact deleted.'));
508 }) || die($db->error);
510 $self->{contact} = $self->_new_contact_object;
513 $self->action_edit();
516 sub action_delete_shipto {
519 my $db = $self->{shipto}->db;
521 if ( !$self->{shipto}->shipto_id ) {
522 SL::Helper::Flash::flash('error', $::locale->text('No shipto selected to delete'));
525 $db->with_transaction(sub {
526 if ( $self->{shipto}->used ) {
527 $self->{shipto}->detach();
528 $self->{shipto}->save(cascade => 1);
529 SL::Helper::Flash::flash('info', $::locale->text('Shipto is in use and was flagged invalid.'));
531 $self->{shipto}->delete(cascade => 1);
532 SL::Helper::Flash::flash('info', $::locale->text('Shipto deleted.'));
536 }) || die($db->error);
538 $self->{shipto} = SL::DB::Shipto->new();
541 $self->action_edit();
544 sub action_delete_additional_billing_address {
547 my $db = $self->{additional_billing_address}->db;
549 if ( !$self->{additional_billing_address}->id ) {
550 SL::Helper::Flash::flash('error', $::locale->text('No address selected to delete'));
552 $db->with_transaction(sub {
553 if ( $self->{additional_billing_address}->used ) {
554 $self->{additional_billing_address}->detach;
555 $self->{additional_billing_address}->save(cascade => 1);
556 SL::Helper::Flash::flash('info', $::locale->text('Address is in use and was flagged invalid.'));
558 $self->{additional_billing_address}->delete(cascade => 1);
559 SL::Helper::Flash::flash('info', $::locale->text('Address deleted.'));
563 }) || die($db->error);
565 $self->{additional_billing_address} = SL::DB::AdditionalBillingAddress->new;
575 controller => 'ct.pl',
577 db => $self->is_vendor() ? 'vendor' : 'customer',
580 if ( $::form->{callback} ) {
581 push(@url_params, callback => $::form->{callback});
584 $self->redirect_to(@url_params);
588 sub action_search_contact {
591 my $url = 'ct.pl?action=search_contact&db=customer';
593 if ( $::form->{callback} ) {
594 $url .= '&callback='. $::form->escape($::form->{callback});
597 print $::form->redirect_header($url);
600 sub action_get_delivery {
603 $::auth->assert('sales_all_edit') if $self->is_customer();
604 $::auth->assert('purchase_all_edit') if $self->is_vendor();
606 my $dbh = $::form->get_standard_dbh();
608 my ($arap, $db, $qty_sign);
609 if ( $self->is_vendor() ) {
612 $qty_sign = ' * -1 AS qty';
619 my $where = ' WHERE 1=1';
622 if ( !$self->is_vendor() && $::form->{shipto_id} && $::form->{shipto_id} ne 'all' ) {
623 $where .= " AND ${arap}.shipto_id = ?";
624 push(@values, $::form->{shipto_id});
626 $where .= " AND ${arap}.${db}_id = ?";
627 push(@values, $::form->{id});
630 if ( $::form->{delivery_from} ) {
631 $where .= " AND ${arap}.transdate >= ?";
632 push(@values, conv_date($::form->{delivery_from}));
635 if ( $::form->{delivery_to} ) {
636 $where .= " AND ${arap}.transdate <= ?";
637 push(@values, conv_date($::form->{delivery_to}));
656 ON ". ($arap eq 'ar' ? '(ar.shipto_id = s.shipto_id) ' : '(ap.id = s.trans_id) ') ."
659 ON ${arap}.id = i.trans_id
665 ON (oe.ordnumber = ${arap}.ordnumber AND NOT ${arap}.ordnumber = ''
666 AND ". ($arap eq 'ar' ? 'oe.customer_id IS NOT NULL' : 'oe.vendor_id IS NOT NULL') ." )
669 ORDER BY ${arap}.transdate DESC LIMIT 15";
671 $self->{delivery} = selectall_hashref_query($::form, $dbh, $query, @values);
673 $self->render('customer_vendor/get_delivery', { layout => 0 });
676 sub action_ajaj_get_shipto {
683 my $name = 'shipto'. $_;
684 $name => $self->{shipto}->$name;
686 qw(_id name department_1 department_2 street zipcode city gln country contact phone fax email)
690 $data->{shipto_cvars} = $self->_prepare_cvar_configs_for_ajaj($self->{shipto}->cvars_by_config);
692 $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
695 sub action_ajaj_get_additional_billing_address {
699 additional_billing_address => {
700 map { ($_ => $self->{additional_billing_address}->$_) } ('id', @ADDITIONAL_BILLING_ADDRESS_COLUMNS)
704 $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
707 sub action_ajaj_get_contact {
715 my $name = 'cp_'. $_;
717 if ( $_ eq 'birthday' && $self->{contact}->$name ) {
718 $name => $self->{contact}->$name->to_lxoffice;
720 $name => $self->{contact}->$name;
724 id gender abteilung title position givenname name email phone1 phone2 fax mobile1 mobile2
725 satphone satfax project street zipcode city privatphone privatemail birthday main
730 $data->{contact_cvars} = $self->_prepare_cvar_configs_for_ajaj($self->{contact}->cvars_by_config);
732 # avoid two or more main_cp
733 my $has_main_cp = grep { $_->cp_main == 1 } @{ $self->{cv}->contacts };
734 $data->{contact}->{disable_cp_main} = 1 if ($has_main_cp && !$data->{contact}->{cp_main});
736 $self->render(\SL::JSON::to_json($data), { type => 'json', process => 0 });
739 sub action_ajaj_autocomplete {
740 my ($self, %params) = @_;
742 my ($model, $manager, $number, $matches);
744 # first see if this is customer or vendor picking
745 if ($::form->{type} eq 'customer') {
746 $model = $self->customer_models;
747 $manager = 'SL::DB::Manager::Customer';
748 $number = 'customernumber';
749 } elsif ($::form->{type} eq 'vendor') {
750 $model = $self->vendor_models;
751 $manager = 'SL::DB::Manager::Vendor';
752 $number = 'vendornumber';
754 die "unknown type $::form->{type}";
757 # if someone types something, and hits enter, assume he entered the full name.
758 # if something matches, treat that as the sole match
759 # unfortunately get_models can't do more than one per package atm, so we do it
760 # the oldfashioned way.
761 if ($::form->{prefer_exact}) {
763 if (1 == scalar @{ $exact_matches = $manager->get_all(
767 name => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
768 $number => { ilike => $::form->{filter}{'all:substr:multi::ilike'} },
773 $matches = $exact_matches;
777 $matches //= $model->get;
781 value => $_->displayable_name,
782 label => $_->displayable_name,
784 $number => $_->$number,
786 type => $::form->{type},
787 cvars => { map { ($_->config->name => { value => $_->value_as_text, is_valid => $_->is_valid }) } @{ $_->cvars_by_config } },
791 $self->render(\ SL::JSON::to_json(\@hashes), { layout => 0, type => 'json', process => 0 });
794 sub action_test_page {
795 $_[0]->render('customer_vendor/test_page');
798 sub action_ajax_list_prices {
799 my ($self, %params) = @_;
801 my $report = SL::ReportGenerator->new(\%::myconfig, $::form);
802 my @columns = qw(partnumber description price);
803 my @visible = qw(partnumber description price);
804 my @sortable = qw(partnumber description price);
807 partnumber => { text => $::locale->text('Part Number'), sub => sub { $_[0]->parts->partnumber } },
808 description => { text => $::locale->text('Part Description'), sub => sub { $_[0]->parts->description } },
809 price => { text => $::locale->text('Price'), sub => sub { $::form->format_amount(\%::myconfig, $_[0]->price, 2) }, align => 'right' },
812 $::form->{sort_by} ||= 'partnumber';
813 $::form->{sort_dir} //= 1;
815 for my $col (@sortable) {
816 $column_defs{$col}{link} = $self->url_for(
817 action => 'ajax_list_prices',
818 callback => $::form->{callback},
820 id => $self->{cv}->id,
822 sort_dir => ($::form->{sort_by} eq $col ? 1 - $::form->{sort_dir} : $::form->{sort_dir})
826 map { $column_defs{$_}{visible} = 1 } @visible;
829 $pricegroup = $self->{cv}->pricegroup->pricegroup if $self->{cv}->pricegroup;
831 $report->set_columns(%column_defs);
832 $report->set_column_order(@columns);
833 $report->set_options(allow_pdf_export => 0, allow_csv_export => 0);
834 $report->set_sort_indicator($::form->{sort_by}, $::form->{sort_dir});
835 $report->set_export_options(@{ $params{report_generator_export_options} || [] });
836 $report->set_options(
837 %{ $params{report_generator_options} || {} },
838 output_format => 'HTML',
839 top_info_text => $::locale->text('Pricegroup') . ': ' . $pricegroup,
840 title => $::locale->text('Price List'),
843 my $sort_param = $::form->{sort_by} eq 'price' ? 'price' :
844 $::form->{sort_by} eq 'description' ? 'parts.description' :
846 $sort_param .= ' ' . ($::form->{sort_dir} ? 'ASC' : 'DESC');
847 my $prices = SL::DB::Manager::Price->get_all(where => [ pricegroup_id => $self->{cv}->pricegroup_id ],
848 sort_by => $sort_param,
849 with_objects => 'parts');
851 $self->report_generator_list_objects(report => $report, objects => $prices, layout => 0, header => 0);
854 # open the dialog for customer/vendor details
855 # called from SL::Presenter::customer_vendor
856 sub action_show_customer_vendor_details_dialog {
859 my $is_customer = 'customer' eq $::form->{cv};
862 $cv = SL::DB::Customer->new(id => $::form->{cv_id})->load;
864 $cv = SL::DB::Vendor->new(id => $::form->{cv_id})->load;
867 my %details = map { $_ => $cv->$_ } @{$cv->meta->columns};
868 $details{discount_as_percent} = $cv->discount_as_percent;
869 $details{creditlimt} = $cv->creditlimit_as_number;
870 $details{business} = $cv->business->description if $cv->business;
871 $details{language} = $cv->language_obj->description if $cv->language_obj;
872 $details{delivery_terms} = $cv->delivery_term->description if $cv->delivery_term;
873 $details{payment_terms} = $cv->payment->description if $cv->payment;
874 $details{pricegroup} = $cv->pricegroup->pricegroup if $is_customer && $cv->pricegroup;
877 foreach my $entry (@{ $cv->additional_billing_addresses }) {
878 push @{ $details{ADDITIONAL_BILLING_ADDRESSES} }, { map { $_ => $entry->$_ } @{$entry->meta->columns} };
881 foreach my $entry (@{ $cv->shipto }) {
882 push @{ $details{SHIPTO} }, { map { $_ => $entry->$_ } @{$entry->meta->columns} };
884 foreach my $entry (@{ $cv->contacts }) {
885 push @{ $details{CONTACTS} }, { map { $_ => $entry->$_ } @{$entry->meta->columns} };
888 $_[0]->render('common/show_vc_details', { layout => 0 },
889 is_customer => $is_customer,
895 return $::form->{db} eq 'vendor';
899 return $::form->{db} eq 'customer';
905 if ( defined($self->{_is_orphaned}) ) {
906 return $self->{_is_orphaned};
909 my $arap = $self->is_vendor ? 'ap' : 'ar';
912 my $cv = $self->is_vendor ? 'vendor' : 'customer';
916 FROM '. $arap .' AS a
917 JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
924 JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
930 FROM delivery_orders a
931 JOIN '. $cv .' ct ON (a.'. $cv .'_id = ct.id)
937 FROM price_rule_items
938 WHERE type LIKE \''. $cv .'\' AND value_int = ?';
941 if ( $self->is_vendor ) {
944 SELECT 1 FROM makemodel mm WHERE mm.make = ?';
948 my ($dummy) = selectrow_query($::form, $::form->get_standard_dbh(), $query, (conv_i($self->{cv}->id)) x $num_args);
950 return $self->{_is_orphaned} = !$dummy;
953 sub _copy_form_to_cvars {
954 my ($self, %params) = @_;
956 foreach my $cvar (@{ $params{target}->cvars_by_config }) {
957 my $value = $params{source}->{$cvar->config->name};
958 $value = $::form->parse_amount(\%::myconfig, $value) if $cvar->config->type eq 'number';
960 $cvar->value($value);
964 sub _instantiate_args {
967 my $curr_employee = SL::DB::Manager::Employee->current;
969 if ( $::form->{cv}->{id} ) {
970 if ( $self->is_vendor() ) {
971 $self->{cv} = SL::DB::Vendor->new(id => $::form->{cv}->{id})->load();
973 $self->{cv} = SL::DB::Customer->new(id => $::form->{cv}->{id})->load();
976 $self->{cv} = $self->_new_customer_vendor_object;
978 $self->{cv}->assign_attributes(%{$::form->{cv}});
980 if ( $self->is_customer() && $::form->{cv}->{taxincluded_checked} eq '' ) {
981 $self->{cv}->taxincluded_checked(undef);
984 $self->{cv}->hourly_rate($::instance_conf->get_customer_hourly_rate) if $self->is_customer && !$self->{cv}->hourly_rate;
986 if ( $::form->{note}->{id} ) {
987 $self->{note} = SL::DB::Note->new(id => $::form->{note}->{id})->load();
988 $self->{note_followup} = $self->{note}->follow_up;
989 $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
992 $self->{note} = SL::DB::Note->new();
993 $self->{note_followup} = SL::DB::FollowUp->new();
994 $self->{note_followup_link} = SL::DB::FollowUpLink->new();
997 $self->{note}->assign_attributes(%{$::form->{note}});
998 $self->{note}->created_by($curr_employee->id);
999 $self->{note}->trans_module('ct');
1001 $self->{note_followup}->assign_attributes(%{$::form->{note_followup}});
1002 $self->{note_followup}->note($self->{note});
1003 $self->{note_followup}->created_by($curr_employee->id);
1005 if (delete $::form->{note_followup_done}) {
1006 $self->{note_followup}->done(SL::DB::FollowUpDone->new) if !$self->{note_followup}->done;
1007 $self->{note_followup}->done->employee_id(SL::DB::Manager::Employee->current->id);
1009 $self->{note_followup}->{not_done} = 1;
1012 $self->{note_followup_link}->trans_type($self->is_vendor() ? 'vendor' : 'customer');
1013 $self->{note_followup_link}->trans_info($self->{cv}->name);
1015 if ( $::form->{shipto}->{shipto_id} ) {
1016 $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto}->{shipto_id})->load();
1018 $self->{shipto} = SL::DB::Shipto->new();
1020 $self->{shipto}->assign_attributes(%{$::form->{shipto}});
1021 $self->{shipto}->module('CT');
1023 if ($self->is_customer) {
1024 if ( $::form->{additional_billing_address}->{id} ) {
1025 $self->{additional_billing_address} = SL::DB::AdditionalBillingAddress->new(id => $::form->{additional_billing_address}->{id})->load;
1027 $self->{additional_billing_address} = SL::DB::AdditionalBillingAddress->new;
1029 $self->{additional_billing_address}->assign_attributes(%{ $::form->{additional_billing_address} });
1032 if ( $::form->{contact}->{cp_id} ) {
1033 $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact}->{cp_id})->load();
1035 $self->{contact} = $self->_new_contact_object;
1037 $self->{contact}->assign_attributes(%{$::form->{contact}});
1039 $self->_copy_form_to_cvars(target => $self->{cv}, source => $::form->{cv_cvars});
1040 $self->_copy_form_to_cvars(target => $self->{contact}, source => $::form->{contact_cvars});
1041 $self->_copy_form_to_cvars(target => $self->{shipto}, source => $::form->{shipto_cvars});
1044 sub _load_customer_vendor {
1047 if ( $self->is_vendor() ) {
1048 $self->{cv} = SL::DB::Vendor->new(id => $::form->{id})->load();
1050 $self->{cv} = SL::DB::Customer->new(id => $::form->{id})->load();
1053 if ( $::form->{note_id} ) {
1054 $self->{note} = SL::DB::Note->new(id => $::form->{note_id})->load();
1055 $self->{note_followup} = $self->{note}->follow_up;
1056 $self->{note_followup_link} = $self->{note_followup}->follow_up_link;
1058 $self->{note} = SL::DB::Note->new();
1059 $self->{note_followup} = SL::DB::FollowUp->new();
1060 $self->{note_followup_link} = SL::DB::FollowUpLink->new();
1063 if ( $::form->{shipto_id} ) {
1064 $self->{shipto} = SL::DB::Shipto->new(shipto_id => $::form->{shipto_id})->load();
1066 if ( $self->{shipto}->trans_id != $self->{cv}->id ) {
1067 die($::locale->text('Error'));
1070 $self->{shipto} = SL::DB::Shipto->new();
1073 if ($self->is_customer) {
1074 if ( $::form->{additional_billing_address_id} ) {
1075 $self->{additional_billing_address} = SL::DB::AdditionalBillingAddress->new(id => $::form->{additional_billing_address_id})->load;
1076 die($::locale->text('Error')) if $self->{additional_billing_address}->customer_id != $self->{cv}->id;
1079 $self->{additional_billing_address} = SL::DB::AdditionalBillingAddress->new;
1083 if ( $::form->{contact_id} ) {
1084 $self->{contact} = SL::DB::Contact->new(cp_id => $::form->{contact_id})->load();
1086 if ( $self->{contact}->cp_cv_id != $self->{cv}->id ) {
1087 die($::locale->text('Error'));
1090 $self->{contact} = $self->_new_contact_object;
1094 sub _may_access_action {
1095 my ($self, $action) = @_;
1097 my $is_new = !$self->{cv} || !$self->{cv}->id;
1098 my $is_own_customer = !$is_new
1099 && $self->{cv}->is_customer
1100 && (SL::DB::Manager::Employee->current->id == $self->{cv}->salesman_id);
1101 my $has_edit_rights = $::auth->assert('customer_vendor_all_edit', 1);
1102 $has_edit_rights ||= $::auth->assert('customer_vendor_edit', 1) && ($is_new || $is_own_customer);
1103 my $needs_edit_rights = $action =~ m{^(?:add|save|delete|update)};
1105 $self->user_has_edit_rights($has_edit_rights);
1107 return 1 if $has_edit_rights;
1108 return 0 if $needs_edit_rights;
1113 my ($self, $action) = @_;
1115 if (!$self->_may_access_action($action)) {
1116 $::auth->deny_access;
1120 sub _create_customer_vendor {
1123 $self->{cv} = $self->_new_customer_vendor_object;
1124 $self->{cv}->currency_id($::instance_conf->get_currency_id());
1126 $self->{note} = SL::DB::Note->new();
1128 $self->{note_followup} = SL::DB::FollowUp->new();
1130 $self->{shipto} = SL::DB::Shipto->new();
1131 $self->{additional_billing_address} = SL::DB::AdditionalBillingAddress->new if $self->is_customer;
1133 $self->{contact} = $self->_new_contact_object;
1139 my $dbh = $::form->get_standard_dbh();
1143 $self->{all_business} = SL::DB::Manager::Business->get_all();
1145 $self->{all_employees} = SL::DB::Manager::Employee->get_all_sorted(query => [ deleted => 0 ]);
1146 $self->{all_auth_groups} = SL::DB::Manager::AuthGroup->get_all_sorted;
1148 $self->{all_greetings} = SL::DB::Manager::Greeting->get_all_sorted();
1149 if ($self->{cv}->id && $self->{cv}->greeting && !grep {$self->{cv}->greeting eq $_->description} @{$self->{all_greetings}}) {
1150 unshift @{$self->{all_greetings}}, (SL::DB::Greeting->new(description => $self->{cv}->greeting));
1153 $self->{all_contact_titles} = SL::DB::Manager::ContactTitle->get_all_sorted();
1154 foreach my $contact (@{ $self->{cv}->contacts }) {
1155 if ($contact->cp_title && !grep {$contact->cp_title eq $_->description} @{$self->{all_contact_titles}}) {
1156 unshift @{$self->{all_contact_titles}}, (SL::DB::ContactTitle->new(description => $contact->cp_title));
1160 $self->{all_contact_departments} = SL::DB::Manager::ContactDepartment->get_all_sorted();
1161 foreach my $contact (@{ $self->{cv}->contacts }) {
1162 if ($contact->cp_abteilung && !grep {$contact->cp_abteilung eq $_->description} @{$self->{all_contact_departments}}) {
1163 unshift @{$self->{all_contact_departments}}, (SL::DB::ContactDepartment->new(description => $contact->cp_abteilung));
1167 $self->{all_currencies} = SL::DB::Manager::Currency->get_all();
1169 $self->{all_languages} = SL::DB::Manager::Language->get_all();
1171 $self->{all_taxzones} = SL::DB::Manager::TaxZone->get_all_sorted();
1173 if ( $::instance_conf->get_vertreter() ) {
1178 my $business_ids = [
1181 selectall_hashref_query($::form, $dbh, $query)
1185 if ( $business_ids->[0] ) {
1186 $self->{all_salesman_customers} = SL::DB::Manager::Customer->get_all(query => [business_id => $business_ids]);
1188 $self->{all_salesman_customers} = [];
1191 $self->{all_salesmen} = SL::DB::Manager::Employee->get_all(query => [ or => [ id => $self->{cv}->salesman_id, deleted => 0 ] ]);
1194 $self->{all_payment_terms} = SL::DB::Manager::PaymentTerm->get_all_sorted(where => [ or => [ id => $self->{cv}->payment_id,
1197 $self->{all_delivery_terms} = SL::DB::Manager::DeliveryTerm->get_all();
1199 if ($self->{cv}->is_customer) {
1200 $self->{all_pricegroups} = SL::DB::Manager::Pricegroup->get_all_sorted(query => [ or => [ id => $self->{cv}->pricegroup_id, obsolete => 0 ] ]);
1203 $self->{contacts} = $self->{cv}->contacts;
1204 $self->{contacts} ||= [];
1206 $self->{shiptos} = $self->{cv}->shipto;
1207 $self->{shiptos} ||= [];
1209 if ($self->is_customer) {
1210 $self->{additional_billing_addresses} = $self->{cv}->additional_billing_addresses;
1211 $self->{additional_billing_addresses} ||= [];
1214 $self->{notes} = SL::DB::Manager::Note->get_all(
1216 trans_id => $self->{cv}->id,
1217 trans_module => 'ct',
1219 with_objects => ['follow_up'],
1222 if ( $self->is_vendor()) {
1223 $self->{open_items} = SL::DB::Manager::PurchaseInvoice->get_all_count(
1225 vendor_id => $self->{cv}->id,
1226 paid => {lt_sql => 'amount'},
1230 $self->{open_items} = SL::DB::Manager::Invoice->get_all_count(
1232 customer_id => $self->{cv}->id,
1233 paid => {lt_sql => 'amount'},
1238 if ( $self->is_vendor() ) {
1239 $self->{open_orders} = SL::DB::Manager::Order->get_all_count(
1241 vendor_id => $self->{cv}->id,
1246 $self->{open_orders} = SL::DB::Manager::Order->get_all_count(
1248 customer_id => $self->{cv}->id,
1254 if ($self->{cv}->number && $::instance_conf->get_webdav) {
1255 my $webdav = SL::Webdav->new(
1256 type => $self->is_customer ? 'customer'
1257 : $self->is_vendor ? 'vendor'
1259 number => $self->{cv}->number,
1261 my @all_objects = $webdav->get_all_objects;
1262 @{ $self->{template_args}->{WEBDAV} } = map { { name => $_->filename,
1264 link => File::Spec->catfile($_->full_filedescriptor),
1268 $self->{template_args} ||= {};
1270 $::request->{layout}->add_javascripts("$_.js") for qw (kivi.CustomerVendor kivi.File chart kivi.CustomerVendorTurnover follow_up);
1272 $self->_setup_form_action_bar;
1275 sub _setup_form_action_bar {
1278 my $no_rights = $self->user_has_edit_rights ? undef
1279 : $self->{cv}->is_customer ? t8("You don't have the rights to edit this customer.")
1280 : t8("You don't have the rights to edit this vendor.");
1282 for my $bar ($::request->layout->get('actionbar')) {
1287 submit => [ '#form', { action => "CustomerVendor/save" } ],
1288 checks => [ 'check_taxzone_and_ustid' ],
1289 accesskey => 'enter',
1290 disabled => $no_rights,
1293 t8('Save and Close'),
1294 submit => [ '#form', { action => "CustomerVendor/save_and_close" } ],
1295 checks => [ 'check_taxzone_and_ustid' ],
1296 disabled => $no_rights,
1298 ], # end of combobox "Save"
1301 action => [ t8('Workflow') ],
1303 t8('Save and AP Transaction'),
1304 submit => [ '#form', { action => "CustomerVendor/save_and_ap_transaction" } ],
1305 checks => [ 'check_taxzone_and_ustid' ],
1306 disabled => $no_rights,
1307 ]) x !!$self->is_vendor,
1309 t8('Save and AR Transaction'),
1310 submit => [ '#form', { action => "CustomerVendor/save_and_ar_transaction" } ],
1311 checks => [ 'check_taxzone_and_ustid' ],
1312 disabled => $no_rights,
1313 ]) x !$self->is_vendor,
1315 t8('Save and Invoice'),
1316 submit => [ '#form', { action => "CustomerVendor/save_and_invoice" } ],
1317 checks => [ 'check_taxzone_and_ustid' ],
1318 disabled => $no_rights,
1321 t8('Save and Order'),
1322 submit => [ '#form', { action => "CustomerVendor/save_and_order" } ],
1323 checks => [ 'check_taxzone_and_ustid' ],
1324 disabled => $no_rights,
1328 submit => [ '#form', { action => "CustomerVendor/save_and_rfq" } ],
1329 checks => [ 'check_taxzone_and_ustid' ],
1330 disabled => $no_rights,
1331 ]) x !!$self->is_vendor,
1333 t8('Save and Quotation'),
1334 submit => [ '#form', { action => "CustomerVendor/save_and_quotation" } ],
1335 checks => [ 'check_taxzone_and_ustid' ],
1336 disabled => $no_rights,
1337 ]) x !$self->is_vendor,
1338 ], # end of combobox "Workflow"
1342 submit => [ '#form', { action => "CustomerVendor/delete" } ],
1343 confirm => t8('Do you really want to delete this object?'),
1344 disabled => !$self->{cv}->id ? t8('This object has not been saved yet.')
1345 : !$self->is_orphaned ? t8('This object has already been used.')
1353 call => [ 'kivi.CustomerVendor.showHistoryWindow', $self->{cv}->id ],
1354 disabled => !$self->{cv}->id ? t8('This object has not been saved yet.') : undef,
1360 sub _prepare_cvar_configs_for_ajaj {
1361 my ($self, $cvars) = @_;
1366 my $result = { type => $cvar->config->type };
1368 if ($cvar->config->type eq 'number') {
1369 $result->{value} = $::form->format_amount(\%::myconfig, $cvar->value, -2);
1371 } elsif ($result->{type} eq 'date') {
1372 $result->{value} = $cvar->value ? $cvar->value->to_kivitendo : undef;
1374 } elsif ($result->{type} =~ m{customer|vendor|part}) {
1375 my $object = $cvar->value;
1376 my $method = $result->{type} eq 'part' ? 'description' : 'name';
1378 $result->{id} = int($cvar->number_value) || undef;
1379 $result->{value} = $object ? $object->$method // '' : '';
1382 $result->{value} = $cvar->value;
1385 ( $cvar->config->name => $result )
1387 } grep { $_->is_valid } @{ $cvars }
1391 sub normalize_name {
1394 # check if feature is enabled (select normalize_vc_names from defaults)
1395 return unless ($::instance_conf->get_normalize_vc_names);
1397 return unless $self->{cv};
1398 my $name = $self->{cv}->name;
1402 $self->{cv}->name($name);
1405 sub home_address_for_google_maps {
1408 my $address = $::instance_conf->get_address // '';
1409 $address =~ s{^\s+|\s+$|\r+}{}g;
1410 $address =~ s{\n+}{,}g;
1411 $address =~ s{\s+}{ }g;
1416 sub init_customer_models {
1419 SL::Controller::Helper::GetModels->new(
1420 controller => $self,
1421 model => 'Customer',
1424 by => 'customernumber',
1427 customernumber => t8('Customer Number'),
1432 sub init_vendor_models {
1435 SL::Controller::Helper::GetModels->new(
1436 controller => $self,
1440 by => 'vendornumber',
1443 vendornumber => t8('Vendor Number'),
1448 sub init_zugferd_settings {
1450 [ -1, t8('Use settings from client configuration') ],
1451 @SL::ZUGFeRD::customer_settings,
1455 sub _new_customer_vendor_object {
1458 my $class = 'SL::DB::' . ($self->is_vendor ? 'Vendor' : 'Customer');
1459 my $object = $class->new(
1462 custom_variables => [],
1465 $object->additional_billing_addresses([]) if $self->is_customer;
1470 sub _new_contact_object {
1473 return SL::DB::Contact->new(custom_variables => []);