1 package FS::ClientAPI::MyAccount;
3 use 5.008; #require 5.8+ for Time::Local 1.05+
5 use vars qw( $cache $DEBUG $me );
6 use subs qw( _cache _provision );
9 use Digest::MD5 qw(md5_hex);
10 use Digest::SHA qw(sha512_hex);
13 use Time::Local qw(timelocal_nocheck);
14 use Business::CreditCard 0.35;
17 use Spreadsheet::WriteExcel;
18 use OLE::Storage_Lite;
19 use FS::UI::Web::small_custview qw(small_custview); #less doh
21 use FS::UI::bytecount qw( display_bytecount );
24 use FS::Record qw(qsearch qsearchs dbh);
25 use FS::Msgcat qw(gettext);
26 use FS::Misc qw(card_types money_pretty);
27 use FS::Misc::DateTime qw(parse_datetime);
29 use FS::ClientAPI_SessionCache;
41 use FS::legacy_cust_bill;
42 use FS::cust_main_county;
46 use FS::acct_rt_transaction;
50 use FS::cust_location;
53 # for code organization
54 use FS::ClientAPI::MyAccount::contact;
55 use FS::ClientAPI::MyAccount::quotation;
58 $me = '[FS::ClientAPI::MyAccount]';
60 use vars qw( @cust_main_editable_fields @location_editable_fields );
61 @cust_main_editable_fields = qw(
62 first last company daytime night fax mobile
64 ss stateid stateid_state
66 @location_editable_fields = qw(
67 address1 address2 city county state zip country
71 BEGIN { #preload to reduce time customer_info takes
72 if ( $FS::TicketSystem::system ) {
73 warn "$me: initializing ticket system\n" if $DEBUG;
74 FS::TicketSystem->init();
79 $cache ||= new FS::ClientAPI_SessionCache( {
80 'namespace' => 'FS::ClientAPI::MyAccount',
87 my($context, $session, $custnum) = _custoragent_session_custnum($p);
88 #return { 'error' => $session } if $context eq 'error';
91 if ( $context eq 'customer' && $custnum ) {
93 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
96 $sth->execute($custnum) or die $sth->errstr;
98 $agentnum = $sth->fetchrow_arrayref->[0]
99 or die "no agentnum for custnum $custnum";
101 #} elsif ( $context eq 'agent' ) {
102 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
105 $p->{'agentnum'} = $agentnum;
107 my $conf = new FS::Conf;
109 #false laziness w/Signup.pm
111 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
113 if ( $skin_info_cache_agent ) {
115 warn "$me loading cached skin info for agentnum $agentnum\n"
120 warn "$me populating skin info cache for agentnum $agentnum\n"
123 $skin_info_cache_agent = {
124 'agentnum' => $agentnum,
125 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
126 qw( company_name date_format ) ),
127 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
128 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
129 text_color link_color vlink_color hlink_color alink_color
130 font title_color title_align title_size menu_bgcolor menu_fontsize
133 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
134 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
135 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo enable_payment_without_balance )
137 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
138 qw( title_left_image title_right_image
139 menu_top_image menu_body_image menu_bottom_image
142 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
143 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
144 qw( head body_header body_footer company_address ) ),
145 'money_char' => $conf->config("money_char") || '$',
146 'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
149 services.php Services
150 services.php My Services
151 services_new.php Order a new service
154 personal.php Personal Information
155 password.php Change Password
158 payment_cc.php Credit Card Payment
159 payment_ach.php Electronic Check Payment
160 payment_paypal.php PayPal Payment
161 payment_webpay.php Webpay Payments
164 usage_data.php Data usage
165 usage_cdr.php Call usage
167 tickets.php Help Desk
168 tickets.php Open Tickets
169 tickets_resolved.php Resolved Tickets
170 ticket_create.php Create a new ticket
178 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
182 #{ %$skin_info_cache_agent };
183 $skin_info_cache_agent;
190 my $conf = new FS::Conf;
194 'phone_login' => $conf->exists('selfservice_server-phone_login'),
195 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
196 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
197 'banner_image_md5' =>
198 md5_hex($conf->config_binary('selfservice-login_banner_image')),
205 sub login_banner_image {
207 my $conf = new FS::Conf;
208 my $image = $conf->config_binary('selfservice-login_banner_image');
210 'md5' => md5_hex($image),
215 #false laziness w/FS::ClientAPI::passwd::passwd
219 my $conf = new FS::Conf;
223 if ( $p->{'domain'} eq 'svc_phone'
224 && $conf->exists('selfservice_server-phone_login') ) {
226 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
227 return { error => 'Number not found.' } unless $svc_phone;
230 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
231 #return { error => 'Only primary user may log in.' }
232 # if $conf->exists('selfservice_server-primary_only')
233 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
235 return { error => 'Incorrect PIN.' }
236 unless $svc_phone->check_pin($p->{'password'});
240 } elsif ( $p->{email}
241 && (my $contact = FS::contact->by_selfservice_email($p->{email},'case_insensitive'))
244 my @customers = grep $_->selfservice_access, $contact->cust_contact;
247 foreach my $customer (@customers) {
248 if ($conf->exists('username-uppercase') || $conf->exists('username-uppercase', $customer->cust_main->agentnum)) {
249 my $check_contact = FS::contact->by_selfservice_email_custnum($p->{email}, $customer->custnum);
250 push @cust_contact, $customer if $check_contact;
252 else { push @cust_contact, $customer; }
255 return { error => 'Username '.$p->{email}.' not found!'}
256 unless @cust_contact;
258 return { error => 'Incorrect contact password.' }
259 unless $contact->authenticate_password($p->{'password'});
261 $session->{'contactnum'} = $contact->contactnum;
263 if ( scalar(@cust_contact) == 1 ) {
264 $session->{'custnum'} = $cust_contact[0]->custnum;
265 } elsif ( scalar(@cust_contact) ) {
266 $session->{'customers'} = { map { $_->custnum => $_->cust_main->name }
270 return { error => 'No customer self-service access for contact' }; #??
275 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
277 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
278 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
280 my @svc_acct = qsearch( 'svc_acct', { 'username' => $p->{'username'},
281 'domsvc' => $svc_domain->svcnum, }
284 if ( $conf->exists('selfservice_server-login_svcpart') ) {
285 my @svcpart = $conf->config('selfservice_server-login_svcpart');
286 @svc_acct = grep { my $svcpart = $_->cust_svc->svcpart;
287 scalar( grep( $_ eq $svcpart, @svcpart ) );
292 if ( $conf->exists('selfservice_server-primary_only') ) {
295 my $cust_svc = $_->cust_svc;
296 $cust_svc->cust_pkg->part_pkg->svcpart([qw( svc_acct svc_phone )])
297 == $cust_svc->svcpart
302 return { error => 'User not found.' } unless @svc_acct;
304 return { error => 'Multiple users.' } if scalar(@svc_acct) > 1;
306 my $svc_acct = $svc_acct[0];
308 if ( $conf->exists('selfservice_server-login_svcpart') ) {
309 my @svcpart = $conf->config('selfservice_server-login_svcpart');
310 my $svcpart = $svc_acct->cust_svc->svcpart;
311 return { error => 'Invalid user.' }
312 unless grep($_ eq $svcpart, @svcpart);
315 return { error => 'Incorrect password.' }
316 unless $svc_acct->check_password($p->{'password'});
324 $session->{'svcnum'} = $svc_x->svcnum;
326 my $cust_svc = $svc_x->cust_svc;
327 my $cust_pkg = $cust_svc->cust_pkg;
329 my $cust_main = $cust_pkg->cust_main;
330 $session->{'custnum'} = $cust_main->custnum;
331 if ( $conf->exists('pkg-balances') ) {
332 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
333 $cust_main->ncancelled_pkgs;
334 $session->{'pkgnum'} = $cust_pkg->pkgnum
335 if scalar(@cust_pkg) > 1;
339 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
340 #return { error => 'Only primary user may log in.' }
341 # if $conf->exists('selfservice_server-primary_only')
342 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
343 my $part_pkg = $cust_pkg->part_pkg;
344 return { error => 'Only primary user may log in.' }
345 if $conf->exists('selfservice_server-primary_only')
346 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
352 $session_id = sha512_hex(time(). {}. rand(). $$)
353 } until ( ! defined _cache->get($session_id) ); #just in case
355 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
356 _cache->set( $session_id, $session, $timeout );
358 return { 'error' => '',
359 'session_id' => $session_id,
366 my $skin_info = skin_info($p);
367 if ( $p->{'session_id'} ) {
368 _cache->remove($p->{'session_id'});
369 return { %$skin_info, 'error' => '' };
371 return { %$skin_info, 'error' => "Can't resume session" }; #better error message
378 my($context, $session, $custnum) = _custoragent_session_custnum($p);
379 return { 'error' => $session } if $context eq 'error';
381 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
382 or return { 'error' => "Service not found" };
384 $session->{'svcnum'} = $svc_acct->svcnum;
386 my $conf = new FS::Conf;
387 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
388 _cache->set( $p->{'session_id'}, $session, $timeout );
390 return { 'error' => '' };
396 my($context, $session, $custnum) = _custoragent_session_custnum($p);
397 return { 'error' => $session } if $context eq 'error';
399 $session->{'custnum'} = $p->{'custnum'}
400 if exists $session->{'customers'}{ $p->{'custnum'} };
402 my $conf = new FS::Conf;
403 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
404 _cache->set( $p->{'session_id'}, $session, $timeout );
406 return { 'error' => '',
407 %{ customer_info( { session_id=>$p->{'session_id'} } ) },
411 sub payment_gateway {
413 # takes a cust_main and a cust_payby entry, returns the payment_gateway
414 my $conf = new FS::Conf;
415 my $cust_main = shift;
416 my $cust_payby = shift;
417 return '' if ! FS::payby->realtime($cust_payby);
418 my $pg = $cust_main->agent->payment_gateway(
419 'method' => FS::payby->payby2bop($cust_payby),
428 my $conf = new FS::Conf;
430 my $info = skin_info($p);
432 use vars qw( $cust_paybys ); #cache for performance
433 unless ( $cust_paybys ) {
435 my %cust_paybys = map { $_ => 1 }
436 map { FS::payby->payby2payment($_) }
437 $conf->config('signup_server-payby');
439 $cust_paybys = [ keys %cust_paybys ];
442 $info->{'cust_paybys'} = $cust_paybys;
444 my($context, $session, $custnum) = _custoragent_session_custnum($p);
445 return { 'error' => $session } if $context eq 'error';
447 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } );
449 $info->{'hide_payment_fields'} = [
451 my $pg = $cust_main && payment_gateway($cust_main, $_);
452 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
453 } @{ $info->{cust_paybys} }
456 $info->{'self_suspend_reason'} =
457 $conf->config('selfservice-self_suspend_reason',
458 $cust_main ? $cust_main->agentnum : ''
461 $info->{'edit_ticket_subject'} =
462 $conf->exists('ticket_system-selfservice_edit_subject') &&
463 $cust_main && $cust_main->edit_subject;
465 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
467 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
470 'custnum' => $custnum,
471 'access_pkgnum' => $session->{'pkgnum'},
472 'access_svcnum' => $session->{'svcnum'},
479 my($context, $session, $custnum) = _custoragent_session_custnum($p);
480 return { 'error' => $session } if $context eq 'error';
484 my $conf = new FS::Conf;
485 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
487 # if ( $FS::TicketSystem::system ) {
488 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
489 # FS::TicketSystem->init();
492 if ( $custnum ) { #customer record
494 %return = ( %return, %{ customer_info_short($p) } );
496 #redundant with customer_info_short, but we need it for several things below
497 my $search = { 'custnum' => $custnum };
498 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
499 my $cust_main = qsearchs('cust_main', $search )
500 or return { 'error' => "customer_info: unknown custnum $custnum" };
502 my $list_tickets = list_tickets($p);
503 $return{'tickets'} = $list_tickets->{'tickets'};
505 if ( $session->{'pkgnum'} ) {
506 #XXX open invoices in the pkg-balances case
508 $return{'money_char'} = $conf->config("money_char") || '$';
511 invnum => $_->invnum,
512 date => time2str("%b %o, %Y", $_->_date),
514 charged => $_->charged,
516 } $cust_main->open_cust_bill;
517 $return{open_invoices} = \@open;
519 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
520 my $sth = dbh->prepare($sql) or die dbh->errstr;
521 $sth->execute($custnum) or die $sth->errstr;
522 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
523 $return{'last_invoice_date_pretty'} =
524 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
527 #customer_info_short always has nobalance on..
528 $return{small_custview} =
529 small_custview( $cust_main,
530 $return{countrydefault},
531 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
534 $return{has_ship_address} = $cust_main->has_ship_address;
535 $return{status} = $cust_main->status_label; #$cust_main->status; #better to break anyone obscurely testing for strings in self-service than to have to upgrade every front-end to get the new status to display
536 $return{statuscolor} = $cust_main->statuscolor;
537 $return{status_label} = $cust_main->status_label;
539 # compatibility: some places in selfservice use this to determine
540 # if there's a ship address
541 if ( $return{has_ship_address} ) {
542 $return{ship_last} = $cust_main->last;
543 $return{ship_first} = $cust_main->first;
546 if (scalar($conf->config('support_packages'))) {
547 my @support_services = ();
548 foreach ($cust_main->support_services) {
549 my $seconds = $_->svc_x->seconds || 0;
550 my $time_remaining = (($seconds < 0) ? '-' : '' ).
551 int(abs($seconds)/3600)."h".
552 sprintf("%02d",(abs($seconds)%3600)/60)."m";
553 my $cust_pkg = $_->cust_pkg;
556 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
557 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
558 push @support_services, { svcnum => $_->svcnum,
559 time => $time_remaining,
564 $return{support_services} = \@support_services;
567 if ( $conf->config('prepayment_discounts-credit_type') ) {
569 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
572 } elsif ( $session->{'svcnum'} ) { #no customer record
574 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
575 or die "unknown svcnum";
576 $return{name} = $svc_acct->email;
580 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
584 return { 'error' => '',
585 'custnum' => $custnum,
591 sub customer_info_short {
594 my($context, $session, $custnum) = _custoragent_session_custnum($p);
595 return { 'error' => $session } if $context eq 'error';
599 my $conf = new FS::Conf;
601 if ( $custnum ) { #customer record
603 my $search = { 'custnum' => $custnum };
604 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
605 my $cust_main = qsearchs('cust_main', $search )
606 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
608 $return{display_custnum} = $cust_main->display_custnum;
609 $return{max_invnum} = $cust_main->max_invnum;
611 if ( $session->{'pkgnum'} ) {
612 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
613 #next_bill_date from cust_pkg?
615 $return{balance} = $cust_main->balance;
616 $return{next_bill_date} = $cust_main->next_bill_date;
617 $return{next_bill_date_pretty} =
618 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
621 $return{balance_pretty} = money_pretty($return{balance});
623 $return{countrydefault} = scalar($conf->config('countrydefault'));
625 $return{small_custview} =
626 small_custview( $cust_main,
627 $return{countrydefault},
631 $return{first} = $cust_main->first;
632 $return{'last'} = $cust_main->get('last');
633 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
635 #none of these are terribly expensive if we want 'em...
636 for (@cust_main_editable_fields) {
637 $return{$_} = $cust_main->get($_);
639 $return{$_} = $cust_main->masked($_) for qw/ss stateid/;
641 #maybe a little more expensive, but it should be cached by now
642 for (@location_editable_fields) {
643 $return{$_} = $cust_main->bill_location->get($_)
644 if $cust_main->bill_locationnum;
645 $return{'ship_'.$_} = $cust_main->ship_location->get($_)
646 if $cust_main->ship_locationnum;
649 my @invoicing_list = $cust_main->invoicing_list;
650 $return{'invoicing_list'} =
651 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
652 $return{'postal_invoicing'} =
653 0 < ( grep { $_ eq 'POST' } @invoicing_list );
655 if ( $session->{'svcnum'} ) {
656 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
657 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
658 $return{'svcnum'} = $session->{'svcnum'};
661 } elsif ( $session->{'svcnum'} ) { #no customer record
663 #uuh, not supproted yet... die?
664 return { 'error' => 'customer_info_short not yet supported as agent' };
668 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
672 # this is here because this routine is called by both fs_ and ng_ main pages, where it appears
673 # it is not customer-specific, though it is only shown to authenticated customers
674 # it is not currently agent-specific, though at some point it might be
675 $return{'announcement'} = join(' ',$conf->config('selfservice-announcement')) || '';
677 return { 'error' => '',
678 'custnum' => $custnum,
683 sub customer_recurring {
686 my($context, $session, $custnum) = _custoragent_session_custnum($p);
687 return { 'error' => $session } if $context eq 'error';
691 my $conf = new FS::Conf;
693 my $search = { 'custnum' => $custnum };
694 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
695 my $cust_main = qsearchs('cust_main', $search )
696 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
698 $return{'display_recurring'} = [ $cust_main->display_recurring ];
700 return { 'error' => '',
701 'custnum' => $custnum,
706 sub billing_history {
709 my($context, $session, $custnum) = _custoragent_session_custnum($p);
710 return { 'error' => $session } if $context eq 'error';
712 return { 'error' => 'No customer' } unless $custnum;
714 my $search = { 'custnum' => $custnum };
715 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
716 my $cust_main = qsearchs('cust_main', $search )
717 or return { 'error' => "unknown custnum $custnum" };
721 if ( $session->{'pkgnum'} ) {
722 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
723 #next_bill_date from cust_pkg?
724 return { 'error' => 'No history for package' };
727 $return{balance} = $cust_main->balance;
728 $return{balance_pretty} = money_pretty($return{balance});
729 $return{next_bill_date} = $cust_main->next_bill_date;
730 $return{next_bill_date_pretty} =
731 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
734 my $conf = new FS::Conf;
736 $return{'history'} = [
737 $cust_main->payment_history(
738 'line_items' => $conf->exists('selfservice-billing_history-line_items'),
743 $return{'money_char'} = $conf->config("money_char") || '$',
751 my $session = _cache->get($p->{'session_id'})
752 or return { 'error' => "Can't resume session" }; #better error message
754 my $custnum = $session->{'custnum'}
755 or return { 'error' => "no customer record" };
757 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
758 or return { 'error' => "unknown custnum $custnum" };
760 my $conf = new FS::Conf;
763 return { 'error' => "You do not have authority to add a bank account" }
764 if (($p->{payby} eq "CHEK" || $p->{payby} eq "DCHEK") && $conf->exists('selfservice-ACH_info_readonly'));
766 ## get default cust_payby and change it. For old v3 selfservice that upgraded to v4. this is for v4 only
767 my ($cust_payby) = $cust_main->cust_payby();
769 $p->{'custpaybynum'} = $cust_payby->custpaybynum;
777 my $new = new FS::cust_main { $cust_main->hash };
779 $new->set( $_ => $p->{$_} )
780 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
782 if ( exists($p->{address1}) ) {
783 my $bill_location = FS::cust_location->new({
784 map { $_ => $p->{$_} } @location_editable_fields
786 # if this is unchanged from before, cust_main::replace will ignore it
787 $new->set('bill_location' => $bill_location);
790 if ( exists($p->{ship_address1}) ) {
791 my $ship_location = FS::cust_location->new({
792 map { $_ => $p->{"ship_$_"} } @location_editable_fields
794 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
795 # Selfservice unfortunately tries to indicate "same as billing
796 # address" by sending all fields empty. Did this ever work?
797 $ship_location = $cust_main->bill_location;
799 $new->set('ship_location' => $ship_location);
801 # but if it hasn't been passed in at all, leave ship_location alone--
802 # DON'T change it to match bill_location.
805 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
806 #false laziness with httemplate/edit/process/cust_main.cgi
807 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
808 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
810 @invoicing_list = $cust_main->invoicing_list;
813 my $error = $new->replace($cust_main, \@invoicing_list);
814 return { 'error' => $error } if $error;
817 return { 'error' => '' };
822 my $session = _cache->get($p->{'session_id'})
823 or return { 'error' => "Can't resume session" }; #better error message
829 my $conf = new FS::Conf;
830 use vars qw($payment_info); #cache for performance
831 unless ( $payment_info ) {
833 my %states = map { $_->state => 1 }
834 qsearch('cust_main_county', {
835 'country' => $conf->config('countrydefault') || 'US'
838 my %cust_paybys = map { $_ => 1 }
839 map { FS::payby->payby2payment($_) }
840 $conf->config('signup_server-payby');
842 my @cust_paybys = keys %cust_paybys;
846 #list all counties/states/countries
847 'cust_main_county' =>
848 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
850 #shortcut for one-country folks
852 [ sort { $a cmp $b } keys %states ],
854 'card_types' => card_types(),
856 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
857 'require_cvv' => $conf->exists('selfservice-require_cvv'),
858 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
860 'paytypes' => [ FS::cust_payby::paytypes ],
862 'paybys' => [ $conf->config('signup_server-payby') ],
863 'cust_paybys' => \@cust_paybys,
865 'stateid_label' => FS::Msgcat::_gettext('stateid'),
866 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
868 'show_ss' => $conf->exists('show_ss'),
869 'show_stateid' => $conf->exists('show_stateid'),
870 'show_paystate' => $conf->exists('show_bankstate'),
872 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
873 'ach_read_only' => $conf->exists('selfservice-ACH_info_readonly'),
883 my %return = %$payment_info;
885 delete $return{'cust_main_county'} if $p->{'omit_cust_main_county'};
887 my $custnum = $session->{'custnum'};
889 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
890 or return { 'error' => "unknown custnum $custnum" };
892 $return{'hide_payment_fields'} = [
894 my $pg = payment_gateway($cust_main, $_);
895 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
896 } @{ $return{cust_paybys} }
899 $return{balance} = $cust_main->balance; #XXX pkg-balances?
901 $return{$_} = $cust_main->bill_location->get($_)
902 for qw(address1 address2 city state zip);
904 # look for stored cust_payby info
905 # v3 to v4 upgrade would break change_pay because change_pay does not send payment_payby
906 # so for change_pay to work need to search for all allowed paybys and grab default payment account
907 my @search_payby = ();
908 @search_payby = ($p->{'payment_payby'} eq 'CARD') ? ('CARD','DCRD') : ('CHEK','DCHK')
909 if ($p->{'payment_payby'} =~ /^(CARD|CHEK)$/);
911 my ($cust_payby) = $cust_main->cust_payby(@search_payby);
913 $return{payby} = $cust_payby->payby;
914 $return{payname} = $cust_payby->payname
915 || ( $cust_main->first. ' '. $cust_main->get('last') );
916 $return{custpaybynum} = $cust_payby->custpaybynum;
918 if ( $cust_payby->payby =~ /^(CARD|DCRD)$/ ) {
919 $return{card_type} = cardtype($cust_payby->payinfo);
920 $return{payinfo} = $cust_payby->paymask;
922 @return{'month', 'year'} = $cust_payby->paydate_monthyear;
926 if ( $cust_payby->payby =~ /^(CHEK|DCHK)$/ ) {
927 my ($payinfo1, $payinfo2) = split '@', $cust_payby->paymask;
928 $return{payinfo1} = $payinfo1;
929 $return{payinfo2} = $payinfo2;
930 $return{paytype} = $cust_payby->paytype;
931 $return{paystate} = $cust_payby->paystate;
932 $return{payname} = $cust_payby->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
936 if ( $conf->config('prepayment_discounts-credit_type') ) {
938 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
941 #doubleclick protection
943 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
944 $return{paybatch} = $return{payunique}; #back compat
946 $return{credit_card_surcharge_percentage} = $conf->config('credit-card-surcharge-percentage', $cust_main->agentnum);
947 $return{credit_card_surcharge_flatfee} = $conf->config('credit-card-surcharge-flatfee', $cust_main->agentnum);
949 # A value for 'payby' must be defined in %return
950 $return{payby} = $return{paybys}->[0]
952 && ref $return{paybys}
953 && scalar @{ $return{paybys} };
955 return { 'error' => '',
961 #some false laziness with httemplate/process/payment.cgi - look there for
962 #ACH and CVV support stuff
964 sub validate_payment {
967 my $session = _cache->get($p->{'session_id'})
968 or return { 'error' => "Can't resume session" }; #better error message
970 my $custnum = $session->{'custnum'};
972 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
973 or return { 'error' => "unknown custnum $custnum" };
975 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
976 or return { 'error' => gettext('illegal_amount') };
978 return { error => 'Amount must be greater than 0' } unless $amount > 0;
980 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
981 #changing the hidden form values
982 my $conf = new FS::Conf;
983 my $fee_display = $conf->config('selfservice_process-display') || 'add';
984 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
985 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
986 if ( $fee_display eq 'add'
988 and ! $fee_skip_first || scalar($cust_main->cust_pay)
991 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
992 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
995 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
996 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
997 my $discount_term = $1;
999 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
1000 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
1003 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1004 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
1007 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1008 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
1011 $payunique = $paybatch if ! length($payunique) && length($paybatch);
1013 $p->{'payby'} ||= 'CARD';
1014 $p->{'payby'} =~ /^([A-Z]{4})$/
1015 or return { 'error' => "illegal_payby " . $p->{'payby'} };
1018 #false laziness w/process/payment.cgi
1021 my $replace_cust_payby;
1022 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
1024 $p->{'payinfo1'} =~ /^([\dx]+)$/
1025 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1027 $p->{'payinfo2'} =~ /^([\dx]+)$/
1028 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1030 $payinfo = $payinfo1. '@'. $payinfo2;
1033 foreach my $cust_payby ($cust_main->cust_payby('CHEK','DCHK')) {
1034 if ( $cust_payby->paymask eq $payinfo ) {
1035 $payinfo = $cust_payby->payinfo;
1036 $replace_cust_payby = $cust_payby;
1042 if ($conf->exists('selfservice-ACH_info_readonly') && !$achonfile) {
1043 return { 'error' => "You are not allowed to change your payment information." };
1046 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1048 $payinfo = $p->{'payinfo'};
1052 #more intelligent matching will be needed here if you change
1053 #card_masking_method and don't remove existing paymasks
1054 foreach my $cust_payby ($cust_main->cust_payby('CARD','DCRD')) {
1055 if ( $cust_payby->paymask eq $payinfo ) {
1056 $payinfo = $cust_payby->payinfo;
1057 $replace_cust_payby = $cust_payby;
1063 $payinfo =~ s/\D//g;
1064 $payinfo =~ /^(\d{13,19}|\d{8,9})$/
1065 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1069 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1070 return { 'error' => gettext('unknown_card_type') }
1071 if !$cust_main->tokenized($payinfo) && cardtype($payinfo) eq "Unknown";
1073 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1074 if ( cardtype($payinfo) eq 'American Express card' ) {
1075 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1076 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1079 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1080 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1083 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1084 return { 'error' => 'CVV2 is required' };
1085 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1086 return { 'error' => 'CVV2 is required' };
1090 die "unknown payby $payby";
1093 my %payby2fields = (
1094 'CARD' => [ qw( paystart_month paystart_year payissue payip
1095 address1 address2 city state zip country ) ],
1096 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1099 my %replace = ( 'replace' => $replace_cust_payby, );
1102 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1105 'cust_main' => $cust_main, #XXX or just custnum??
1106 'amount' => sprintf('%.2f', $amount),
1108 'payinfo' => $payinfo,
1109 'paymask' => FS::payinfo_Mixin->mask_payinfo( $payby, $payinfo ),
1110 'card_type' => $card_type,
1111 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1112 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1113 'month' => $p->{'month'},
1114 'year' => $p->{'year'},
1115 'payname' => $payname,
1116 'payunique' => $payunique,
1117 'paybatch' => $paybatch,
1118 'paycvv' => $paycvv,
1119 'payname' => $payname,
1120 'discount_term' => $discount_term,
1121 'pkgnum' => $session->{'pkgnum'},
1123 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1133 my $validate = validate_payment($p);
1134 return $validate if $validate->{'error'};
1136 my $conf = new FS::Conf;
1137 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1138 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1140 +{ map { $_=>$validate->{$_} }
1141 qw( card_type paymask payname paydate_pretty month year amount
1142 address1 address2 city state zip country
1148 sub process_stored_payment {
1151 my $session_id = $p->{'session_id'};
1153 my $payment_info = _cache->get( "payment_$session_id" )
1154 or return { 'error' => "Can't resume session" }; #better error message
1156 do_process_payment($payment_info);
1160 sub process_payment {
1163 my $payment_info = validate_payment($p);
1164 return $payment_info if $payment_info->{'error'};
1166 do_process_payment($payment_info);
1170 sub do_process_payment {
1171 my $validate = shift;
1173 my $cust_main = $validate->{'cust_main'};
1175 my $amount = delete $validate->{'amount'};
1178 my $payby = delete $validate->{'payby'};
1180 if ( $validate->{'save'} ) {
1183 foreach my $field ( qw( auto payinfo paymask payname payip ) ) {
1184 $saveopt{$field} = $validate->{$field};
1187 if ( $payby eq 'CARD' ) {
1188 my $bill_location = FS::cust_location->new({
1189 map { $_ => $validate->{$_} }
1190 qw(address1 address2 city state country zip)
1192 $saveopt{'bill_location'} = $bill_location;
1193 foreach my $field ( qw( paydate paystart_month paystart_year payissue ) ) {
1194 $saveopt{$field} = $validate->{$field};
1197 # stateid/stateid_state won't be saved, might be broken as of 4.x
1198 foreach my $field ( qw( paytype paystate ) ) {
1199 $saveopt{$field} = $validate->{$field};
1203 my $error = $cust_main->save_cust_payby(
1204 'payment_payby' => $payby,
1205 'replace' => $validate->{'replace'}, # cust_payby object to replace
1210 #no, this causes customers to process their payments again
1211 #return { 'error' => $error };
1212 #XXX just warn verosely for now so i can figure out how these happen in
1213 # the first place, eventually should redirect them to the "change
1214 #address" page but indicate if the payment processed?
1215 delete($validate->{'payinfo'}); #don't want to log this!
1216 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1218 "SAVEOPT: ".Dumper(\%saveopt)."\n".
1219 "CUST_MAIN: ". Dumper($cust_main)."\n".
1220 "PACKET: ". Dumper($validate)."\n";
1224 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1228 'paynum_ref' => \$paynum,
1231 return { 'error' => $error } if $error;
1233 #no error, so order the fee package if applicable...
1234 my $conf = new FS::Conf;
1235 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1236 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1238 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1240 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1242 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1243 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1246 #and generate an invoice for it now too
1247 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1248 return { 'error' => "payment processed and fee ordered successfully, but error billing fee: $error" }
1253 $cust_main->apply_payments;
1256 my $receipt_html = '';
1258 # currently supported for realtime CC only; send receipt data to SS
1259 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1262 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1265 <TD ALIGN="right">Payment#</TD>
1266 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1270 <TD ALIGN="right">Date</TD>
1272 <TD BGCOLOR="#FFFFFF"><B>! .
1273 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1279 <TD ALIGN="right">Amount</TD>
1280 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1285 <TD ALIGN="right">Payment method</TD>
1286 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1299 'amount' => sprintf('%.2f', $cust_pay->paid),
1300 'date' => $cust_pay->_date,
1301 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1302 'time_pretty' => time2str('%T', $cust_pay->_date),
1303 'auth_num' => $cust_pay->auth,
1304 'order_num' => $cust_pay->order_number,
1305 'receipt_html' => $receipt_html,
1312 'receipt_html' => '',
1319 sub realtime_collect {
1322 my $session = _cache->get($p->{'session_id'})
1323 or return { 'error' => "Can't resume session" }; #better error message
1325 my $custnum = $session->{'custnum'};
1327 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1328 or return { 'error' => "unknown custnum $custnum" };
1331 if ( $p->{'amount'} ) {
1332 $amount = $p->{'amount'};
1334 elsif ( $session->{'pkgnum'} ) {
1335 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1338 $amount = $cust_main->balance;
1341 my $error = $cust_main->realtime_collect(
1342 'method' => $p->{'method'},
1343 'amount' => $amount,
1344 'pkgnum' => $session->{'pkgnum'},
1345 'session_id' => $p->{'session_id'},
1349 return { 'error' => $error } unless ref( $error );
1351 return { 'error' => '', amount => $amount, %$error };
1354 sub start_thirdparty {
1356 my $session = _cache->get($p->{'session_id'})
1357 or return { 'error' => "Can't resume session" }; #better error message
1358 my $custnum = $session->{'custnum'};
1359 my $cust_main = FS::cust_main->by_key($custnum);
1361 my $amount = $p->{'amount'}
1362 or return { error => 'no amount' };
1364 my $result = $cust_main->create_payment(
1365 'method' => $p->{'method'},
1366 'amount' => $p->{'amount'},
1367 'pkgnum' => $session->{'pkgnum'},
1368 'session_id' => $p->{'session_id'},
1371 if ( ref($result) ) { # hashref or error
1374 return { error => $result };
1378 sub finish_thirdparty {
1380 my $session_id = delete $p->{'session_id'};
1381 my $session = _cache->get($session_id)
1382 or return { 'error' => "Can't resume session" };
1383 my $custnum = $session->{'custnum'};
1384 my $cust_main = FS::cust_main->by_key($custnum);
1386 if ( $p->{_cancel} ) {
1387 # customer backed out of making a payment
1388 return $cust_main->cancel_payment( $session_id );
1390 my $result = $cust_main->execute_payment( $session_id, %$p );
1391 if ( ref($result) ) {
1394 return { error => $result };
1398 sub process_payment_order_pkg {
1401 my $hr = process_payment($p);
1402 return $hr if $hr->{'error'};
1407 sub process_payment_order_renew {
1410 my $hr = process_payment($p);
1411 return $hr if $hr->{'error'};
1416 sub process_prepay {
1420 my $session = _cache->get($p->{'session_id'})
1421 or return { 'error' => "Can't resume session" }; #better error message
1425 my $custnum = $session->{'custnum'};
1427 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1428 or return { 'error' => "unknown custnum $custnum" };
1430 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1431 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1439 return { 'error' => $error } if $error;
1441 return { 'error' => '',
1442 'amount' => $amount,
1443 'seconds' => $seconds,
1444 'duration' => duration_exact($seconds),
1445 'upbytes' => $upbytes,
1446 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1447 'downbytes' => $downbytes,
1448 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1449 'totalbytes'=> $totalbytes,
1450 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1457 my $session = _cache->get($p->{'session_id'})
1458 or return { 'error' => "Can't resume session" }; #better error message
1460 my $custnum = $session->{'custnum'};
1462 my $invnum = $p->{'invnum'};
1464 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1465 'custnum' => $custnum } )
1466 or return { 'error' => "Can't find invnum" };
1470 return { 'error' => '',
1471 'invnum' => $invnum,
1472 'invoice_text' => join('', $cust_bill->print_text ),
1473 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1480 my $session = _cache->get($p->{'session_id'})
1481 or return { 'error' => "Can't resume session" }; #better error message
1483 my $custnum = $session->{'custnum'};
1485 my $invnum = $p->{'invnum'};
1487 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1488 'custnum' => $custnum } )
1489 or return { 'error' => "Can't find invnum" };
1493 return { 'error' => '',
1494 'invnum' => $invnum,
1495 'invoice_pdf' => $cust_bill->print_pdf({
1496 'unsquelch_cdr' => 1,
1497 'locale' => $p->{'locale'},
1503 sub legacy_invoice {
1505 my $session = _cache->get($p->{'session_id'})
1506 or return { 'error' => "Can't resume session" }; #better error message
1508 my $custnum = $session->{'custnum'};
1510 my $legacyinvnum = $p->{'legacyinvnum'};
1513 'legacyinvnum' => $legacyinvnum,
1514 'custnum' => $custnum,
1517 my $legacy_cust_bill =
1518 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1519 || qsearchs('legacy_cust_bill', \%hash )
1520 or return { 'error' => "Can't find legacyinvnum" };
1524 return { 'error' => '',
1525 'legacyinvnum' => $legacyinvnum,
1526 'legacyid' => $legacy_cust_bill->legacyid,
1527 'invoice_html' => $legacy_cust_bill->content_html,
1532 sub legacy_invoice_pdf {
1534 my $session = _cache->get($p->{'session_id'})
1535 or return { 'error' => "Can't resume session" }; #better error message
1537 my $custnum = $session->{'custnum'};
1539 my $legacyinvnum = $p->{'legacyinvnum'};
1541 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1542 'legacyinvnum' => $legacyinvnum,
1543 'custnum' => $custnum,
1544 }) or return { 'error' => "Can't find legacyinvnum" };
1548 return { 'error' => '',
1549 'legacyinvnum' => $legacyinvnum,
1550 'legacyid' => $legacy_cust_bill->legacyid,
1551 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1559 #sessioning for this? how do we get the session id to the backend invoice
1560 # template so it can add it to the link, blah
1563 if ( $p->{'invnum'} ) {
1564 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1565 or return { 'error' => 'unknown invnum' };
1566 $agentnum = $cust_bill->cust_main->agentnum;
1569 my $templatename = $p->{'template'} || $p->{'templatename'};
1571 #false laziness-ish w/view/cust_bill-logo.cgi
1573 my $conf = new FS::Conf;
1574 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1575 $templatename = "_$1";
1580 my $filename = "logo$templatename.png";
1582 return { 'error' => '',
1583 'logo' => $conf->config_binary($filename, $agentnum),
1584 'content_type' => 'image/png', #should allow gif, jpg too
1590 my $session = _cache->get($p->{'session_id'})
1591 or return { 'error' => "Can't resume session" }; #better error message
1593 my $custnum = $session->{'custnum'};
1595 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1596 or return { 'error' => "unknown custnum $custnum" };
1598 my $conf = new FS::Conf;
1600 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1602 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1607 #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1608 my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1609 my $owed = $_->owed;
1611 +{ 'invnum' => $_->invnum,
1612 '_date' => $_->_date,
1613 'date' => time2str("%b %o, %Y", $_->_date),
1614 'date_short' => time2str("%m-%d-%Y", $_->_date),
1615 'previous' => sprintf('%.2f', ($_->previous)[0]),
1616 'charged' => sprintf('%.2f', $_->charged),
1617 'owed' => sprintf('%.2f', $owed),
1618 'balance' => sprintf('%.2f', $balance),
1619 'lastpay' => @payments_and_credits
1620 ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1626 return { 'error' => '',
1627 'balance' => $cust_main->balance,
1628 'money_char' => $conf->config("money_char") || '$',
1629 'invoices' => $invoices,
1630 'legacy_invoices' => [
1632 +{ 'legacyinvnum' => $_->legacyinvnum,
1633 'legacyid' => $_->legacyid,
1634 '_date' => $_->_date,
1635 'date' => time2str("%b %o, %Y", $_->_date),
1636 'date_short' => time2str("%m-%d-%Y", $_->_date),
1637 'charged' => sprintf('%.2f', $_->charged),
1638 'has_content' => ( length($_->content_pdf)
1639 || length($_->content_html) ),
1649 my $session = _cache->get($p->{'session_id'})
1650 or return { 'error' => "Can't resume session" }; #better error message
1652 my $custnum = $session->{'custnum'};
1654 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1655 or return { 'error' => "unknown custnum $custnum" };
1657 return { 'error' => '',
1658 'balance' => $cust_main->balance,
1659 'money_char' => FS::Conf->new->config("money_char") || '$',
1660 'payments' => [ map $_->SSAPI_getinfo, $cust_main->cust_pay ],
1664 sub payment_receipt {
1666 my $session = _cache->get($p->{'session_id'})
1667 or return { 'error' => "Can't resume session" }; #better error message
1669 my $custnum = $session->{'custnum'};
1671 my $cust_pay = qsearchs('cust_pay', { 'custnum' => $custnum,
1672 'paynum' => $p->{'paynum'},
1675 or return { 'error' => "unknown payment ". $p->{'paynum'} };
1679 %{ $cust_pay->SSAPI_getinfo },
1686 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1687 return { 'error' => $session } if $context eq 'error';
1689 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1690 or return { 'error' => "unknown custnum $custnum" };
1694 my $cust_payby = $_;
1696 map { $_ => $cust_payby->$_ }
1697 qw( custpaybynum weight payby paymask paydate
1698 payname paystate paytype
1702 $cust_main->cust_payby
1710 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1711 return { 'error' => $session } if $context eq 'error';
1713 #XXX payinfo1 + payinfo2 for CHEK?
1714 #or take the opportunity to use separate, more well- named fields?
1715 if ($p->{'payby'} eq 'CHEK') {
1716 $p->{'payinfo1'} =~ /^([\dx]+)$/
1717 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1719 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
1720 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1722 $p->{'payinfo'} = $payinfo1. '@'. $payinfo2;
1724 elsif ($p->{'payby'} eq 'CARD') {
1725 $p->{paydate} = $p->{year} . '-' . $p->{month} . '-01' unless $p->{paydate};
1728 my $cust_payby = new FS::cust_payby {
1729 'custnum' => $custnum,
1730 map { $_ => $p->{$_} } qw( weight payby payinfo paycvv paydate payname
1731 paystate paytype payip
1735 my $error = $cust_payby->insert;
1737 return { 'error' => $error };
1739 return { 'custpaybynum' => $cust_payby->custpaybynum };
1747 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1748 return { 'error' => $session } if $context eq 'error';
1750 if ($p->{'payby'} eq 'CHEK') {
1751 $p->{'payinfo1'} =~ /^([\dx]+)$/
1752 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1754 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
1755 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1757 $p->{'payinfo'} = $payinfo1. '@'. $payinfo2;
1759 elsif ($p->{'payby'} eq 'CARD') {
1760 $p->{paydate} = $p->{year} . '-' . $p->{month} . '-01' unless $p->{paydate};
1763 my $cust_payby = qsearchs('cust_payby', {
1764 'custnum' => $custnum,
1765 'custpaybynum' => $p->{'custpaybynum'},
1767 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1769 my $cust_main = qsearchs( 'cust_main', {custnum => $cust_payby->custnum} )
1770 or return { 'error' => 'unknown custnum '.$cust_payby->custnum };
1773 qw( weight payby payinfo paycvv paydate payname paystate paytype payip )
1775 next unless exists($p->{$field});
1776 $cust_payby->set($field,$p->{$field});
1778 $cust_payby->set( 'paymask' => $cust_payby->mask_payinfo );
1780 # Update column if given a value, and the given value wasn't
1781 # the value generated by $cust_main->masked($column);
1782 $cust_main->set( $_, $p->{$_} )
1783 for grep{ $p->{$_} !~ /^x/i; }
1784 grep{ exists $p->{$_} }
1787 # Perform updates within a transaction
1788 local $FS::UID::AutoCommit = 0;
1790 if ( my $error = $cust_payby->replace || $cust_main->replace ) {
1792 return { error => $error };
1796 return { custpaybynum => $cust_payby->custpaybynum };
1802 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1803 return { 'error' => $session } if $context eq 'error';
1805 my $cust_payby = qsearchs('cust_payby', {
1806 'custnum' => $custnum,
1807 'custpaybynum' => $p->{'custpaybynum'},
1809 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1811 return { 'error' => $cust_payby->verify };
1818 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1819 return { 'error' => $session } if $context eq 'error';
1821 my $cust_payby = qsearchs('cust_payby', {
1822 'custnum' => $custnum,
1823 'custpaybynum' => $p->{'custpaybynum'},
1825 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1827 my $conf = new FS::Conf;
1828 if (($cust_payby->payby eq "DCHK" || $cust_payby->payby eq "CHEK") && $conf->exists('selfservice-ACH_info_readonly')) {
1829 return { 'error' => "Sorry you do not have permission to delete bank information." };
1832 return { 'error' => $cust_payby->delete };
1838 my $session = _cache->get($p->{'session_id'})
1839 or return { 'error' => "Can't resume session" }; #better error message
1841 my $custnum = $session->{'custnum'};
1843 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1844 or return { 'error' => "unknown custnum $custnum" };
1846 my @errors = $cust_main->cancel( 'quiet'=>1 );
1848 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1850 return { 'error' => $error };
1857 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1858 return { 'error' => $session } if $context eq 'error';
1860 my $pkg = qsearchs({
1861 'table' => 'cust_pkg',
1862 'addl_from' => 'LEFT JOIN part_pkg USING ( pkgpart )',
1864 'custnum' => $custnum,
1865 'pkgnum' => $p->{'pkgnum'},
1868 or return {'error' => 'unknown pkg num $pkgnum'};
1871 pkg_label => $pkg->pkg,
1872 pkgpart => $pkg->pkgpart,
1873 classnum => $pkg->classnum,
1881 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1882 return { 'error' => $session } if $context eq 'error';
1884 my $search = { 'custnum' => $custnum };
1885 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1886 my $cust_main = qsearchs('cust_main', $search )
1887 or return { 'error' => "unknown custnum $custnum" };
1889 my $conf = new FS::Conf;
1890 my $immutable = $conf->exists('selfservice_immutable-package');
1892 # the duplication below is necessary:
1893 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1894 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1895 # non-backwards-compatible change breaking the software of anyone using the API
1896 # instead of the stock selfservice
1897 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1898 if( $conf->exists('selfservice_server-view-wholesale') ) {
1899 return { 'svcnum' => $session->{'svcnum'},
1900 'custnum' => $custnum,
1901 'cust_pkg' => [ map {
1903 immutable => $immutable,
1904 part_pkg => [ map $_->hashref, $_->part_pkg ],
1906 [ map $_->hashref, $_->available_part_svc ],
1908 [ map { my $ref = { $_->hash,
1909 label => [ $_->label ],
1911 $ref->{_password} = $_->svc_x->_password
1912 if $context eq 'agent'
1913 && $conf->exists('agent-showpasswords')
1914 && $_->part_svc->svcdb eq 'svc_acct';
1919 } $cust_main->cust_pkg
1922 small_custview( $cust_main, $conf->config('countrydefault') ),
1923 'wholesale_view' => 1,
1924 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1925 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1926 'lnp' => $conf->exists('svc_phone-lnp'),
1930 { 'svcnum' => $session->{'svcnum'},
1931 'custnum' => $custnum,
1932 'cust_pkg' => [ map {
1933 my $primary_cust_svc = $_->primary_cust_svc;
1936 immutable => $immutable,
1937 pkg_label => $_->pkg_locale,
1938 status => $_->status,
1939 statuscolor => $_->statuscolor,
1941 [ map { $_->hashref }
1942 grep { $_->selfservice_access ne 'hidden' }
1943 $_->available_part_svc
1946 [ map { my $ref = { $_->hash,
1947 label => [ $_->label ],
1949 $ref->{_password} = $_->svc_x->_password
1950 if $context eq 'agent'
1951 && $conf->exists('agent-showpasswords')
1952 && $_->part_svc->svcdb eq 'svc_acct';
1953 $ref->{svchash} = { $_->svc_x->hash } if
1954 $_->part_svc->svcdb eq 'svc_phone';
1955 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1956 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1959 grep { $_->part_svc->selfservice_access ne 'hidden' }
1964 ? { $primary_cust_svc->hash,
1965 label => [ $primary_cust_svc->label ],
1966 finger => $primary_cust_svc->svc_x->finger, #uuh
1967 $primary_cust_svc->part_svc->hash,
1971 } $cust_main->ncancelled_pkgs
1974 small_custview( $cust_main, $conf->config('countrydefault') ),
1975 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1983 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1984 return { 'error' => $session } if $context eq 'error';
1986 my $conf = new FS::Conf;
1988 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1989 my $search = { 'custnum' => $custnum };
1990 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1991 my $cust_main = qsearchs('cust_main', $search )
1992 or return { 'error' => "unknown custnum $custnum" };
1994 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1995 if ( ! $pkgnum && $p->{'svcnum'} ) {
1996 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1997 $pkgnum = $cust_svc->pkgnum if $cust_svc;
2001 my @cust_pkg_usage = ();
2002 foreach my $cust_pkg ( $p->{'ncancelled'}
2003 ? $cust_main->ncancelled_pkgs
2004 : $cust_main->unsuspended_pkgs ) {
2005 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
2006 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
2007 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
2010 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
2013 foreach (@cust_pkg_usage) {
2014 my $part = $_->part_pkg_usage;
2015 my $tag = $part->description . ($part->shared ? 1 : 0);
2016 my $row = $usage_pools{$tag}
2017 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
2018 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
2019 $row->[2] += $part->minutes; # minutes total
2021 } # otherwise just leave them empty
2023 if ( $p->{'svcdb'} ) {
2024 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
2026 : ref($p->{'svcdb'}) eq 'ARRAY'
2027 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
2028 : { $p->{'svcdb'} => 1 };
2029 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
2032 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
2035 my @svcs; # stuff to return to the client
2036 my %bytes_used_total; # for _used columns only
2037 foreach my $cust_svc (@cust_svc) {
2038 my $svc_x = $cust_svc->svc_x;
2039 my($label, $value) = $cust_svc->label;
2040 my $part_svc = $cust_svc->part_svc;
2041 my $svcdb = $part_svc->svcdb;
2042 my $cust_pkg = $cust_svc->cust_pkg;
2043 my $part_pkg = $cust_pkg->part_pkg;
2046 'svcnum' => $cust_svc->svcnum,
2047 'display_svcnum' => $cust_svc->display_svcnum,
2051 'pkg_label' => $cust_pkg->pkg_locale,
2052 'pkg_status' => $cust_pkg->status,
2053 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
2056 # would it make sense to put this in a svc_* method?
2058 if (!$hide_usage and grep(/^$svcdb$/, qw(svc_acct svc_broadband)) and $part_svc->part_export_usage) {
2059 my $last_bill = $cust_pkg->last_bill || 0;
2061 my $up_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctInputOctets');
2062 my $down_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctOutputOctets');
2065 'seconds_used' => $cust_svc->seconds_since_sqlradacct($last_bill,$now),
2066 'upbytes_used' => display_bytecount($up_used),
2067 'downbytes_used' => display_bytecount($down_used),
2068 'totalbytes_used' => display_bytecount($up_used + $down_used)
2070 $bytes_used_total{'seconds_used'} += $hash{'seconds_used'};
2071 $bytes_used_total{'upbytes_used'} += $up_used;
2072 $bytes_used_total{'downbytes_used'} += $down_used;
2073 $bytes_used_total{'totalbytes_used'} += $up_used + $down_used;
2076 if ( $svcdb eq 'svc_acct' ) {
2077 foreach (qw(username email finger seconds)) {
2078 $hash{$_} = $svc_x->$_;
2084 'upbytes' => display_bytecount($svc_x->upbytes),
2085 'downbytes' => display_bytecount($svc_x->downbytes),
2086 'totalbytes' => display_bytecount($svc_x->totalbytes),
2088 'recharge_amount' => $part_pkg->option('recharge_amount',1),
2089 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
2090 'recharge_upbytes' =>
2091 display_bytecount($part_pkg->option('recharge_upbytes',1)),
2092 'recharge_downbytes' =>
2093 display_bytecount($part_pkg->option('recharge_downbytes',1)),
2094 'recharge_totalbytes' =>
2095 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
2100 } elsif ( $svcdb eq 'svc_dsl' ) {
2102 $hash{'phonenum'} = $svc_x->phonenum;
2103 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
2104 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
2105 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
2108 $hash{'name'} = $cust_main->name;
2110 # no usage to hide here
2112 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2114 # could potentially show lots of things...
2115 $hash{'outbound'} = 1;
2116 $hash{'inbound'} = 0;
2117 if ( $svcdb eq 'svc_phone' ) {
2118 if ( $part_pkg->plan eq 'voip_inbound' ) {
2119 $hash{'outbound'} = 0;
2120 $hash{'inbound'} = 1;
2121 } elsif ( $part_pkg->option('selfservice_inbound_format')
2122 or $conf->config('selfservice-default_inbound_cdr_format')
2124 $hash{'inbound'} = 1;
2127 foreach (qw(inbound outbound)) {
2128 # hmm...we can't filter by status here, because there might
2129 # not be cdr_terminations at all. have to go by date.
2130 # find all since the last bill date.
2131 # XXX cdr types? we are going to need them.
2133 my $sum_cdr = $svc_x->sum_cdrs(
2134 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
2135 'begin' => ($cust_pkg->last_bill || 0),
2137 'disable_charged_party' => 1,
2139 $hash{$_} = $sum_cdr->hashref;
2142 } # not hiding usage
2146 } # foreach $cust_svc
2148 foreach my $field (keys %bytes_used_total) {
2149 if ($field =~ /bytes/) {
2150 $bytes_used_total{$field} = display_bytecount($bytes_used_total{$field});
2155 'svcnum' => $session->{'svcnum'},
2156 'custnum' => $custnum,
2157 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
2158 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
2160 'bytes_used_total' => \%bytes_used_total,
2162 map { $usage_pools{$_} }
2166 'hide_usage' => $hide_usage,
2171 sub _customer_svc_x {
2172 my($custnum, $svcnum, $table) = (shift, shift, shift);
2173 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
2175 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2176 my $search = " AND custnum = $1";
2177 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2180 'table' => ($table || 'svc_acct'),
2181 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2182 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
2183 #'LEFT JOIN cust_main USING ( custnum ) ',
2184 'hashref' => $hashref,
2185 'extra_sql' => $search, #important
2190 sub svc_status_html {
2193 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2194 return { 'error' => $session } if $context eq 'error';
2196 #XXX only svc_dsl for now
2197 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
2198 or return { 'error' => "Service not found" };
2200 my $html = $svc_x->getstatus_html;
2202 return { 'html' => $html };
2206 sub svc_status_hash {
2209 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2210 return { 'error' => $session } if $context eq 'error';
2212 #XXX only svc_acct for now
2213 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2214 or return { 'error' => "Service not found" };
2216 my ( $html, $hashref ) = $svc_x->export_getstatus;
2221 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
2222 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
2223 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
2224 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
2225 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
2228 my( $p, $method ) = @_;
2230 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2231 return { 'error' => $session } if $context eq 'error';
2233 #XXX only svc_acct for now
2234 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2235 or return { 'error' => "Service not found" };
2237 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
2239 my $error = $svc_x->$method($p); #$p? returns error?
2240 return { 'error' => $error } if $error;
2242 return {}; #? { 'error' => '' }
2246 sub acct_forward_info {
2249 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2250 return { 'error' => $session } if $context eq 'error';
2252 my $svc_forward = _customer_svc_x( $custnum,
2253 { 'srcsvc' => $p->{'svcnum'} },
2256 or return { 'error' => '',
2260 return { 'error' => '',
2261 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2266 sub process_acct_forward {
2268 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2269 return { 'error' => $session } if $context eq 'error';
2271 my $old = _customer_svc_x( $custnum,
2272 { 'srcsvc' => $p->{'svcnum'} },
2276 if ( $p->{'dst'} eq '' ) {
2278 my $error = $old->delete;
2279 return { 'error' => $error };
2281 return { 'error' => '' };
2284 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2285 'dst' => $p->{'dst'},
2290 $new->svcnum($old->svcnum);
2291 my $cust_svc = $old->cust_svc;
2292 $new->svcpart($old->svcpart);
2293 $new->pkgnuym($old->pkgnum);
2294 $error = $new->replace($old);
2296 my $conf = new FS::Conf;
2297 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2299 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2300 or return { 'error' => 'No service' }; #how would we even get here?
2302 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2304 $error = $new->insert;
2307 return { 'error' => $error };
2311 sub list_dsl_devices {
2314 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2315 return { 'error' => $session } if $context eq 'error';
2317 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2318 or return { 'error' => "Service not found" };
2321 'devices' => [ map {
2322 +{ 'mac_addr' => $_->mac_addr };
2323 } $svc_dsl->dsl_device
2329 sub add_dsl_device {
2332 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2333 return { 'error' => $session } if $context eq 'error';
2335 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2336 or return { 'error' => "Service not found" };
2338 return { 'error' => 'No MAC address supplied' }
2339 unless length($p->{'mac_addr'});
2341 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2342 'mac_addr' => scalar($p->{'mac_addr'}),
2344 my $error = $dsl_device->insert;
2345 return { 'error' => $error };
2349 sub delete_dsl_device {
2352 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2353 return { 'error' => $session } if $context eq 'error';
2355 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2356 or return { 'error' => "Service not found" };
2358 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2359 'mac_addr' => scalar($p->{'mac_addr'}),
2362 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2364 my $error = $dsl_device->delete;
2365 return { 'error' => $error };
2371 _usage_details( \&_port_graph, $p,
2372 'svcdb' => 'svc_port',
2377 my($svc_port, $begin, $end) = @_;
2379 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2380 push @usage, { 'png' => $pngOrError };
2384 sub _list_svc_usage {
2385 my($svc_acct, $begin, $end) = @_;
2387 foreach my $part_export (
2388 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2389 qw( sqlradius sqlradius_withdomain )
2391 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2396 sub list_svc_usage {
2397 _usage_details(\&_list_svc_usage, @_);
2400 sub _list_support_usage {
2401 my($svc_acct, $begin, $end) = @_;
2403 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2404 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2406 push @usage, { 'seconds' => $_->seconds,
2407 'support' => $_->support,
2408 '_date' => $_->_date,
2409 'id' => $_->transaction_id,
2410 'creator' => $_->creator,
2411 'subject' => $_->subject,
2412 'status' => $_->status,
2413 'ticketid' => $_->ticketid,
2419 sub list_support_usage {
2420 _usage_details(\&_list_support_usage, @_);
2423 sub _list_cdr_usage {
2424 # XXX CDR type support...
2425 # XXX any way to do a paged search on this?
2426 # we have to return the results all at once...
2427 my($svc_x, $begin, $end, %opt) = @_;
2428 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2432 'disable_charged_party' => 1,
2437 sub list_cdr_usage {
2439 _usage_details( \&_list_cdr_usage, $p );
2442 sub _usage_details {
2443 my($callback, $p, %opt) = @_;
2444 my $conf = FS::Conf->new;
2446 if ( $conf->exists('selfservice_hide-usage') ) {
2447 return { 'error' => 'Viewing usage is not allowed.' };
2450 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2451 return { 'error' => $session } if $context eq 'error';
2453 my $search = { 'svcnum' => $p->{'svcnum'} };
2454 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2456 my $cust_svc = qsearchs( 'cust_svc', $search );
2457 return { 'error' => 'No service selected in list_svc_usage' }
2460 my $svc_x = $cust_svc->svc_x;
2461 my $svcdb = $svc_x->table;
2462 my $cust_pkg = $cust_svc->cust_pkg;
2463 my $freq = $cust_pkg->part_pkg->freq;
2466 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2468 if ( $p->{inbound} ) {
2469 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2470 || $conf->config('selfservice-default_inbound_cdr_format')
2471 || 'source_default';
2472 $callback_opt{inbound} = 1;
2474 $format = $cust_pkg->part_pkg->option('selfservice_format')
2475 || $conf->config('selfservice-default_cdr_format')
2479 $callback_opt{format} = $format;
2480 $callback_opt{use_clid} = 1;
2481 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2484 my $start = $cust_pkg->setup;
2485 #my $end = $cust_pkg->bill; # or time?
2488 unless ( $p->{beginning} ) {
2489 $p->{beginning} = $cust_pkg->last_bill;
2490 $p->{ending} = $end;
2493 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2494 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2496 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2500 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2501 # ugly kludge, I know
2502 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2503 if (defined $delete_col) {
2504 delete($_->[$delete_col]) foreach ($header, @usage);
2508 #kinda false laziness with FS::cust_main::bill, but perhaps
2509 #we should really change this bit to DateTime and DateTime::Duration
2511 #change this bit to use Date::Manip? CAREFUL with timezones (see
2512 # mailing list archive)
2513 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2514 (localtime($p->{ending}) )[0,1,2,3,4,5];
2515 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2516 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2518 if ( $freq =~ /^\d+$/ ) {
2520 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2522 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2523 } elsif ( $freq =~ /^(\d+)w$/ ) {
2525 $nmday += $weeks * 7;
2526 $pmday -= $weeks * 7;
2527 } elsif ( $freq =~ /^(\d+)d$/ ) {
2531 } elsif ( $freq =~ /^(\d+)h$/ ) {
2536 return { 'error' => "unparsable frequency: ". $freq };
2539 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2540 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2544 'svcnum' => $p->{svcnum},
2545 'beginning' => $p->{beginning},
2546 'ending' => $p->{ending},
2547 'inbound' => $p->{inbound},
2548 'previous' => ($previous > $start) ? $previous : $start,
2549 'next' => ($next < $end) ? $next : $end,
2550 'header' => $header,
2558 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2559 return { 'error' => $session } if $context eq 'error';
2561 my $search = { 'custnum' => $custnum };
2562 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2563 my $cust_main = qsearchs('cust_main', $search )
2564 or return { 'error' => "unknown custnum $custnum" };
2566 my $status = $cust_main->status;
2568 my %order_pkg_options = ();
2569 if ( $p->{locationnum} > 0 ) {
2570 $order_pkg_options{locationnum} = delete($p->{locationnum});
2571 } elsif ( $p->{address1} ) {
2572 $order_pkg_options{'cust_location'} = new FS::cust_location {
2573 map { $_ => $p->{$_} }
2574 qw( address1 address2 city county state zip country )
2578 #false laziness w/ClientAPI/Signup.pm
2580 my $cust_pkg = new FS::cust_pkg ( {
2581 'custnum' => $custnum,
2582 'pkgpart' => $p->{'pkgpart'},
2583 'quantity' => $p->{'quantity'} || 1,
2585 my $error = $cust_pkg->check;
2586 return { 'error' => $error } if $error;
2589 unless ( $p->{'svcpart'} eq 'none' ) {
2593 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2595 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2596 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2597 $svcdb = $part_svc->svcdb;
2599 $svcdb = 'svc_acct';
2601 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2604 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2605 'svc_domain' => [ qw( domain ) ],
2606 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2607 'svc_external' => [ qw( id title ) ],
2608 'svc_pbx' => [ qw( id title ) ],
2611 my $svc_x = "FS::$svcdb"->new( {
2612 'svcpart' => $svcpart,
2613 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2616 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2619 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2620 my $acct_snarf = new FS::acct_snarf ( {
2621 'machine' => $p->{"snarf_machine$snarfnum"},
2622 'protocol' => $p->{"snarf_protocol$snarfnum"},
2623 'username' => $p->{"snarf_username$snarfnum"},
2624 '_password' => $p->{"snarf_password$snarfnum"},
2627 push @acct_snarf, $acct_snarf;
2629 $svc_x->child_objects( \@acct_snarf );
2632 my $y = $svc_x->setdefault; # arguably should be in new method
2633 return { 'error' => $y } if $y && !ref($y);
2635 $error = $svc_x->check;
2636 return { 'error' => $error } if $error;
2642 $error = $cust_main->order_pkg(
2643 'cust_pkg' => $cust_pkg,
2648 return { 'error' => $error } if $error;
2650 my $conf = new FS::Conf;
2651 if ( $conf->exists('signup_server-realtime') ) {
2653 my $bill_error = _do_bop_realtime( $cust_main, $status, 'collect'=>$p->{run_bill_events} );
2656 $cust_pkg->cancel('quiet'=>1);
2659 $cust_pkg->reexport;
2663 $cust_pkg->reexport;
2666 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2668 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2675 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2676 return { 'error' => $session } if $context eq 'error';
2678 my $conf = new FS::Conf;
2679 my $immutable = $conf->exists('selfservice_immutable-package');
2680 return { 'error' => "Package modification disabled" } if $immutable;
2682 my $search = { 'custnum' => $custnum };
2683 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2684 my $cust_main = qsearchs('cust_main', $search )
2685 or return { 'error' => "unknown custnum $custnum" };
2687 my $status = $cust_main->status;
2688 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2689 or return { 'error' => "unknown package $p->{pkgnum}" };
2691 #if someone does need self-service package change of suspended packages,
2692 # figure out how to be more discriminating
2693 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2694 if $cust_pkg->status eq 'suspended';
2696 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2697 'quantity' => $p->{'quantity'} || 1,
2700 my $new_pkg = qsearchs('part_pkg', { 'pkgpart' => $p->{pkgpart} } )
2701 or return { 'error' => "unknown package $p->{pkgpart}" };
2703 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2704 unless ref($err_or_cust_pkg);
2707 if ( $conf->exists('signup_server-realtime') ) {
2709 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2712 $err_or_cust_pkg->suspend;
2715 $err_or_cust_pkg->reexport;
2719 $err_or_cust_pkg->reexport;
2722 return { error => '', pkg => $new_pkg->pkg, pkgnum => $err_or_cust_pkg->pkgnum };
2726 sub order_recharge {
2729 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2730 return { 'error' => $session } if $context eq 'error';
2732 my $search = { 'custnum' => $custnum };
2733 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2734 my $cust_main = qsearchs('cust_main', $search )
2735 or return { 'error' => "unknown custnum $custnum" };
2737 my $status = $cust_main->status;
2738 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2739 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2741 my $svc_x = $cust_svc->svc_x;
2742 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2745 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2746 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2747 recharge_totalbytes );
2748 my $amount = $part_pkg->option('recharge_amount', 1);
2750 my ($l, $v, $d) = $cust_svc->label; # blah
2751 my $pkg = "Recharge $v";
2753 my $bill_error = $cust_main->charge($amount, $pkg,
2754 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2755 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2756 $part_pkg->taxclass); #meh
2758 my $conf = new FS::Conf;
2759 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2761 $bill_error = _do_bop_realtime( $cust_main, $status );
2766 my $error = $svc_x->recharge (\%vhash);
2767 return { 'error' => $error } if $error;
2771 my $error = $bill_error;
2772 $error ||= $svc_x->recharge (\%vhash);
2773 return { 'error' => $error } if $error;
2776 return { error => '', svc => $cust_svc->part_svc->svc };
2780 sub _do_bop_realtime {
2781 my ($cust_main, $status, %opt) = @_;
2783 my $old_balance = $cust_main->balance;
2786 my $bill_error = $cust_main->bill(
2787 'return_bill' => \@cust_bill,
2790 $bill_error ||= $cust_main->apply_payments_and_credits;
2792 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1);
2794 if ( $cust_main->balance > $old_balance
2795 && $cust_main->balance > 0
2796 && ( $cust_main->has_cust_payby_auto || $status eq 'suspended' )
2799 unless ( $opt{'no_invoice_void'} ) {
2801 #this used to apply a credit, but now we can void invoices...
2802 foreach my $cust_bill (@cust_bill) {
2803 my $voiderror = $cust_bill->void('automatic payment failed');
2804 warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2809 return { 'error' => '_decline', 'bill_error' => $bill_error };
2812 if ( $opt{'collect'} ) {
2813 my $collect_error = $cust_main->collect();
2814 return { 'error' => '_decline', 'bill_error' => $collect_error }
2815 if $collect_error; #?
2824 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2825 return { 'error' => $session } if $context eq 'error';
2827 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2828 or return { 'error' => "unknown custnum $custnum" };
2830 my @cust_pkg = sort { $a->bill <=> $b->bill }
2831 grep { $_->part_pkg->freq ne '0' }
2832 $cust_main->ncancelled_pkgs;
2834 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2836 my $total = $cust_main->balance;
2839 my $bill = $_->bill;
2840 $total += $_->part_pkg->base_recur($_, \$bill);
2841 my $renew_date = $_->part_pkg->add_freq($_->bill);
2843 'pkgnum' => $_->pkgnum,
2844 'amount' => sprintf('%.2f', $total),
2845 'bill_date' => $_->bill,
2846 'bill_date_pretty' => time2str('%x', $_->bill),
2847 'renew_date' => $renew_date,
2848 'renew_date_pretty' => time2str('%x', $renew_date),
2849 'expire_date' => $_->expire,
2850 'expire_date_pretty' => time2str('%x', $_->expire),
2855 return { 'dates' => \@array };
2859 sub payment_info_renew_info {
2861 my $renew_info = renew_info($p);
2862 my $payment_info = payment_info($p);
2863 return { %$renew_info,
2871 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2872 return { 'error' => $session } if $context eq 'error';
2874 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2875 or return { 'error' => "unknown custnum $custnum" };
2877 my $date = $p->{'date'};
2881 #freeside-daily -n -d $date fs_daily $custnum
2882 $cust_main->bill_and_collect( 'time' => $date,
2883 'invoice_time' => $now,
2884 'actual_time' => $now,
2885 'check_freq' => '1d',
2888 return { 'error' => '' };
2894 my $session = _cache->get($p->{'session_id'})
2895 or return { 'error' => "Can't resume session" }; #better error message
2897 my $custnum = $session->{'custnum'};
2899 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2900 or return { 'error' => "unknown custnum $custnum" };
2902 my $conf = new FS::Conf;
2904 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2905 or return { 'error' => 'Permission denied' };
2907 my $pkgnum = $p->{'pkgnum'};
2909 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2910 'pkgnum' => $pkgnum, } )
2911 or return { 'error' => "unknown pkgnum $pkgnum" };
2913 my $error = $cust_pkg->suspend(reason => $reasonnum);
2914 return { 'error' => $error };
2920 my $session = _cache->get($p->{'session_id'})
2921 or return { 'error' => "Can't resume session" }; #better error message
2923 my $custnum = $session->{'custnum'};
2924 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2925 or return { 'error' => "unknown custnum $custnum" };
2927 my $pkgnum = $p->{'pkgnum'};
2928 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2929 'pkgnum' => $pkgnum, } )
2930 or return { 'error' => "unknown pkgnum $pkgnum" };
2932 my $error = $cust_pkg->cancel( 'quiet' => 1,
2933 'date' => $p->{'date'},
2935 return { 'error' => $error };
2938 sub provision_phone {
2941 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2943 #editing an existing phone number
2944 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2945 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2946 return { 'error' => $session } if $context eq 'error';
2948 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2949 return { 'error' => 'service not found' } unless $svc_phone;
2950 return { 'error' => 'invalid svcnum' }
2951 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2953 $svc_phone->email($p->{'email'})
2954 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2955 $svc_phone->forwarddst($p->{'forwarddst'})
2956 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2957 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2958 return { 'error' => $svc_phone->replace };
2962 unless ( $p->{'lnp'} ) {
2963 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2964 $p->{'lnp_status'} = "portingin";
2965 return _provision( 'FS::svc_phone',
2966 [qw(lnp_desired_due_date lnp_other_provider
2967 lnp_other_provider_account phonenum countrycode lnp_status)],
2968 [qw(phonenum countrycode)],
2974 # single DID order (the usual case)
2975 unless (scalar(@bulkdid)) {
2976 return _provision( 'FS::svc_phone',
2977 [qw(phonenum countrycode)],
2978 [qw(phonenum countrycode)],
2984 # bulk DID order case
2986 foreach my $did ( @bulkdid ) {
2987 $did =~ s/[^0-9]//g;
2988 $error = _provision( 'FS::svc_phone',
2989 [qw(phonenum countrycode)],
2990 [qw(phonenum countrycode)],
2992 'pkgnum' => $p->{'pkgnum'},
2993 'svcpart' => $p->{'svcpart'},
2995 'countrycode' => $p->{'countrycode'},
2996 'session_id' => $p->{'session_id'},
2999 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
3001 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
3006 warn "provision_pbx called\n"
3009 warn "provision_pbx calling _provision\n"
3011 _provision( 'FS::svc_pbx',
3012 [qw(id title max_extensions max_simultaneous ip_addr)],
3013 [qw(id title max_extensions max_simultaneous ip_addr)],
3019 sub provision_acct {
3021 warn "provision_acct called\n"
3024 return { 'error' => gettext('passwords_dont_match') }
3025 if $p->{'_password'} ne $p->{'_password2'};
3026 return { 'error' => gettext('empty_password') }
3027 unless length($p->{'_password'});
3029 if ($p->{'domsvc'}) {
3030 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
3031 qw ( svcpart pkgnum ) );
3032 return { 'error' => gettext('invalid_domain') }
3033 unless ($domains{$p->{'domsvc'}});
3036 warn "provision_acct calling _provision\n"
3038 _provision( 'FS::svc_acct',
3039 [qw(username _password domsvc)],
3040 [qw(username _password domsvc)],
3046 sub provision_external {
3048 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
3049 _provision( 'FS::svc_external',
3057 sub provision_forward {
3059 _provision( 'FS::svc_forward',
3060 ['srcsvc','src','dstsvc','dst'],
3067 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
3068 warn "_provision called for $class\n"
3071 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3072 return { 'error' => $session } if $context eq 'error';
3074 my $search = { 'custnum' => $custnum };
3075 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3076 my $cust_main = qsearchs('cust_main', $search )
3077 or return { 'error' => "unknown custnum $custnum" };
3079 my $pkgnum = $p->{'pkgnum'};
3081 warn "searching for custnum $custnum pkgnum $pkgnum\n"
3083 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3084 'pkgnum' => $pkgnum,
3086 or return { 'error' => "unknown pkgnum $pkgnum" };
3088 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
3090 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
3091 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
3093 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
3094 if $class ne 'FS::'. $part_svc->svcdb;
3096 warn "creating $class record\n"
3098 my $svc_x = $class->new( {
3099 'pkgnum' => $p->{'pkgnum'},
3100 'svcpart' => $p->{'svcpart'},
3101 map { $_ => $p->{$_} } @$fields
3104 my %insert_args = ();
3105 #i shouldn't be a special case here (pass an option or something)
3106 if ( $class eq 'FS::svc_phone'
3107 && grep length($p->{$_}), @location_editable_fields
3110 $insert_args{'cust_location'} = new FS::cust_location {
3111 map { $_ => $p->{$_} } @location_editable_fields
3115 warn "inserting $class record\n"
3117 my $error = $svc_x->insert(%insert_args);
3120 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
3122 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
3125 my $return = { 'svc' => $part_svc->svc,
3127 map { $_ => $svc_x->get($_) } @$return_fields
3129 warn "_provision returning ". Dumper($return). "\n"
3138 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3139 return { 'error' => $session } if $context eq 'error';
3141 my $search = { 'custnum' => $custnum };
3142 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3143 my $cust_main = qsearchs('cust_main', $search )
3144 or return { 'error' => "unknown custnum $custnum" };
3146 my $pkgnum = $p->{'pkgnum'};
3148 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3149 'pkgnum' => $pkgnum,
3151 or return { 'error' => "unknown pkgnum $pkgnum" };
3153 my $svcpart = $p->{'svcpart'};
3155 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
3156 'svcpart' => $svcpart, } )
3157 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
3158 my $part_svc = $pkg_svc->part_svc;
3160 my $conf = new FS::Conf;
3163 'svc' => $part_svc->svc,
3164 'svcdb' => $part_svc->svcdb,
3165 'pkgnum' => $pkgnum,
3166 'svcpart' => $svcpart,
3167 'custnum' => $custnum,
3169 'security_phrase' => 0, #XXX !
3170 'svc_acct_pop' => [], #XXX !
3172 'init_popstate' => '',
3177 small_custview( $cust_main, $conf->config('countrydefault') ),
3181 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
3182 && $ret->{'svcdb'} eq 'svc_phone') {
3183 $ret->{'svcnum'} = $p->{'svcnum'};
3184 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
3185 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
3186 $ret->{'email'} = $svc_phone->email;
3187 $ret->{'forwarddst'} = $svc_phone->forwarddst;
3191 if ($ret->{'svcdb'} eq 'svc_forward') {
3192 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
3198 sub unprovision_svc {
3201 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3202 return { 'error' => $session } if $context eq 'error';
3204 my $search = { 'custnum' => $custnum };
3205 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3206 my $cust_main = qsearchs('cust_main', $search )
3207 or return { 'error' => "unknown custnum $custnum" };
3209 my $svcnum = $p->{'svcnum'};
3211 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
3212 or return { 'error' => "unknown svcnum $svcnum" };
3214 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
3215 unless $cust_svc->cust_pkg->custnum == $custnum;
3217 my $conf = new FS::Conf;
3219 return { 'svc' => $cust_svc->part_svc->svc,
3220 'error' => $cust_svc->cancel,
3222 small_custview( $cust_main, $conf->config('countrydefault') ),
3227 sub myaccount_passwd {
3229 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3230 return { 'error' => $session } if $context eq 'error';
3232 return { 'error' => "New passwords don't match." }
3233 if $p->{'new_password'} ne $p->{'new_password2'};
3235 return { 'error' => 'Enter new password' }
3236 unless length($p->{'new_password'});
3238 #my $search = { 'custnum' => $custnum };
3239 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3240 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3241 my $search = " AND custnum = $1";
3242 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3244 my $svc_acct = qsearchs( {
3245 'table' => 'svc_acct',
3246 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3247 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3248 'LEFT JOIN cust_main USING ( custnum ) ',
3249 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3250 'extra_sql' => $search, #important
3252 or return { 'error' => "Service not found" };
3256 my $conf = new FS::Conf;
3258 return { 'error' => 'Incorrect current password.' }
3259 if ( exists($p->{'old_password'})
3260 || $conf->exists('selfservice-password_change_oldpass')
3262 && ! $svc_acct->check_password($p->{'old_password'});
3264 $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3265 || $svc_acct->set_password($p->{'new_password'})
3266 || $svc_acct->replace();
3268 #regular pw change in self-service should change contact pw too, otherwise its
3269 #way too confusing. hell its confusing they're separate at all, but alas.
3270 #need to support the "ISP provides email that's used as a contact email" case
3272 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3273 if ( $contact && qsearchs('cust_contact', { contactnum=> $contact->contactnum,
3274 custnum => $custnum,
3275 selfservice_access => 'Y',
3279 #svc_acct was successful but this one returns an error? "shouldn't happen"
3280 #don't recheck is_password_allowed here; if the svc_acct password was
3281 #legal, that's good enough
3282 $error ||= $contact->change_password($p->{'new_password'});
3285 my($label, $value) = $svc_acct->cust_svc->label;
3287 return { 'error' => $error,
3297 my $info = skin_info($p);
3299 my $conf = new FS::Conf;
3300 my $verification = $conf->config('selfservice-password_reset_verification')
3301 or return { %$info, 'error' => 'Password resets disabled' };
3306 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3308 $contact = FS::contact->by_selfservice_email($p->{'email'}, 'case_insensitive');
3310 my @customers = grep $_->selfservice_access, $contact->cust_contact;
3313 foreach my $customer (@customers) {
3314 if ($conf->exists('username-uppercase') || $conf->exists('username-uppercase', $customer->cust_main->agentnum)) {
3315 my $check_contact = FS::contact->by_selfservice_email_custnum($p->{email}, $customer->custnum);
3316 push @cust_contact, $customer if $check_contact;
3318 else { push @cust_contact, $customer; }
3321 $contact = '' unless @cust_contact;
3322 $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
3324 #also look for an svc_acct, otherwise it would be super confusing
3326 my($username, $domain) = split('@', $p->{'email'});
3327 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3328 if ( $svc_domain ) {
3329 $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3330 'domsvc' => $svc_domain->svcnum }
3333 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3334 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3336 #precaution: don't change svc_acct password not part of the same
3337 # customer as contact
3338 $svc_acct = '' if ! $cust_pkg
3339 || $cust_pkg->custnum != $cust_main->custnum;
3344 return { %$info, 'error' => 'Email address not found' }
3345 unless $contact || $svc_acct;
3347 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3349 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3350 or return { %$info, 'error' => 'Account not found' };
3352 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3353 'domsvc' => $svc_domain->svcnum }
3355 or return { %$info, 'error' => 'Account not found' };
3357 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3358 or return { %$info, 'error' => 'Account not found' };
3360 $cust_main = $cust_pkg->cust_main;
3364 return { %$info, 'error' => 'Multi-customer contacts incompatible with customer-based verification' }
3365 if ! $cust_main && $verification ne 'email';
3368 'email' => sub { 1; },
3370 my( $p, $cust_main ) = @_;
3371 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3372 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3375 my( $p, $cust_main ) = @_;
3376 my $cust_pay = qsearchs({
3377 'table' => 'cust_pay',
3378 'hashref' => { 'custnum' => $cust_main->custnum },
3379 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3383 $p->{'amount'} == $cust_pay->paid;
3386 my( $p, $cust_main ) = @_;
3387 $p->{'zip'} eq $cust_main->zip
3388 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3392 foreach my $verify ( split(',', $verification) ) {
3394 &{ $verify{$verify} }( $p, $cust_main )
3395 or return { %$info, 'error' => 'Account not found' };
3399 #okay, we're verified
3403 my $error = $contact->send_reset_email(
3404 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3408 return { %$info, 'error' => $error }; #????
3411 } elsif ( $svc_acct ) {
3413 #create a unique session
3415 my $reset_session = {
3416 'svcnum' => $svc_acct->svcnum,
3417 'agentnum' => $svc_acct->cust_main->agentnum,
3420 my $timeout = '1 hour'; #?
3422 my $reset_session_id;
3424 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3425 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3428 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3432 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3433 $cust_main->agentnum);
3434 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3435 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3437 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3438 my $error = $msg_template->send( 'cust_main' => $cust_main,
3439 'object' => $svc_acct,
3440 'substitutions' => {
3441 'session_id' => $reset_session_id,
3445 return { %$info, 'error' => $error }; #????
3450 return { %$info, 'error' => '' };
3453 sub check_reset_passwd {
3456 my $conf = new FS::Conf;
3457 my $verification = $conf->config('selfservice-password_reset_verification')
3458 or return { 'error' => 'Password resets disabled' };
3460 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3461 or return { 'error' => "Can't resume session" }; #better error message
3463 if ( $reset_session->{'svcnum'} ) {
3465 my $svcnum = $reset_session->{'svcnum'};
3467 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3468 or return { 'error' => "Service not found" };
3470 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3471 my $info = skin_info($p);
3475 'session_id' => $p->{'session_id'},
3476 'username' => $svc_acct->username,
3479 } elsif ( $reset_session->{'contactnum'} ) {
3481 my $contactnum = $reset_session->{'contactnum'};
3483 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3484 or return { 'error' => "Contact not found" };
3486 my @contact_email = $contact->contact_email;
3487 return { 'error' => 'No contact email' } unless @contact_email;
3489 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3490 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3491 if scalar(@cust_contact) == 1;
3492 my $info = skin_info($p);
3496 'session_id' => $p->{'session_id'},
3497 'email' => $contact_email[0]->email, #the first?
3502 return { 'error' => 'No svcnum or contactnum in session' }; #??
3508 sub process_reset_passwd {
3511 my $conf = new FS::Conf;
3512 my $verification = $conf->config('selfservice-password_reset_verification')
3513 or return { 'error' => 'Password resets disabled' };
3515 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3516 or return { 'error' => "Can't resume session" }; #better error message
3521 if ( $reset_session->{'svcnum'} ) {
3523 my $svcnum = $reset_session->{'svcnum'};
3525 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3526 or return { 'error' => "Service not found" };
3528 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3529 $info ||= skin_info($p);
3534 if ( $reset_session->{'contactnum'} ) {
3536 my $contactnum = $reset_session->{'contactnum'};
3538 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3539 or return { 'error' => "Contact not found" };
3541 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3542 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3543 if scalar(@cust_contact) == 1;
3544 $info ||= skin_info($p);
3548 return { %$info, 'error' => "New passwords don't match." }
3549 if $p->{'new_password'} ne $p->{'new_password2'};
3551 return { %$info, 'error' => 'Enter new password' }
3552 unless length($p->{'new_password'});
3556 my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3557 || $svc_acct->set_password($p->{'new_password'})
3558 || $svc_acct->replace();
3560 return { %$info, 'error' => $error } if $error;
3562 #my($label, $value) = $svc_acct->cust_svc->label;
3563 #return { 'error' => $error,
3564 # #'label' => $label,
3565 # #'value' => $value,
3572 my $error = $contact->is_password_allowed($p->{'new_password'})
3573 || $contact->change_password($p->{'new_password'});
3575 return { %$info, 'error' => $error }; # if $error;
3579 #password changed ,so remove session, don't want it reused
3580 _cache->remove($p->{'session_id'});
3582 return { %$info, 'error' => '' };
3586 sub validate_passwd {
3590 %result = ( 'fieldid' => $p->{'fieldid'} )
3591 if $p->{'fieldid'} =~ /^\w+$/;
3593 return { %result, 'password_invalid' => 'Enter new password' }
3594 unless length($p->{'check_password'});
3597 if ($p->{'svcnum'}) {
3598 # false laziness with myaccount_passwd
3599 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3600 return { %result, 'error' => $session } if $context eq 'error';
3602 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3603 my $search = " AND custnum = $1";
3604 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3606 $svc_acct = qsearchs( {
3607 'table' => 'svc_acct',
3608 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3609 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3610 'LEFT JOIN cust_main USING ( custnum ) ',
3611 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3612 'extra_sql' => $search, #important
3614 or return { %result, 'error' => "Service not found" };
3615 # end false laziness
3618 $svc_acct ||= new FS::svc_acct {};
3620 my $error = $svc_acct->is_password_allowed($p->{'check_password'});
3621 return { %result, 'password_invalid' => $error } if $error;
3622 return { %result, 'password_valid' => 1 };
3627 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3628 return { 'error' => $session } if $context eq 'error';
3631 if ( $session->{'pkgnum'} ) {
3633 #tickets for specific service with pkg-balances on
3634 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3635 'pkgnum' => $session->{'pkgnum'} })
3636 or return { 'error' => 'unknown package' };
3637 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3638 push @tickets, $cust_svc->tickets( $p->{status} );
3643 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3644 or return { 'error' => "unknown custnum $custnum" };
3646 @tickets = $cust_main->tickets( $p->{status} );
3649 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3650 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3652 @tickets = grep { $_->{'_selfservice_priority'}
3653 !~ /^\s*(closed?|resolved?|done)\s*/i }
3656 my $conf = new FS::Conf;
3657 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3661 ($a->{'_selfservice_priority'} eq '') <=>
3662 ($b->{'_selfservice_priority'} eq '')
3665 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3671 +{ tickets => \@tickets };
3678 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3679 return { 'error' => $session } if $context eq 'error';
3681 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3682 FS::TicketSystem->init();
3684 my $conf = new FS::Conf;
3685 my $queue = $p->{'queue'}
3686 || $conf->config('ticket_system-selfservice_queueid')
3687 || $conf->config('ticket_system-default_queueid');
3689 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3690 my $err_or_ticket = FS::TicketSystem->create_ticket(
3691 '', #create RT session based on FS CurrentUser (fs_selfservice)
3693 'custnum' => $custnum,
3694 'svcnum' => $session->{'svcnum'},
3695 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3698 if ( ref($err_or_ticket) ) {
3699 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3701 return { 'error' => '',
3702 'ticket_id' => $err_or_ticket->id,
3705 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3707 return { 'error' => $err_or_ticket };
3715 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3716 return { 'error' => $session } if $context eq 'error';
3718 return { error => 'requested format not implemented' }
3719 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3721 my $conf = new FS::Conf;
3722 my $age_threshold = 0;
3723 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3724 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3726 my $search = { 'custnum' => $custnum };
3727 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3728 my $cust_main = qsearchs('cust_main', $search )
3729 or return { 'error' => "unknown custnum $custnum" };
3731 # does it make more sense to just run one sql query for this instead of all the
3732 # insanity below? would increase performance greately for large data sets?
3734 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3735 my @part_svc = $cust_pkg->part_svc;
3736 foreach my $part_svc ( @part_svc ) {
3737 if($part_svc->svcdb eq 'svc_phone'){
3738 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3739 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3740 push @svc_phone, $cust_pkg_svc->svc_x
3741 if $cust_pkg_svc->date_inserted >= $age_threshold;
3749 my($xls_r,$xls_c) = (0,0);
3752 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3753 if($p->{'format'} eq 'csv') {
3754 $csv = new Text::CSV_XS { 'always_quote' => 1,
3757 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3758 $content .= $csv->string;
3760 elsif($p->{'format'} eq 'xls') {
3761 my $XLS1 = new IO::Scalar \$content;
3762 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3763 or return { 'error' => "Error opening .xls file: $!" };
3764 $xls = $xls_workbook->add_worksheet('DIDs');
3765 foreach ( @fields ) {
3766 $xls->write(0,$xls_c++,$_);
3771 foreach my $svc_phone ( @svc_phone ) {
3772 my @cols = map { $svc_phone->$_ } @fields;
3773 if($p->{'format'} eq 'csv') {
3774 return { 'error' => 'Unable to create CSV' }
3775 unless $csv->combine(@cols);
3776 $content .= $csv->string;
3778 elsif($p->{'format'} eq 'xls') {
3781 $xls->write($xls_r,$xls_c++,$_);
3787 $xls_workbook->close() if $p->{'format'} eq 'xls';
3789 { content => $content, format => $p->{'format'}, };
3794 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3795 return { 'error' => $session } if $context eq 'error';
3797 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3798 # FS::TicketSystem->init();
3799 # return { 'error' => 'get_ticket configuration error' }
3800 # if $FS::TicketSystem::system ne 'RT_Internal';
3802 # check existence and ownership as part of this
3803 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3804 my $rt_session = FS::TicketSystem->session('');
3805 my $Ticket = FS::TicketSystem->get_ticket_object(
3807 ticket_id => $p->{'ticket_id'},
3810 return { 'error' => 'ticket not found' } if !$Ticket;
3812 if ( length( $p->{'subject'} || '' ) ) {
3814 if ( $p->{'subject'} ne $Ticket->Subject ) {
3815 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3816 return { 'error' => "unable to set subject: $msg" } if !$val;
3820 if(length($p->{'reply'})) {
3821 my @err_or_res = FS::TicketSystem->correspond_ticket(
3823 'ticket_id' => $p->{'ticket_id'},
3824 'content' => $p->{'reply'},
3827 return { 'error' => 'unable to reply to ticket' }
3828 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3831 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3832 my $err_or_ticket = FS::TicketSystem->get_ticket(
3834 'ticket_id' => $p->{'ticket_id'},
3837 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3838 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3840 return { 'error' => $err_or_ticket };
3843 my @custs = @{$err_or_ticket->{'custs'}};
3844 my @txns = @{$err_or_ticket->{'txns'}};
3847 # superseded by check in get_ticket_object
3848 #return { 'error' => 'invalid ticket requested' }
3849 #unless grep($_ eq $custnum, @custs);
3851 foreach my $txn ( @txns ) {
3852 push @filtered_txns, $txn
3853 if ($txn->{'type'} eq 'EmailRecord'
3854 || $txn->{'type'} eq 'Correspond'
3855 || $txn->{'type'} eq 'Create');
3858 warn "$me get_ticket: successful: \n"
3860 return { 'error' => '',
3861 'transactions' => \@filtered_txns,
3862 'ticket_fields' => $err_or_ticket->{'fields'},
3863 'ticket_id' => $p->{'ticket_id'},
3867 sub adjust_ticket_priority {
3869 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3870 return { 'error' => $session } if $context eq 'error';
3872 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3873 # FS::TicketSystem->init;
3874 my $ss_priority = FS::TicketSystem->selfservice_priority;
3876 return { 'error' => 'adjust_ticket_priority configuration error' }
3877 if $FS::TicketSystem::system ne 'RT_Internal'
3880 my $values = $p->{'values'}; #hashref, id => priority value
3883 foreach my $id (keys %$values) {
3884 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3885 my $Ticket = FS::TicketSystem->get_ticket_object('',
3887 'custnum' => $custnum,
3890 $ticket_error{$id} = 'ticket not found';
3894 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3895 # We're not going to implement it for RT_External.
3896 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3897 my $new_value = $values->{$id};
3898 next if $old_value eq $new_value;
3900 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3902 # AddCustomFieldValue works fine (replacing any existing value) if it's
3903 # a single-valued custom field, which it should be. If it's not, you're
3904 # doing something wrong.
3906 if ( length($new_value) ) {
3907 ($val, $msg) = $Ticket->AddCustomFieldValue(
3908 Field => $ss_priority,
3909 Value => $new_value,
3913 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3914 Field => $ss_priority,
3915 Value => $old_value,
3919 $ticket_error{$id} = $msg if !$val;
3920 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3922 return { 'error' => '',
3923 'ticket_error' => \%ticket_error,
3924 %{ customer_info($p) } # send updated customer info back
3930 sub _custoragent_session_custnum {
3933 my($context, $session, $custnum);
3934 if ( $p->{'session_id'} ) {
3936 $context = 'customer';
3937 $session = _cache->get($p->{'session_id'})
3938 or return ( 'error' => "Can't resume session" ); #better error message
3939 $custnum = $session->{'custnum'};
3941 } elsif ( $p->{'agent_session_id'} ) {
3944 my $agent_cache = new FS::ClientAPI_SessionCache( {
3945 'namespace' => 'FS::ClientAPI::Agent',
3947 $session = $agent_cache->get($p->{'agent_session_id'})
3948 or return ( 'error' => "Can't resume session" ); #better error message
3949 $custnum = $p->{'custnum'};
3953 return ( 'error' => "Can't resume session" ); #better error message
3956 ($context, $session, $custnum);