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;
49 use FS::cust_location;
51 # for code organization
52 use FS::ClientAPI::MyAccount::contact;
53 use FS::ClientAPI::MyAccount::quotation;
56 $me = '[FS::ClientAPI::MyAccount]';
58 use vars qw( @cust_main_editable_fields @location_editable_fields );
59 @cust_main_editable_fields = qw(
60 first last company daytime night fax mobile
62 payby payinfo payname paystart_month paystart_year payissue payip
63 ss paytype paystate stateid stateid_state
65 @location_editable_fields = qw(
66 address1 address2 city county state zip country
70 BEGIN { #preload to reduce time customer_info takes
71 if ( $FS::TicketSystem::system ) {
72 warn "$me: initializing ticket system\n" if $DEBUG;
73 FS::TicketSystem->init();
78 $cache ||= new FS::ClientAPI_SessionCache( {
79 'namespace' => 'FS::ClientAPI::MyAccount',
86 my($context, $session, $custnum) = _custoragent_session_custnum($p);
87 #return { 'error' => $session } if $context eq 'error';
89 my $domain = $session->{'domain'};
92 if ( $context eq 'customer' ) {
94 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
97 $sth->execute($custnum) or die $sth->errstr;
99 $agentnum = $sth->fetchrow_arrayref->[0]
100 or die "no agentnum for custnum $custnum";
102 #} elsif ( $context eq 'agent' ) {
103 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
106 $p->{'agentnum'} = $agentnum;
108 my $conf = new FS::Conf;
109 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
110 #false laziness w/Signup.pm
112 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
114 if ( $skin_info_cache_agent ) {
116 warn "$me loading cached skin info for agentnum $agentnum\n"
121 warn "$me populating skin info cache for agentnum $agentnum\n"
124 my $menu = $conf->config("ng_selfservice-menu", $agentnum );
126 $skin_info_cache_agent = {
127 'agentnum' => $agentnum,
128 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
129 qw( company_name date_format ) ),
130 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
131 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
132 text_color link_color vlink_color hlink_color alink_color
133 font title_color title_align title_size menu_bgcolor menu_fontsize
136 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
137 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
138 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo enable_payment_without_balance )
140 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
141 qw( title_left_image title_right_image
142 menu_top_image menu_body_image menu_bottom_image
145 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
146 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
147 qw( head body_header body_footer company_address ) ),
148 'money_char' => $conf->config("money_char") || '$',
149 'menu' => _menu($domain,$menu),
152 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent, $timeout);
156 #{ %$skin_info_cache_agent };
157 $skin_info_cache_agent;
161 ## checks if page is in menu listing, if not sends to main with error.
166 return if $p->{'page'} eq "index.php";
167 return if $p->{'page'} eq "ip_login.php";
169 return if substr($p->{'page'}, 0, length("process_")) eq "process_";
171 my $conf = new FS::Conf;
173 my($context, $session, $custnum) = _custoragent_session_custnum($p);
175 my $domain = ref($session) ? $session->{'domain'} : '';
178 if ( $context eq 'customer' && $custnum ) {
180 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
183 $sth->execute($custnum) or die $sth->errstr;
185 $agentnum = $sth->fetchrow_arrayref->[0]
186 or die "no agentnum for custnum $custnum";
188 #} elsif ( $context eq 'agent' ) {
189 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
192 $p->{'agentnum'} = $agentnum;
194 my $menu = $conf->config("ng_selfservice-menu", $agentnum );
196 my $allowed_pages = _menu($domain,$menu);
199 my @lines = split /\n/, $allowed_pages;
200 foreach my $line (@lines) {
201 chomp; # remove newlines
202 $line =~ s/^\s+//; # remove leading whitespace
203 next unless length($line);
204 my (@pages) = split(/ /, $line, 2);
205 $allowed{$pages[0]} = $pages[1];
208 $error = "You do not have access to the page ".$allowed{$p->{page}} unless $allowed{$p->{page}};
210 return { 'error' => $error, };
220 if ($p eq 'ip_mac') {
221 $menu = 'main.php Home
224 payment_cc.php Credit Card Payment
225 payment_ach.php Electronic Check Payment
226 payment_paypal.php PayPal Payment
227 payment_webpay.php Webpay Payments
235 $menu = join("\n", $m ) ||
238 services.php Services
239 services.php My Services
240 services_new.php Order a new service
243 personal.php Personal Information
244 password.php Change Password
247 payment_cc.php Credit Card Payment
248 payment_ach.php Electronic Check Payment
249 payment_paypal.php PayPal Payment
250 payment_webpay.php Webpay Payments
253 usage_data.php Data usage
254 usage_cdr.php Call usage
256 tickets.php Help Desk
257 tickets.php Open Tickets
258 tickets_resolved.php Resolved Tickets
259 ticket_create.php Create a new ticket
269 sub get_mac_address {
272 ## access radius exports acct tables to get mac
273 my @part_export = ();
275 qsearch( 'part_export', { 'exporttype' => 'sqlradius' } ),
276 qsearch( 'part_export', { 'exporttype' => 'sqlradius_withdomain' } ),
277 qsearch( 'part_export', { 'exporttype' => 'broadband_sqlradius' } ),
281 foreach my $part_export (@part_export) {
282 push @sessions, ( @{ $part_export->usage_sessions( {
284 'session_status' => 'open',
288 return { 'mac_address' => $sessions[0]->{'callingstationid'}, };
294 my $conf = new FS::Conf;
298 'phone_login' => $conf->exists('selfservice_server-phone_login'),
299 'single_domain' => scalar($conf->config('selfservice_server-single_domain')),
300 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
301 'banner_image_md5' =>
302 md5_hex($conf->config_binary('selfservice-login_banner_image')),
309 sub login_banner_image {
311 my $conf = new FS::Conf;
312 my $image = $conf->config_binary('selfservice-login_banner_image');
314 'md5' => md5_hex($image),
319 #false laziness w/FS::ClientAPI::passwd::passwd
323 my $conf = new FS::Conf;
327 if ( $p->{'domain'} eq 'svc_phone'
328 && $conf->exists('selfservice_server-phone_login') ) {
330 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
331 return { error => 'Number not found.' } unless $svc_phone;
334 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
335 #return { error => 'Only primary user may log in.' }
336 # if $conf->exists('selfservice_server-primary_only')
337 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
339 return { error => 'Incorrect PIN.' }
340 unless $svc_phone->check_pin($p->{'password'});
344 } elsif ( $p->{'domain'} eq 'ip_mac' ) {
346 return { error => 'MAC address empty '.$p->{'username'} }
347 unless $p->{'username'};
349 my $mac_address = $p->{'username'};
350 $mac_address =~ s/[\:\,\-\. ]//g;
351 $mac_address =~ tr/[a-z]/[A-Z/;
353 my $svc_broadband = qsearchs( 'svc_broadband', { 'mac_addr' => $mac_address } );
354 return { error => 'MAC address not found '.$p->{'username'} }
355 unless $svc_broadband;
356 $svc_x = $svc_broadband;
358 $session->{'domain'} = $p->{'domain'};
360 } elsif ( $p->{email}
361 && (my $contact = FS::contact->by_selfservice_email($p->{email}))
364 return { error => 'Incorrect contact password.' }
365 unless $contact->authenticate_password($p->{'password'});
367 $session->{'contactnum'} = $contact->contactnum;
369 $session->{'custnum'} = $contact->custnum;
373 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
375 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
376 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
378 my @svc_acct = qsearch( 'svc_acct', { 'username' => $p->{'username'},
379 'domsvc' => $svc_domain->svcnum, }
382 if ( $conf->exists('selfservice_server-login_svcpart') ) {
383 my @svcpart = $conf->config('selfservice_server-login_svcpart');
384 @svc_acct = grep { my $svcpart = $_->cust_svc->svcpart;
385 scalar( grep( $_ eq $svcpart, @svcpart ) );
390 if ( $conf->exists('selfservice_server-primary_only') ) {
393 my $cust_svc = $_->cust_svc;
394 $cust_svc->cust_pkg->part_pkg->svcpart([qw( svc_acct svc_phone )])
395 == $cust_svc->svcpart
400 return { error => 'User not found.' } unless @svc_acct;
402 #return { error => 'Multiple users.' } if scalar(@svc_acct) > 1;
404 my $svc_acct = $svc_acct[0];
406 if ( $conf->exists('selfservice_server-login_svcpart') ) {
407 my @svcpart = $conf->config('selfservice_server-login_svcpart');
408 my $svcpart = $svc_acct->cust_svc->svcpart;
409 return { error => 'Invalid user.' }
410 unless grep($_ eq $svcpart, @svcpart);
413 return { error => 'Incorrect password.' }
414 unless $svc_acct->check_password($p->{'password'});
422 $session->{'svcnum'} = $svc_x->svcnum;
424 my $cust_svc = $svc_x->cust_svc;
425 my $cust_pkg = $cust_svc->cust_pkg;
427 my $cust_main = $cust_pkg->cust_main;
428 $session->{'custnum'} = $cust_main->custnum;
429 if ( $conf->exists('pkg-balances') ) {
430 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
431 $cust_main->ncancelled_pkgs;
432 $session->{'pkgnum'} = $cust_pkg->pkgnum
433 if scalar(@cust_pkg) > 1;
437 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
438 #return { error => 'Only primary user may log in.' }
439 # if $conf->exists('selfservice_server-primary_only')
440 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
441 my $part_pkg = $cust_pkg->part_pkg;
442 return { error => 'Only primary user may log in.' }
443 if $conf->exists('selfservice_server-primary_only')
444 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
450 $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
451 } until ( ! defined _cache->get($session_id) ); #just in case
453 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
454 _cache->set( $session_id, $session, $timeout );
456 return { 'error' => '',
457 'session_id' => $session_id,
464 my $skin_info = skin_info($p);
465 if ( $p->{'session_id'} ) {
466 _cache->remove($p->{'session_id'});
467 return { %$skin_info, 'error' => '' };
469 return { %$skin_info, 'error' => "Can't resume session" }; #better error message
476 my($context, $session, $custnum) = _custoragent_session_custnum($p);
477 return { 'error' => $session } if $context eq 'error';
479 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
480 or return { 'error' => "Service not found" };
482 $session->{'svcnum'} = $svc_acct->svcnum;
484 my $conf = new FS::Conf;
485 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
486 _cache->set( $p->{'session_id'}, $session, $timeout );
488 return { 'error' => '' };
492 sub payment_gateway {
494 # takes a cust_main and a cust_payby entry, returns the payment_gateway
495 my $conf = new FS::Conf;
496 my $cust_main = shift;
497 my $cust_payby = shift;
498 my $gatewaynum = $conf->config('selfservice-payment_gateway');
500 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
501 die "configured gatewaynum $gatewaynum not found!" if !$pg;
505 return '' if ! FS::payby->realtime($cust_payby);
506 my $pg = $cust_main->agent->payment_gateway(
507 'method' => FS::payby->payby2bop($cust_payby),
517 my $conf = new FS::Conf;
519 my $info = skin_info($p);
521 use vars qw( $cust_paybys ); #cache for performance
522 unless ( $cust_paybys ) {
524 my %cust_paybys = map { $_ => 1 }
525 map { FS::payby->payby2payment($_) }
526 $conf->config('signup_server-payby');
528 $cust_paybys = [ keys %cust_paybys ];
531 $info->{'cust_paybys'} = $cust_paybys;
533 my($context, $session, $custnum) = _custoragent_session_custnum($p);
534 return { 'error' => $session } if $context eq 'error';
536 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
537 or return { 'error' => "unknown custnum $custnum" };
539 $info->{'hide_payment_fields'} = [
541 my $pg = payment_gateway($cust_main, $_);
542 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
543 } @{ $info->{cust_paybys} }
546 $info->{'self_suspend_reason'} =
547 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
549 $info->{'edit_ticket_subject'} =
550 $conf->exists('ticket_system-selfservice_edit_subject') &&
551 $cust_main->edit_subject;
553 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
555 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
558 'custnum' => $custnum,
559 'access_pkgnum' => $session->{'pkgnum'},
560 'access_svcnum' => $session->{'svcnum'},
567 my($context, $session, $custnum) = _custoragent_session_custnum($p);
568 return { 'error' => $session } if $context eq 'error';
572 my $conf = new FS::Conf;
573 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
575 # if ( $FS::TicketSystem::system ) {
576 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
577 # FS::TicketSystem->init();
580 if ( $custnum ) { #customer record
582 %return = ( %return, %{ customer_info_short($p) } );
584 #redundant with customer_info_short, but we need it for several things below
585 my $search = { 'custnum' => $custnum };
586 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
587 my $cust_main = qsearchs('cust_main', $search )
588 or return { 'error' => "unknown custnum $custnum" };
590 my $list_tickets = list_tickets($p);
591 $return{'tickets'} = $list_tickets->{'tickets'};
593 if ( $session->{'pkgnum'} ) {
594 #XXX open invoices in the pkg-balances case
596 $return{'money_char'} = $conf->config("money_char") || '$';
599 invnum => $_->invnum,
600 date => time2str("%b %o, %Y", $_->_date),
602 charged => $_->charged,
604 } $cust_main->open_cust_bill;
605 $return{open_invoices} = \@open;
607 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
608 my $sth = dbh->prepare($sql) or die dbh->errstr;
609 $sth->execute($custnum) or die $sth->errstr;
610 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
611 $return{'last_invoice_date_pretty'} =
612 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
615 #customer_info_short always has nobalance on..
616 $return{small_custview} =
617 small_custview( $cust_main,
618 $return{countrydefault},
619 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
622 $return{has_ship_address} = $cust_main->has_ship_address;
623 $return{status} = $cust_main->status;
624 $return{statuscolor} = $cust_main->statuscolor;
626 # compatibility: some places in selfservice use this to determine
627 # if there's a ship address
628 if ( $return{has_ship_address} ) {
629 $return{ship_last} = $cust_main->last;
630 $return{ship_first} = $cust_main->first;
633 if (scalar($conf->config('support_packages'))) {
634 my @support_services = ();
635 foreach ($cust_main->support_services) {
636 my $seconds = $_->svc_x->seconds || 0;
637 my $time_remaining = (($seconds < 0) ? '-' : '' ).
638 int(abs($seconds)/3600)."h".
639 sprintf("%02d",(abs($seconds)%3600)/60)."m";
640 my $cust_pkg = $_->cust_pkg;
643 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
644 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
645 push @support_services, { svcnum => $_->svcnum,
646 time => $time_remaining,
651 $return{support_services} = \@support_services;
654 if ( $conf->config('prepayment_discounts-credit_type') ) {
656 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
659 } elsif ( $session->{'svcnum'} ) { #no customer record
661 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
662 or die "unknown svcnum";
663 $return{name} = $svc_acct->email;
667 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
671 return { 'error' => '',
672 'custnum' => $custnum,
678 sub customer_info_short {
681 my($context, $session, $custnum) = _custoragent_session_custnum($p);
682 return { 'error' => $session } if $context eq 'error';
686 my $conf = new FS::Conf;
688 if ( $custnum ) { #customer record
690 my $search = { 'custnum' => $custnum };
691 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
692 my $cust_main = qsearchs('cust_main', $search )
693 or return { 'error' => "unknown custnum $custnum" };
695 $return{display_custnum} = $cust_main->display_custnum;
697 if ( $session->{'pkgnum'} ) {
698 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
699 #next_bill_date from cust_pkg?
701 $return{balance} = $cust_main->balance;
702 $return{next_bill_date} = $cust_main->next_bill_date;
703 $return{next_bill_date_pretty} =
704 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
707 $return{balance_pretty} = money_pretty($return{balance});
709 $return{countrydefault} = scalar($conf->config('countrydefault'));
711 $return{small_custview} =
712 small_custview( $cust_main,
713 $return{countrydefault},
717 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
719 $return{payby} = $cust_main->payby;
721 #none of these are terribly expensive if we want 'em...
722 for (@cust_main_editable_fields) {
723 $return{$_} = $cust_main->get($_);
725 $return{$_} = $cust_main->masked($_) for qw/ss stateid/;
727 #maybe a little more expensive, but it should be cached by now
728 for (@location_editable_fields) {
729 $return{$_} = $cust_main->bill_location->get($_);
730 $return{'ship_'.$_} = $cust_main->ship_location->get($_);
733 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
734 $return{payinfo} = $cust_main->paymask;
735 @return{'month', 'year'} = $cust_main->paydate_monthyear;
738 my @invoicing_list = $cust_main->invoicing_list;
739 $return{'invoicing_list'} =
740 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
741 $return{'postal_invoicing'} =
742 0 < ( grep { $_ eq 'POST' } @invoicing_list );
744 if ( $session->{'svcnum'} ) {
745 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
746 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
747 $return{'svcnum'} = $session->{'svcnum'};
750 } elsif ( $session->{'svcnum'} ) { #no customer record
752 #uuh, not supproted yet... die?
753 return { 'error' => 'customer_info_short not yet supported as agent' };
757 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
761 # this is here because this routine is called by both fs_ and ng_ main pages, where it appears
762 # it is not customer-specific, though it is only shown to authenticated customers
763 # it is not currently agent-specific, though at some point it might be
764 $return{'announcement'} = join(' ',$conf->config('selfservice-announcement')) || '';
766 return { 'error' => '',
767 'custnum' => $custnum,
772 sub customer_recurring {
775 my($context, $session, $custnum) = _custoragent_session_custnum($p);
776 return { 'error' => $session } if $context eq 'error';
780 my $conf = new FS::Conf;
782 my $search = { 'custnum' => $custnum };
783 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
784 my $cust_main = qsearchs('cust_main', $search )
785 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
787 $return{'display_recurring'} = [ $cust_main->display_recurring ];
789 return { 'error' => '',
790 'custnum' => $custnum,
795 sub billing_history {
798 my($context, $session, $custnum) = _custoragent_session_custnum($p);
799 return { 'error' => $session } if $context eq 'error';
801 return { 'error' => 'No customer' } unless $custnum;
803 my $search = { 'custnum' => $custnum };
804 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
805 my $cust_main = qsearchs('cust_main', $search )
806 or return { 'error' => "unknown custnum $custnum" };
810 if ( $session->{'pkgnum'} ) {
811 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
812 #next_bill_date from cust_pkg?
813 return { 'error' => 'No history for package' };
816 $return{balance} = $cust_main->balance;
817 $return{balance_pretty} = money_pretty($return{balance});
818 $return{next_bill_date} = $cust_main->next_bill_date;
819 $return{next_bill_date_pretty} =
820 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
823 my $conf = new FS::Conf;
825 $return{'history'} = [
826 $cust_main->payment_history(
827 'line_items' => $conf->exists('selfservice-billing_history-line_items'),
832 $return{'money_char'} = $conf->config("money_char") || '$',
840 my $session = _cache->get($p->{'session_id'})
841 or return { 'error' => "Can't resume session" }; #better error message
843 my $custnum = $session->{'custnum'}
844 or return { 'error' => "no customer record" };
846 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
847 or return { 'error' => "unknown custnum $custnum" };
849 my $conf = new FS::Conf;
850 if (($p->{payby} eq "CHEK" || $p->{payby} eq "DCHK") && $conf->exists('selfservice-ACH_info_readonly')) {
851 return { 'error' => "You do not have authority to add a bank account" };
854 my $new = new FS::cust_main { $cust_main->hash };
856 $new->set( $_ => $p->{$_} )
857 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
859 if ( exists($p->{address1}) ) {
860 my $bill_location = FS::cust_location->new({
861 map { $_ => $p->{$_} } @location_editable_fields
863 # if this is unchanged from before, cust_main::replace will ignore it
864 $new->set('bill_location' => $bill_location);
867 if ( exists($p->{ship_address1}) ) {
868 my $ship_location = FS::cust_location->new({
869 map { $_ => $p->{"ship_$_"} } @location_editable_fields
871 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
872 # Selfservice unfortunately tries to indicate "same as billing
873 # address" by sending all fields empty. Did this ever work?
874 $ship_location = $cust_main->bill_location;
876 $new->set('ship_location' => $ship_location);
878 # but if it hasn't been passed in at all, leave ship_location alone--
879 # DON'T change it to match bill_location.
882 if (exists($p->{'payby'})) {
883 $p->{'payby'} =~ /^([A-Z]{4})$/
884 or return { 'error' => "illegal_payby " . $p->{'payby'} };
888 if ( $payby =~ /^(CARD|DCRD)$/ ) {
890 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
892 if ( $new->payinfo eq $cust_main->paymask ) {
893 $new->payinfo($cust_main->payinfo);
894 $new->paycvv( $p->{'paycvv'} || $cust_main->paycvv );
896 $new->payinfo($p->{'payinfo'});
897 return { 'error' => 'CVV2 is required' }
898 if ! $p->{'paycvv'} && $conf->exists('selfservice-onfile_require_cvv');
899 $new->paycvv( $p->{'paycvv'} )
902 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
904 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
907 $p->{'payinfo1'} =~ /^([\dx]+)$/
908 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
910 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
911 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
913 $payinfo = $payinfo1. '@'. $payinfo2;
915 $new->payinfo( ($payinfo eq $cust_main->paymask)
916 ? $cust_main->payinfo
920 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
922 } elsif ( $payby =~ /^(BILL)$/ ) {
924 } elsif ( $payby ) { #notyet ready
925 return { 'error' => "unknown payby $payby" };
929 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
930 #false laziness with httemplate/edit/process/cust_main.cgi
931 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
932 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
934 @invoicing_list = $cust_main->invoicing_list;
937 my $error = $new->replace($cust_main, \@invoicing_list);
938 return { 'error' => $error } if $error;
941 return { 'error' => '' };
946 my $session = _cache->get($p->{'session_id'})
947 or return { 'error' => "Can't resume session" }; #better error message
953 my $conf = new FS::Conf;
954 use vars qw($payment_info); #cache for performance
955 unless ( $payment_info ) {
957 my %states = map { $_->state => 1 }
958 qsearch('cust_main_county', {
959 'country' => $conf->config('countrydefault') || 'US'
962 my %cust_paybys = map { $_ => 1 }
963 map { FS::payby->payby2payment($_) }
964 $conf->config('signup_server-payby');
966 my @cust_paybys = keys %cust_paybys;
970 #list all counties/states/countries
971 'cust_main_county' =>
972 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
974 #shortcut for one-country folks
976 [ sort { $a cmp $b } keys %states ],
978 'card_types' => card_types(),
980 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
981 'require_cvv' => $conf->exists('selfservice-require_cvv'),
982 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
984 'paytypes' => [ @FS::cust_main::paytypes ],
986 'paybys' => [ $conf->config('signup_server-payby') ],
987 'cust_paybys' => \@cust_paybys,
989 'stateid_label' => FS::Msgcat::_gettext('stateid'),
990 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
992 'show_ss' => $conf->exists('show_ss'),
993 'show_stateid' => $conf->exists('show_stateid'),
994 'show_paystate' => $conf->exists('show_bankstate'),
996 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
997 'ach_read_only' => $conf->exists('selfservice-ACH_info_readonly'),
1007 my %return = %$payment_info;
1009 delete $return{'cust_main_county'} if $p->{'omit_cust_main_county'};
1011 my $custnum = $session->{'custnum'};
1013 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1014 or return { 'error' => "unknown custnum $custnum" };
1016 $return{'hide_payment_fields'} = [
1018 my $pg = payment_gateway($cust_main, $_);
1019 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
1020 } @{ $return{cust_paybys} }
1023 $return{balance} = $cust_main->balance; #XXX pkg-balances?
1025 $return{payname} = $cust_main->payname
1026 || ( $cust_main->first. ' '. $cust_main->get('last') );
1028 $return{$_} = $cust_main->bill_location->get($_)
1029 for qw(address1 address2 city state zip);
1031 $return{payby} = $cust_main->payby;
1032 $return{stateid_state} = $cust_main->stateid_state;
1034 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
1035 $return{card_type} = cardtype($cust_main->payinfo);
1036 $return{payinfo} = $cust_main->paymask;
1038 @return{'month', 'year'} = $cust_main->paydate_monthyear;
1042 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
1043 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
1044 $return{payinfo1} = $payinfo1;
1045 $return{payinfo2} = $payinfo2;
1046 $return{paytype} = $cust_main->paytype;
1047 $return{paystate} = $cust_main->paystate;
1048 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
1051 if ( $conf->config('prepayment_discounts-credit_type') ) {
1053 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
1056 #doubleclick protection
1058 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
1059 $return{paybatch} = $return{payunique}; #back compat
1061 $return{credit_card_surcharge_percentage} = $conf->config('credit-card-surcharge-percentage', $cust_main->agentnum);
1062 $return{credit_card_surcharge_flatfee} = $conf->config('credit-card-surcharge-flatfee', $cust_main->agentnum);
1064 return { 'error' => '',
1070 #some false laziness with httemplate/process/payment.cgi - look there for
1071 #ACH and CVV support stuff
1073 sub validate_payment {
1076 my $session = _cache->get($p->{'session_id'})
1077 or return { 'error' => "Can't resume session" }; #better error message
1079 my $custnum = $session->{'custnum'};
1081 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1082 or return { 'error' => "unknown custnum $custnum" };
1084 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
1085 or return { 'error' => gettext('illegal_amount') };
1087 return { error => 'Amount must be greater than 0' } unless $amount > 0;
1089 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
1090 #changing the hidden form values
1091 my $conf = new FS::Conf;
1092 my $fee_display = $conf->config('selfservice_process-display') || 'add';
1093 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1094 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1095 if ( $fee_display eq 'add'
1097 and ! $fee_skip_first || scalar($cust_main->cust_pay)
1100 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
1101 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
1104 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
1105 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
1106 my $discount_term = $1;
1108 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
1109 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
1112 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1113 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
1116 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1117 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
1120 $payunique = $paybatch if ! length($payunique) && length($paybatch);
1122 $p->{'payby'} ||= 'CARD';
1123 $p->{'payby'} =~ /^([A-Z]{4})$/
1124 or return { 'error' => "illegal_payby " . $p->{'payby'} };
1127 #false laziness w/process/payment.cgi
1130 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
1132 $p->{'payinfo1'} =~ /^([\dx]+)$/
1133 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1135 $p->{'payinfo2'} =~ /^([\dx]+)$/
1136 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1138 $payinfo = $payinfo1. '@'. $payinfo2;
1140 $payinfo = $cust_main->payinfo
1141 if $cust_main->paymask eq $payinfo;
1144 if ( $cust_main->paymask eq $payinfo ) {
1145 $payinfo = $cust_main->payinfo;
1149 if ($conf->exists('selfservice-ACH_info_readonly') && !$achonfile) {
1150 return { 'error' => "You are not allowed to change your payment information." };
1153 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1155 $payinfo = $p->{'payinfo'};
1159 #more intelligent matching will be needed here if you change
1160 #card_masking_method and don't remove existing paymasks
1161 if ( $cust_main->paymask eq $payinfo ) {
1162 $payinfo = $cust_main->payinfo;
1166 $payinfo =~ s/\D//g;
1167 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1168 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1172 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1173 return { 'error' => gettext('unknown_card_type') }
1174 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1176 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1177 if ( cardtype($payinfo) eq 'American Express card' ) {
1178 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1179 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1182 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1183 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1186 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1187 return { 'error' => 'CVV2 is required' };
1188 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1189 return { 'error' => 'CVV2 is required' };
1193 die "unknown payby $payby";
1196 my %payby2fields = (
1197 'CARD' => [ qw( paystart_month paystart_year payissue payip
1198 address1 address2 city state zip country ) ],
1199 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1203 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1206 'cust_main' => $cust_main, #XXX or just custnum??
1207 'amount' => sprintf('%.2f', $amount),
1209 'payinfo' => $payinfo,
1210 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1211 'card_type' => $card_type,
1212 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1213 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1214 'month' => $p->{'month'},
1215 'year' => $p->{'year'},
1216 'payname' => $payname,
1217 'payunique' => $payunique,
1218 'paybatch' => $paybatch,
1219 'paycvv' => $paycvv,
1220 'payname' => $payname,
1221 'discount_term' => $discount_term,
1222 'pkgnum' => $session->{'pkgnum'},
1223 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1233 my $validate = validate_payment($p);
1234 return $validate if $validate->{'error'};
1236 my $conf = new FS::Conf;
1237 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1238 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1240 +{ map { $_=>$validate->{$_} }
1241 qw( card_type paymask payname paydate_pretty month year amount
1242 address1 address2 city state zip country
1248 sub process_stored_payment {
1251 my $session_id = $p->{'session_id'};
1253 my $payment_info = _cache->get( "payment_$session_id" )
1254 or return { 'error' => "Can't resume session" }; #better error message
1256 do_process_payment($payment_info);
1260 sub process_payment {
1263 my $payment_info = validate_payment($p);
1264 return $payment_info if $payment_info->{'error'};
1266 do_process_payment($payment_info);
1270 sub do_process_payment {
1271 my $validate = shift;
1273 my $cust_main = $validate->{'cust_main'};
1275 my $amount = delete $validate->{'amount'};
1278 my $payby = delete $validate->{'payby'};
1280 if ( $validate->{'save'} ) {
1281 my $new = new FS::cust_main { $cust_main->hash };
1282 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1283 $new->set( $_ => $validate->{$_} )
1284 foreach qw( payname paystart_month paystart_year payissue payip );
1285 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1287 my $bill_location = FS::cust_location->new({
1288 map { $_ => $validate->{$_} }
1289 qw(address1 address2 city state country zip)
1291 $new->set('bill_location' => $bill_location);
1292 # but don't allow the service address to change this way.
1294 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1295 $new->set( $_ => $validate->{$_} )
1296 foreach qw( payname payip paytype paystate
1297 stateid stateid_state );
1298 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1300 $new->payinfo( $validate->{'payinfo'} ); #to properly set paymask
1301 $new->set( 'paydate' => $validate->{'paydate'} );
1302 my $error = $new->replace($cust_main);
1304 #no, this causes customers to process their payments again
1305 #return { 'error' => $error };
1306 #XXX just warn verosely for now so i can figure out how these happen in
1307 # the first place, eventually should redirect them to the "change
1308 #address" page but indicate if the payment processed?
1309 delete($validate->{'payinfo'}); #don't want to log this!
1310 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1311 "NEW: ". Dumper($new)."\n".
1312 "OLD: ". Dumper($cust_main)."\n".
1313 "PACKET: ". Dumper($validate)."\n";
1319 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1323 'paynum_ref' => \$paynum,
1326 return { 'error' => $error } if $error;
1328 #no error, so order the fee package if applicable...
1329 my $conf = new FS::Conf;
1330 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1331 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1333 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1335 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1337 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1338 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1341 #and generate an invoice for it now too
1342 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1343 return { 'error' => "payment processed and fee ordered successfully, but error billing fee: $error" }
1348 $cust_main->apply_payments;
1351 my $receipt_html = '';
1353 # currently supported for realtime CC only; send receipt data to SS
1354 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1357 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1360 <TD ALIGN="right">Payment#</TD>
1361 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1365 <TD ALIGN="right">Date</TD>
1367 <TD BGCOLOR="#FFFFFF"><B>! .
1368 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1374 <TD ALIGN="right">Amount</TD>
1375 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1380 <TD ALIGN="right">Payment method</TD>
1381 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1394 'amount' => sprintf('%.2f', $cust_pay->paid),
1395 'date' => $cust_pay->_date,
1396 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1397 'time_pretty' => time2str('%T', $cust_pay->_date),
1398 'auth_num' => $cust_pay->auth,
1399 'order_num' => $cust_pay->order_number,
1400 'receipt_html' => $receipt_html,
1407 'receipt_html' => '',
1414 sub realtime_collect {
1417 my $session = _cache->get($p->{'session_id'})
1418 or return { 'error' => "Can't resume session" }; #better error message
1420 my $custnum = $session->{'custnum'};
1422 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1423 or return { 'error' => "unknown custnum $custnum" };
1426 if ( $p->{'amount'} ) {
1427 $amount = $p->{'amount'};
1429 elsif ( $session->{'pkgnum'} ) {
1430 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1433 $amount = $cust_main->balance;
1436 my $error = $cust_main->realtime_collect(
1437 'method' => $p->{'method'},
1438 'amount' => $amount,
1439 'pkgnum' => $session->{'pkgnum'},
1440 'session_id' => $p->{'session_id'},
1444 return { 'error' => $error } unless ref( $error );
1446 return { 'error' => '', amount => $amount, %$error };
1449 sub start_thirdparty {
1451 my $session = _cache->get($p->{'session_id'})
1452 or return { 'error' => "Can't resume session" }; #better error message
1453 my $custnum = $session->{'custnum'};
1454 my $cust_main = FS::cust_main->by_key($custnum);
1456 my $amount = $p->{'amount'}
1457 or return { error => 'no amount' };
1459 my $result = $cust_main->create_payment(
1460 'method' => $p->{'method'},
1461 'amount' => $p->{'amount'},
1462 'pkgnum' => $session->{'pkgnum'},
1463 'session_id' => $p->{'session_id'},
1466 if ( ref($result) ) { # hashref or error
1469 return { error => $result };
1473 sub finish_thirdparty {
1475 my $session_id = delete $p->{'session_id'};
1476 my $session = _cache->get($session_id)
1477 or return { 'error' => "Can't resume session" };
1478 my $custnum = $session->{'custnum'};
1479 my $cust_main = FS::cust_main->by_key($custnum);
1481 if ( $p->{_cancel} ) {
1482 # customer backed out of making a payment
1483 return $cust_main->cancel_payment( $session_id );
1485 my $result = $cust_main->execute_payment( $session_id, %$p );
1486 if ( ref($result) ) {
1489 return { error => $result };
1493 sub process_payment_order_pkg {
1496 my $hr = process_payment($p);
1497 return $hr if $hr->{'error'};
1502 sub process_payment_order_renew {
1505 my $hr = process_payment($p);
1506 return $hr if $hr->{'error'};
1511 sub process_prepay {
1515 my $session = _cache->get($p->{'session_id'})
1516 or return { 'error' => "Can't resume session" }; #better error message
1520 my $custnum = $session->{'custnum'};
1522 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1523 or return { 'error' => "unknown custnum $custnum" };
1525 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1526 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1534 return { 'error' => $error } if $error;
1536 return { 'error' => '',
1537 'amount' => $amount,
1538 'seconds' => $seconds,
1539 'duration' => duration_exact($seconds),
1540 'upbytes' => $upbytes,
1541 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1542 'downbytes' => $downbytes,
1543 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1544 'totalbytes'=> $totalbytes,
1545 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1552 my $session = _cache->get($p->{'session_id'})
1553 or return { 'error' => "Can't resume session" }; #better error message
1555 my $custnum = $session->{'custnum'};
1557 my $invnum = $p->{'invnum'};
1559 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1560 'custnum' => $custnum } )
1561 or return { 'error' => "Can't find invnum" };
1565 return { 'error' => '',
1566 'invnum' => $invnum,
1567 'invoice_text' => join('', $cust_bill->print_text ),
1568 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1575 my $session = _cache->get($p->{'session_id'})
1576 or return { 'error' => "Can't resume session" }; #better error message
1578 my $custnum = $session->{'custnum'};
1580 my $invnum = $p->{'invnum'};
1582 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1583 'custnum' => $custnum } )
1584 or return { 'error' => "Can't find invnum" };
1588 return { 'error' => '',
1589 'invnum' => $invnum,
1590 'invoice_pdf' => $cust_bill->print_pdf({
1591 'unsquelch_cdr' => 1,
1592 'locale' => $p->{'locale'},
1598 sub legacy_invoice {
1600 my $session = _cache->get($p->{'session_id'})
1601 or return { 'error' => "Can't resume session" }; #better error message
1603 my $custnum = $session->{'custnum'};
1605 my $legacyinvnum = $p->{'legacyinvnum'};
1608 'legacyinvnum' => $legacyinvnum,
1609 'custnum' => $custnum,
1612 my $legacy_cust_bill =
1613 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1614 || qsearchs('legacy_cust_bill', \%hash )
1615 or return { 'error' => "Can't find legacyinvnum" };
1619 return { 'error' => '',
1620 'legacyinvnum' => $legacyinvnum,
1621 'legacyid' => $legacy_cust_bill->legacyid,
1622 'invoice_html' => $legacy_cust_bill->content_html,
1627 sub legacy_invoice_pdf {
1629 my $session = _cache->get($p->{'session_id'})
1630 or return { 'error' => "Can't resume session" }; #better error message
1632 my $custnum = $session->{'custnum'};
1634 my $legacyinvnum = $p->{'legacyinvnum'};
1636 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1637 'legacyinvnum' => $legacyinvnum,
1638 'custnum' => $custnum,
1639 }) or return { 'error' => "Can't find legacyinvnum" };
1643 return { 'error' => '',
1644 'legacyinvnum' => $legacyinvnum,
1645 'legacyid' => $legacy_cust_bill->legacyid,
1646 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1654 #sessioning for this? how do we get the session id to the backend invoice
1655 # template so it can add it to the link, blah
1658 if ( $p->{'invnum'} ) {
1659 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1660 or return { 'error' => 'unknown invnum' };
1661 $agentnum = $cust_bill->cust_main->agentnum;
1664 my $templatename = $p->{'template'} || $p->{'templatename'};
1666 #false laziness-ish w/view/cust_bill-logo.cgi
1668 my $conf = new FS::Conf;
1669 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1670 $templatename = "_$1";
1675 my $filename = "logo$templatename.png";
1677 return { 'error' => '',
1678 'logo' => $conf->config_binary($filename, $agentnum),
1679 'content_type' => 'image/png', #should allow gif, jpg too
1686 my $session = _cache->get($p->{'session_id'})
1687 or return { 'error' => "Can't resume session" }; #better error message
1689 my $custnum = $session->{'custnum'};
1691 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1692 or return { 'error' => "unknown custnum $custnum" };
1694 my $conf = new FS::Conf;
1696 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1698 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1703 #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1704 my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1705 my $owed = $_->owed;
1707 +{ 'invnum' => $_->invnum,
1708 '_date' => $_->_date,
1709 'date' => time2str("%b %o, %Y", $_->_date),
1710 'date_short' => time2str("%m-%d-%Y", $_->_date),
1711 'previous' => sprintf('%.2f', ($_->previous)[0]),
1712 'charged' => sprintf('%.2f', $_->charged),
1713 'owed' => sprintf('%.2f', $owed),
1714 'balance' => sprintf('%.2f', $balance),
1715 'lastpay' => @payments_and_credits
1716 ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1722 return { 'error' => '',
1723 'balance' => $cust_main->balance,
1724 'money_char' => $conf->config("money_char") || '$',
1725 'invoices' => $invoices,
1726 'legacy_invoices' => [
1728 +{ 'legacyinvnum' => $_->legacyinvnum,
1729 'legacyid' => $_->legacyid,
1730 '_date' => $_->_date,
1731 'date' => time2str("%b %o, %Y", $_->_date),
1732 'date_short' => time2str("%m-%d-%Y", $_->_date),
1733 'charged' => sprintf('%.2f', $_->charged),
1734 'has_content' => ( length($_->content_pdf)
1735 || length($_->content_html) ),
1745 my $session = _cache->get($p->{'session_id'})
1746 or return { 'error' => "Can't resume session" }; #better error message
1748 my $custnum = $session->{'custnum'};
1750 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1751 or return { 'error' => "unknown custnum $custnum" };
1753 return { 'error' => '',
1754 'balance' => $cust_main->balance,
1755 'money_char' => FS::Conf->new->config("money_char") || '$',
1756 'payments' => [ map $_->SSAPI_getinfo, $cust_main->cust_pay ],
1760 sub payment_receipt {
1762 my $session = _cache->get($p->{'session_id'})
1763 or return { 'error' => "Can't resume session" }; #better error message
1765 my $custnum = $session->{'custnum'};
1767 my $cust_pay = qsearchs('cust_pay', { 'custnum' => $custnum,
1768 'paynum' => $p->{'paynum'},
1771 or return { 'error' => "unknown payment ". $p->{'paynum'} };
1775 %{ $cust_pay->SSAPI_getinfo },
1782 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1783 return { 'error' => $session } if $context eq 'error';
1785 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1786 or return { 'error' => "unknown custnum $custnum" };
1790 my $cust_payby = $_;
1792 map { $_ => $cust_payby->$_ }
1793 qw( custpaybynum weight payby paymask paydate
1794 payname paystate paytype
1798 $cust_main->cust_payby
1806 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1807 return { 'error' => $session } if $context eq 'error';
1809 #XXX payinfo1 + payinfo2 for CHEK?
1810 #or take the opportunity to use separate, more well- named fields?
1812 # $p->{'payinfo1'} =~ /^([\dx]+)$/
1813 # or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1814 # my $payinfo1 = $1;
1815 # $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
1816 # or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1817 # my $payinfo2 = $1;
1818 # $payinfo = $payinfo1. '@'. $payinfo2;
1820 my $cust_payby = new FS::cust_payby {
1821 'custnum' => $custnum,
1822 map { $_ => $p->{$_} } qw( weight payby payinfo paycvv paydate payname
1823 paystate paytype payip
1827 my $error = $cust_payby->insert;
1829 return { 'error' => $error };
1831 return { 'custpaybynum' => $cust_payby->custpaybynum };
1839 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1840 return { 'error' => $session } if $context eq 'error';
1842 my $cust_payby = qsearchs('cust_payby', {
1843 'custnum' => $custnum,
1844 'custpaybynum' => $p->{'custpaybynum'},
1846 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1849 qw( weight payby payinfo paycvv paydate payname paystate paytype payip )
1851 next unless exists($p->{$field});
1852 $cust_payby->set($field,$p->{$field});
1855 my $error = $cust_payby->replace;
1857 return { 'error' => $error };
1859 return { 'custpaybynum' => $cust_payby->custpaybynum };
1867 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1868 return { 'error' => $session } if $context eq 'error';
1870 my $cust_payby = qsearchs('cust_payby', {
1871 'custnum' => $custnum,
1872 'custpaybynum' => $p->{'custpaybynum'},
1874 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1876 return { 'error' => $cust_payby->verify };
1883 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1884 return { 'error' => $session } if $context eq 'error';
1886 my $cust_payby = qsearchs('cust_payby', {
1887 'custnum' => $custnum,
1888 'custpaybynum' => $p->{'custpaybynum'},
1890 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1892 my $conf = new FS::Conf;
1893 if (($cust_payby->payby eq "DCHK" || $cust_payby->payby eq "CHEK") && $conf->exists('selfservice-ACH_info_readonly')) {
1894 return { 'error' => "Sorry you do not have permission to delete bank information." };
1897 return { 'error' => $cust_payby->delete };
1903 my $session = _cache->get($p->{'session_id'})
1904 or return { 'error' => "Can't resume session" }; #better error message
1906 my $custnum = $session->{'custnum'};
1908 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1909 or return { 'error' => "unknown custnum $custnum" };
1911 my @errors = $cust_main->cancel( 'quiet'=>1 );
1913 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1915 return { 'error' => $error };
1922 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1923 return { 'error' => $session } if $context eq 'error';
1925 my $pkg = qsearchs({
1926 'table' => 'cust_pkg',
1927 'addl_from' => 'LEFT JOIN part_pkg USING ( pkgpart )',
1929 'custnum' => $custnum,
1930 'pkgnum' => $p->{'pkgnum'},
1933 or return {'error' => 'unknown pkg num $pkgnum'};
1936 pkg_label => $pkg->pkg,
1937 pkgpart => $pkg->pkgpart,
1938 classnum => $pkg->classnum,
1946 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1947 return { 'error' => $session } if $context eq 'error';
1949 my $search = { 'custnum' => $custnum };
1950 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1951 my $cust_main = qsearchs('cust_main', $search )
1952 or return { 'error' => "unknown custnum $custnum" };
1954 my $conf = new FS::Conf;
1955 my $immutable = $conf->exists('selfservice_immutable-package');
1957 # the duplication below is necessary:
1958 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1959 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1960 # non-backwards-compatible change breaking the software of anyone using the API
1961 # instead of the stock selfservice
1962 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1963 if( $conf->exists('selfservice_server-view-wholesale') ) {
1964 return { 'svcnum' => $session->{'svcnum'},
1965 'custnum' => $custnum,
1966 'cust_pkg' => [ map {
1968 immutable => $immutable,
1969 part_pkg => [ map $_->hashref, $_->part_pkg ],
1971 [ map $_->hashref, $_->available_part_svc ],
1973 [ map { my $ref = { $_->hash,
1974 label => [ $_->label ],
1976 $ref->{_password} = $_->svc_x->_password
1977 if $context eq 'agent'
1978 && $conf->exists('agent-showpasswords')
1979 && $_->part_svc->svcdb eq 'svc_acct';
1984 } $cust_main->cust_pkg
1987 small_custview( $cust_main, $conf->config('countrydefault') ),
1988 'wholesale_view' => 1,
1989 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1990 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1991 'lnp' => $conf->exists('svc_phone-lnp'),
1995 { 'svcnum' => $session->{'svcnum'},
1996 'custnum' => $custnum,
1997 'cust_pkg' => [ map {
1998 my $primary_cust_svc = $_->primary_cust_svc;
2001 immutable => $immutable,
2002 pkg_label => $_->pkg_locale,
2003 status => $_->status,
2004 statuscolor => $_->statuscolor,
2006 [ map { $_->hashref }
2007 grep { $_->selfservice_access ne 'hidden' }
2008 $_->available_part_svc
2011 [ map { my $ref = { $_->hash,
2012 label => [ $_->label ],
2014 $ref->{_password} = $_->svc_x->_password
2015 if $context eq 'agent'
2016 && $conf->exists('agent-showpasswords')
2017 && $_->part_svc->svcdb eq 'svc_acct';
2018 $ref->{svchash} = { $_->svc_x->hash } if
2019 $_->part_svc->svcdb eq 'svc_phone';
2020 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
2021 if $_->part_svc->svcdb eq 'svc_phone'; # hack
2024 grep { $_->part_svc->selfservice_access ne 'hidden' }
2029 ? { $primary_cust_svc->hash,
2030 label => [ $primary_cust_svc->label ],
2031 finger => $primary_cust_svc->svc_x->finger, #uuh
2032 $primary_cust_svc->part_svc->hash,
2036 } $cust_main->ncancelled_pkgs
2039 small_custview( $cust_main, $conf->config('countrydefault') ),
2040 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
2048 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2049 return { 'error' => $session } if $context eq 'error';
2051 my $conf = new FS::Conf;
2053 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
2054 my $search = { 'custnum' => $custnum };
2055 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2056 my $cust_main = qsearchs('cust_main', $search )
2057 or return { 'error' => "unknown custnum $custnum" };
2059 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
2060 if ( ! $pkgnum && $p->{'svcnum'} ) {
2061 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
2062 $pkgnum = $cust_svc->pkgnum if $cust_svc;
2066 my @cust_pkg_usage = ();
2067 foreach my $cust_pkg ( $p->{'ncancelled'}
2068 ? $cust_main->ncancelled_pkgs
2069 : $cust_main->unsuspended_pkgs ) {
2070 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
2071 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
2072 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
2075 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
2078 foreach (@cust_pkg_usage) {
2079 my $part = $_->part_pkg_usage;
2080 my $tag = $part->description . ($part->shared ? 1 : 0);
2081 my $row = $usage_pools{$tag}
2082 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
2083 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
2084 $row->[2] += $part->minutes; # minutes total
2086 } # otherwise just leave them empty
2088 if ( $p->{'svcdb'} ) {
2089 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
2091 : ref($p->{'svcdb'}) eq 'ARRAY'
2092 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
2093 : { $p->{'svcdb'} => 1 };
2094 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
2097 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
2100 my @svcs; # stuff to return to the client
2101 my %bytes_used_total; # for _used columns only
2102 foreach my $cust_svc (@cust_svc) {
2103 my $svc_x = $cust_svc->svc_x;
2104 my($label, $value) = $cust_svc->label;
2105 my $part_svc = $cust_svc->part_svc;
2106 my $svcdb = $part_svc->svcdb;
2107 my $cust_pkg = $cust_svc->cust_pkg;
2108 my $part_pkg = $cust_pkg->part_pkg;
2111 'svcnum' => $cust_svc->svcnum,
2112 'display_svcnum' => $cust_svc->display_svcnum,
2116 'pkg_label' => $cust_pkg->pkg_locale,
2117 'pkg_status' => $cust_pkg->status,
2118 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
2121 # would it make sense to put this in a svc_* method?
2123 if (!$hide_usage and grep(/^$svcdb$/, qw(svc_acct svc_broadband)) and $part_svc->part_export_usage) {
2124 my $last_bill = $cust_pkg->last_bill || 0;
2126 my $up_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctInputOctets');
2127 my $down_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctOutputOctets');
2130 'seconds_used' => $cust_svc->seconds_since_sqlradacct($last_bill,$now),
2131 'upbytes_used' => display_bytecount($up_used),
2132 'downbytes_used' => display_bytecount($down_used),
2133 'totalbytes_used' => display_bytecount($up_used + $down_used)
2135 $bytes_used_total{'seconds_used'} += $hash{'seconds_used'};
2136 $bytes_used_total{'upbytes_used'} += $up_used;
2137 $bytes_used_total{'downbytes_used'} += $down_used;
2138 $bytes_used_total{'totalbytes_used'} += $up_used + $down_used;
2141 if ( $svcdb eq 'svc_acct' ) {
2142 foreach (qw(username email finger seconds)) {
2143 $hash{$_} = $svc_x->$_;
2149 'upbytes' => display_bytecount($svc_x->upbytes),
2150 'downbytes' => display_bytecount($svc_x->downbytes),
2151 'totalbytes' => display_bytecount($svc_x->totalbytes),
2153 'recharge_amount' => $part_pkg->option('recharge_amount',1),
2154 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
2155 'recharge_upbytes' =>
2156 display_bytecount($part_pkg->option('recharge_upbytes',1)),
2157 'recharge_downbytes' =>
2158 display_bytecount($part_pkg->option('recharge_downbytes',1)),
2159 'recharge_totalbytes' =>
2160 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
2165 } elsif ( $svcdb eq 'svc_dsl' ) {
2167 $hash{'phonenum'} = $svc_x->phonenum;
2168 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
2169 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
2170 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
2173 $hash{'name'} = $cust_main->name;
2175 # no usage to hide here
2177 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2179 # could potentially show lots of things...
2180 $hash{'outbound'} = 1;
2181 $hash{'inbound'} = 0;
2182 if ( $svcdb eq 'svc_phone' ) {
2183 if ( $part_pkg->plan eq 'voip_inbound' ) {
2184 $hash{'outbound'} = 0;
2185 $hash{'inbound'} = 1;
2186 } elsif ( $part_pkg->option('selfservice_inbound_format')
2187 or $conf->config('selfservice-default_inbound_cdr_format')
2189 $hash{'inbound'} = 1;
2192 foreach (qw(inbound outbound)) {
2193 # hmm...we can't filter by status here, because there might
2194 # not be cdr_terminations at all. have to go by date.
2195 # find all since the last bill date.
2196 # XXX cdr types? we are going to need them.
2198 my $sum_cdr = $svc_x->sum_cdrs(
2199 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
2200 'begin' => ($cust_pkg->last_bill || 0),
2202 'disable_charged_party' => 1,
2204 $hash{$_} = $sum_cdr->hashref;
2207 } # not hiding usage
2211 } # foreach $cust_svc
2213 foreach my $field (keys %bytes_used_total) {
2214 if ($field =~ /bytes/) {
2215 $bytes_used_total{$field} = display_bytecount($bytes_used_total{$field});
2220 'svcnum' => $session->{'svcnum'},
2221 'custnum' => $custnum,
2222 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
2223 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
2225 'bytes_used_total' => \%bytes_used_total,
2227 map { $usage_pools{$_} }
2231 'hide_usage' => $hide_usage,
2236 sub _customer_svc_x {
2237 my($custnum, $svcnum, $table) = (shift, shift, shift);
2238 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
2240 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2241 my $search = " AND custnum = $1";
2242 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2245 'table' => ($table || 'svc_acct'),
2246 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2247 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
2248 #'LEFT JOIN cust_main USING ( custnum ) ',
2249 'hashref' => $hashref,
2250 'extra_sql' => $search, #important
2255 sub svc_status_html {
2258 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2259 return { 'error' => $session } if $context eq 'error';
2261 #XXX only svc_dsl for now
2262 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
2263 or return { 'error' => "Service not found" };
2265 my $html = $svc_x->getstatus_html;
2267 return { 'html' => $html };
2271 sub svc_status_hash {
2274 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2275 return { 'error' => $session } if $context eq 'error';
2277 #XXX only svc_acct for now
2278 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2279 or return { 'error' => "Service not found" };
2281 my ( $html, $hashref ) = $svc_x->export_getstatus;
2286 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
2287 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
2288 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
2289 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
2290 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
2293 my( $p, $method ) = @_;
2295 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2296 return { 'error' => $session } if $context eq 'error';
2298 #XXX only svc_acct for now
2299 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2300 or return { 'error' => "Service not found" };
2302 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
2304 my $error = $svc_x->$method($p); #$p? returns error?
2305 return { 'error' => $error } if $error;
2307 return {}; #? { 'error' => '' }
2311 sub acct_forward_info {
2314 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2315 return { 'error' => $session } if $context eq 'error';
2317 my $svc_forward = _customer_svc_x( $custnum,
2318 { 'srcsvc' => $p->{'svcnum'} },
2321 or return { 'error' => '',
2325 return { 'error' => '',
2326 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2331 sub process_acct_forward {
2333 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2334 return { 'error' => $session } if $context eq 'error';
2336 my $old = _customer_svc_x( $custnum,
2337 { 'srcsvc' => $p->{'svcnum'} },
2341 if ( $p->{'dst'} eq '' ) {
2343 my $error = $old->delete;
2344 return { 'error' => $error };
2346 return { 'error' => '' };
2349 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2350 'dst' => $p->{'dst'},
2355 $new->svcnum($old->svcnum);
2356 my $cust_svc = $old->cust_svc;
2357 $new->svcpart($old->svcpart);
2358 $new->pkgnuym($old->pkgnum);
2359 $error = $new->replace($old);
2361 my $conf = new FS::Conf;
2362 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2364 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2365 or return { 'error' => 'No service' }; #how would we even get here?
2367 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2369 $error = $new->insert;
2372 return { 'error' => $error };
2376 sub list_dsl_devices {
2379 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2380 return { 'error' => $session } if $context eq 'error';
2382 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2383 or return { 'error' => "Service not found" };
2386 'devices' => [ map {
2387 +{ 'mac_addr' => $_->mac_addr };
2388 } $svc_dsl->dsl_device
2394 sub add_dsl_device {
2397 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2398 return { 'error' => $session } if $context eq 'error';
2400 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2401 or return { 'error' => "Service not found" };
2403 return { 'error' => 'No MAC address supplied' }
2404 unless length($p->{'mac_addr'});
2406 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2407 'mac_addr' => scalar($p->{'mac_addr'}),
2409 my $error = $dsl_device->insert;
2410 return { 'error' => $error };
2414 sub delete_dsl_device {
2417 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2418 return { 'error' => $session } if $context eq 'error';
2420 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2421 or return { 'error' => "Service not found" };
2423 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2424 'mac_addr' => scalar($p->{'mac_addr'}),
2427 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2429 my $error = $dsl_device->delete;
2430 return { 'error' => $error };
2436 _usage_details( \&_port_graph, $p,
2437 'svcdb' => 'svc_port',
2442 my($svc_port, $begin, $end) = @_;
2444 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2445 push @usage, { 'png' => $pngOrError };
2449 sub _list_svc_usage {
2450 my($svc_acct, $begin, $end) = @_;
2452 foreach my $part_export (
2453 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2454 qw( sqlradius sqlradius_withdomain )
2456 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2461 sub list_svc_usage {
2462 _usage_details(\&_list_svc_usage, @_);
2465 sub _list_support_usage {
2466 my($svc_acct, $begin, $end) = @_;
2468 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2469 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2471 push @usage, { 'seconds' => $_->seconds,
2472 'support' => $_->support,
2473 '_date' => $_->_date,
2474 'id' => $_->transaction_id,
2475 'creator' => $_->creator,
2476 'subject' => $_->subject,
2477 'status' => $_->status,
2478 'ticketid' => $_->ticketid,
2484 sub list_support_usage {
2485 _usage_details(\&_list_support_usage, @_);
2488 sub _list_cdr_usage {
2489 # XXX CDR type support...
2490 # XXX any way to do a paged search on this?
2491 # we have to return the results all at once...
2492 my($svc_x, $begin, $end, %opt) = @_;
2493 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2497 'disable_charged_party' => 1,
2502 sub list_cdr_usage {
2504 _usage_details( \&_list_cdr_usage, $p );
2507 sub _usage_details {
2508 my($callback, $p, %opt) = @_;
2509 my $conf = FS::Conf->new;
2511 if ( $conf->exists('selfservice_hide-usage') ) {
2512 return { 'error' => 'Viewing usage is not allowed.' };
2515 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2516 return { 'error' => $session } if $context eq 'error';
2518 my $search = { 'svcnum' => $p->{'svcnum'} };
2519 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2521 my $cust_svc = qsearchs( 'cust_svc', $search );
2522 return { 'error' => 'No service selected in list_svc_usage' }
2525 my $svc_x = $cust_svc->svc_x;
2526 my $svcdb = $svc_x->table;
2527 my $cust_pkg = $cust_svc->cust_pkg;
2528 my $freq = $cust_pkg->part_pkg->freq;
2531 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2533 if ( $p->{inbound} ) {
2534 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2535 || $conf->config('selfservice-default_inbound_cdr_format')
2536 || 'source_default';
2537 $callback_opt{inbound} = 1;
2539 $format = $cust_pkg->part_pkg->option('selfservice_format')
2540 || $conf->config('selfservice-default_cdr_format')
2544 $callback_opt{format} = $format;
2545 $callback_opt{use_clid} = 1;
2546 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2549 my $start = $cust_pkg->setup;
2550 #my $end = $cust_pkg->bill; # or time?
2553 unless ( $p->{beginning} ) {
2554 $p->{beginning} = $cust_pkg->last_bill;
2555 $p->{ending} = $end;
2558 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2559 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2561 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2565 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2566 # ugly kludge, I know
2567 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2568 if (defined $delete_col) {
2569 delete($_->[$delete_col]) foreach ($header, @usage);
2573 #kinda false laziness with FS::cust_main::bill, but perhaps
2574 #we should really change this bit to DateTime and DateTime::Duration
2576 #change this bit to use Date::Manip? CAREFUL with timezones (see
2577 # mailing list archive)
2578 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2579 (localtime($p->{ending}) )[0,1,2,3,4,5];
2580 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2581 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2583 if ( $freq =~ /^\d+$/ ) {
2585 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2587 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2588 } elsif ( $freq =~ /^(\d+)w$/ ) {
2590 $nmday += $weeks * 7;
2591 $pmday -= $weeks * 7;
2592 } elsif ( $freq =~ /^(\d+)d$/ ) {
2596 } elsif ( $freq =~ /^(\d+)h$/ ) {
2601 return { 'error' => "unparsable frequency: ". $freq };
2604 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2605 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2609 'svcnum' => $p->{svcnum},
2610 'beginning' => $p->{beginning},
2611 'ending' => $p->{ending},
2612 'inbound' => $p->{inbound},
2613 'previous' => ($previous > $start) ? $previous : $start,
2614 'next' => ($next < $end) ? $next : $end,
2615 'header' => $header,
2623 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2624 return { 'error' => $session } if $context eq 'error';
2626 my $search = { 'custnum' => $custnum };
2627 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2628 my $cust_main = qsearchs('cust_main', $search )
2629 or return { 'error' => "unknown custnum $custnum" };
2631 my $status = $cust_main->status;
2633 my %order_pkg_options = ();
2634 if ( $p->{locationnum} > 0 ) {
2635 $order_pkg_options{locationnum} = delete($p->{locationnum});
2636 } elsif ( $p->{address1} ) {
2637 $order_pkg_options{'cust_location'} = new FS::cust_location {
2638 map { $_ => $p->{$_} }
2639 qw( address1 address2 city county state zip country )
2643 #false laziness w/ClientAPI/Signup.pm
2645 my $cust_pkg = new FS::cust_pkg ( {
2646 'custnum' => $custnum,
2647 'pkgpart' => $p->{'pkgpart'},
2648 'quantity' => $p->{'quantity'} || 1,
2650 my $error = $cust_pkg->check;
2651 return { 'error' => $error } if $error;
2654 unless ( $p->{'svcpart'} eq 'none' ) {
2658 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2660 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2661 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2662 $svcdb = $part_svc->svcdb;
2664 $svcdb = 'svc_acct';
2666 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2669 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2670 'svc_domain' => [ qw( domain ) ],
2671 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2672 'svc_external' => [ qw( id title ) ],
2673 'svc_pbx' => [ qw( id title ) ],
2676 my $svc_x = "FS::$svcdb"->new( {
2677 'svcpart' => $svcpart,
2678 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2681 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2684 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2685 my $acct_snarf = new FS::acct_snarf ( {
2686 'machine' => $p->{"snarf_machine$snarfnum"},
2687 'protocol' => $p->{"snarf_protocol$snarfnum"},
2688 'username' => $p->{"snarf_username$snarfnum"},
2689 '_password' => $p->{"snarf_password$snarfnum"},
2692 push @acct_snarf, $acct_snarf;
2694 $svc_x->child_objects( \@acct_snarf );
2697 my $y = $svc_x->setdefault; # arguably should be in new method
2698 return { 'error' => $y } if $y && !ref($y);
2700 $error = $svc_x->check;
2701 return { 'error' => $error } if $error;
2707 $error = $cust_main->order_pkg(
2708 'cust_pkg' => $cust_pkg,
2713 return { 'error' => $error } if $error;
2715 my $conf = new FS::Conf;
2716 if ( $conf->exists('signup_server-realtime') ) {
2718 my $bill_error = _do_bop_realtime( $cust_main, $status, 'collect'=>$p->{run_bill_events} );
2721 $cust_pkg->cancel('quiet'=>1);
2724 $cust_pkg->reexport;
2728 $cust_pkg->reexport;
2731 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2733 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2740 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2741 return { 'error' => $session } if $context eq 'error';
2743 my $conf = new FS::Conf;
2744 my $immutable = $conf->exists('selfservice_immutable-package');
2745 return { 'error' => "Package modification disabled" } if $immutable;
2747 my $search = { 'custnum' => $custnum };
2748 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2749 my $cust_main = qsearchs('cust_main', $search )
2750 or return { 'error' => "unknown custnum $custnum" };
2752 my $status = $cust_main->status;
2753 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2754 or return { 'error' => "unknown package $p->{pkgnum}" };
2756 #if someone does need self-service package change of suspended packages,
2757 # figure out how to be more discriminating
2758 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2759 if $cust_pkg->status eq 'suspended';
2761 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2762 'quantity' => $p->{'quantity'} || 1,
2765 my $new_pkg = qsearchs('part_pkg', { 'pkgpart' => $p->{pkgpart} } )
2766 or return { 'error' => "unknown package $p->{pkgpart}" };
2768 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2769 unless ref($err_or_cust_pkg);
2772 if ( $conf->exists('signup_server-realtime') ) {
2774 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2777 $err_or_cust_pkg->suspend;
2780 $err_or_cust_pkg->reexport;
2784 $err_or_cust_pkg->reexport;
2787 return { error => '', pkg => $new_pkg->pkg, pkgnum => $err_or_cust_pkg->pkgnum };
2791 sub order_recharge {
2794 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2795 return { 'error' => $session } if $context eq 'error';
2797 my $search = { 'custnum' => $custnum };
2798 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2799 my $cust_main = qsearchs('cust_main', $search )
2800 or return { 'error' => "unknown custnum $custnum" };
2802 my $status = $cust_main->status;
2803 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2804 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2806 my $svc_x = $cust_svc->svc_x;
2807 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2810 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2811 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2812 recharge_totalbytes );
2813 my $amount = $part_pkg->option('recharge_amount', 1);
2815 my ($l, $v, $d) = $cust_svc->label; # blah
2816 my $pkg = "Recharge $v";
2818 my $bill_error = $cust_main->charge($amount, $pkg,
2819 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2820 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2821 $part_pkg->taxclass); #meh
2823 my $conf = new FS::Conf;
2824 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2826 $bill_error = _do_bop_realtime( $cust_main, $status );
2831 my $error = $svc_x->recharge (\%vhash);
2832 return { 'error' => $error } if $error;
2836 my $error = $bill_error;
2837 $error ||= $svc_x->recharge (\%vhash);
2838 return { 'error' => $error } if $error;
2841 return { error => '', svc => $cust_svc->part_svc->svc };
2845 sub _do_bop_realtime {
2846 my ($cust_main, $status, %opt) = @_;
2848 my $old_balance = $cust_main->balance;
2851 my $bill_error = $cust_main->bill(
2852 'return_bill' => \@cust_bill,
2855 $bill_error ||= $cust_main->apply_payments_and_credits;
2857 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2858 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2860 if ( $cust_main->balance > $old_balance
2861 && $cust_main->balance > 0
2862 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2863 || $status eq 'suspended'
2867 unless ( $opt{'no_invoice_void'} ) {
2869 #this used to apply a credit, but now we can void invoices...
2870 foreach my $cust_bill (@cust_bill) {
2871 my $voiderror = $cust_bill->void('automatic payment failed');
2872 warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2877 return { 'error' => '_decline', 'bill_error' => $bill_error };
2880 if ( $opt{'collect'} ) {
2881 my $collect_error = $cust_main->collect();
2882 return { 'error' => '_decline', 'bill_error' => $collect_error }
2883 if $collect_error; #?
2892 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2893 return { 'error' => $session } if $context eq 'error';
2895 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2896 or return { 'error' => "unknown custnum $custnum" };
2898 my @cust_pkg = sort { $a->bill <=> $b->bill }
2899 grep { $_->part_pkg->freq ne '0' }
2900 $cust_main->ncancelled_pkgs;
2902 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2904 my $total = $cust_main->balance;
2907 my $bill = $_->bill;
2908 $total += $_->part_pkg->base_recur($_, \$bill);
2909 my $renew_date = $_->part_pkg->add_freq($_->bill);
2911 'pkgnum' => $_->pkgnum,
2912 'amount' => sprintf('%.2f', $total),
2913 'bill_date' => $_->bill,
2914 'bill_date_pretty' => time2str('%x', $_->bill),
2915 'renew_date' => $renew_date,
2916 'renew_date_pretty' => time2str('%x', $renew_date),
2917 'expire_date' => $_->expire,
2918 'expire_date_pretty' => time2str('%x', $_->expire),
2923 return { 'dates' => \@array };
2927 sub payment_info_renew_info {
2929 my $renew_info = renew_info($p);
2930 my $payment_info = payment_info($p);
2931 return { %$renew_info,
2939 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2940 return { 'error' => $session } if $context eq 'error';
2942 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2943 or return { 'error' => "unknown custnum $custnum" };
2945 my $date = $p->{'date'};
2949 #freeside-daily -n -d $date fs_daily $custnum
2950 $cust_main->bill_and_collect( 'time' => $date,
2951 'invoice_time' => $now,
2952 'actual_time' => $now,
2953 'check_freq' => '1d',
2956 return { 'error' => '' };
2962 my $session = _cache->get($p->{'session_id'})
2963 or return { 'error' => "Can't resume session" }; #better error message
2965 my $custnum = $session->{'custnum'};
2967 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2968 or return { 'error' => "unknown custnum $custnum" };
2970 my $conf = new FS::Conf;
2972 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2973 or return { 'error' => 'Permission denied' };
2975 my $pkgnum = $p->{'pkgnum'};
2977 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2978 'pkgnum' => $pkgnum, } )
2979 or return { 'error' => "unknown pkgnum $pkgnum" };
2981 my $error = $cust_pkg->suspend(reason => $reasonnum);
2982 return { 'error' => $error };
2988 my $session = _cache->get($p->{'session_id'})
2989 or return { 'error' => "Can't resume session" }; #better error message
2991 my $custnum = $session->{'custnum'};
2992 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2993 or return { 'error' => "unknown custnum $custnum" };
2995 my $pkgnum = $p->{'pkgnum'};
2996 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2997 'pkgnum' => $pkgnum, } )
2998 or return { 'error' => "unknown pkgnum $pkgnum" };
3000 my $error = $cust_pkg->cancel( 'quiet' => 1,
3001 'date' => $p->{'date'},
3003 return { 'error' => $error };
3006 sub provision_phone {
3009 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
3011 #editing an existing phone number
3012 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
3013 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3014 return { 'error' => $session } if $context eq 'error';
3016 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
3017 return { 'error' => 'service not found' } unless $svc_phone;
3018 return { 'error' => 'invalid svcnum' }
3019 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
3021 $svc_phone->email($p->{'email'})
3022 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
3023 $svc_phone->forwarddst($p->{'forwarddst'})
3024 if $svc_phone->forwarddst ne $p->{'forwarddst'}
3025 && $p->{'forwarddst'} =~ /^(\d+|)$/;
3026 return { 'error' => $svc_phone->replace };
3030 unless ( $p->{'lnp'} ) {
3031 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
3032 $p->{'lnp_status'} = "portingin";
3033 return _provision( 'FS::svc_phone',
3034 [qw(lnp_desired_due_date lnp_other_provider
3035 lnp_other_provider_account phonenum countrycode lnp_status)],
3036 [qw(phonenum countrycode)],
3042 # single DID order (the usual case)
3043 unless (scalar(@bulkdid)) {
3044 return _provision( 'FS::svc_phone',
3045 [qw(phonenum countrycode)],
3046 [qw(phonenum countrycode)],
3052 # bulk DID order case
3054 foreach my $did ( @bulkdid ) {
3055 $did =~ s/[^0-9]//g;
3056 $error = _provision( 'FS::svc_phone',
3057 [qw(phonenum countrycode)],
3058 [qw(phonenum countrycode)],
3060 'pkgnum' => $p->{'pkgnum'},
3061 'svcpart' => $p->{'svcpart'},
3063 'countrycode' => $p->{'countrycode'},
3064 'session_id' => $p->{'session_id'},
3067 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
3069 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
3074 warn "provision_pbx called\n"
3077 warn "provision_pbx calling _provision\n"
3079 _provision( 'FS::svc_pbx',
3080 [qw(id title max_extensions max_simultaneous ip_addr)],
3081 [qw(id title max_extensions max_simultaneous ip_addr)],
3087 sub provision_acct {
3089 warn "provision_acct called\n"
3092 return { 'error' => gettext('passwords_dont_match') }
3093 if $p->{'_password'} ne $p->{'_password2'};
3094 return { 'error' => gettext('empty_password') }
3095 unless length($p->{'_password'});
3097 if ($p->{'domsvc'}) {
3098 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
3099 qw ( svcpart pkgnum ) );
3100 return { 'error' => gettext('invalid_domain') }
3101 unless ($domains{$p->{'domsvc'}});
3104 warn "provision_acct calling _provision\n"
3106 _provision( 'FS::svc_acct',
3107 [qw(username _password domsvc)],
3108 [qw(username _password domsvc)],
3114 sub provision_external {
3116 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
3117 _provision( 'FS::svc_external',
3125 sub provision_forward {
3127 _provision( 'FS::svc_forward',
3128 ['srcsvc','src','dstsvc','dst'],
3135 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
3136 warn "_provision called for $class\n"
3139 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3140 return { 'error' => $session } if $context eq 'error';
3142 my $search = { 'custnum' => $custnum };
3143 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3144 my $cust_main = qsearchs('cust_main', $search )
3145 or return { 'error' => "unknown custnum $custnum" };
3147 my $pkgnum = $p->{'pkgnum'};
3149 warn "searching for custnum $custnum pkgnum $pkgnum\n"
3151 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3152 'pkgnum' => $pkgnum,
3154 or return { 'error' => "unknown pkgnum $pkgnum" };
3156 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
3158 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
3159 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
3161 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
3162 if $class ne 'FS::'. $part_svc->svcdb;
3164 warn "creating $class record\n"
3166 my $svc_x = $class->new( {
3167 'pkgnum' => $p->{'pkgnum'},
3168 'svcpart' => $p->{'svcpart'},
3169 map { $_ => $p->{$_} } @$fields
3172 my %insert_args = ();
3173 #i shouldn't be a special case here (pass an option or something)
3174 if ( $class eq 'FS::svc_phone'
3175 && grep length($p->{$_}), @location_editable_fields
3178 $insert_args{'cust_location'} = new FS::cust_location {
3179 map { $_ => $p->{$_} } @location_editable_fields
3183 warn "inserting $class record\n"
3185 my $error = $svc_x->insert(%insert_args);
3188 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
3190 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
3193 my $return = { 'svc' => $part_svc->svc,
3195 map { $_ => $svc_x->get($_) } @$return_fields
3197 warn "_provision returning ". Dumper($return). "\n"
3206 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3207 return { 'error' => $session } if $context eq 'error';
3209 my $search = { 'custnum' => $custnum };
3210 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3211 my $cust_main = qsearchs('cust_main', $search )
3212 or return { 'error' => "unknown custnum $custnum" };
3214 my $pkgnum = $p->{'pkgnum'};
3216 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3217 'pkgnum' => $pkgnum,
3219 or return { 'error' => "unknown pkgnum $pkgnum" };
3221 my $svcpart = $p->{'svcpart'};
3223 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
3224 'svcpart' => $svcpart, } )
3225 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
3226 my $part_svc = $pkg_svc->part_svc;
3228 my $conf = new FS::Conf;
3231 'svc' => $part_svc->svc,
3232 'svcdb' => $part_svc->svcdb,
3233 'pkgnum' => $pkgnum,
3234 'svcpart' => $svcpart,
3235 'custnum' => $custnum,
3237 'security_phrase' => 0, #XXX !
3238 'svc_acct_pop' => [], #XXX !
3240 'init_popstate' => '',
3245 small_custview( $cust_main, $conf->config('countrydefault') ),
3249 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
3250 && $ret->{'svcdb'} eq 'svc_phone') {
3251 $ret->{'svcnum'} = $p->{'svcnum'};
3252 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
3253 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
3254 $ret->{'email'} = $svc_phone->email;
3255 $ret->{'forwarddst'} = $svc_phone->forwarddst;
3259 if ($ret->{'svcdb'} eq 'svc_forward') {
3260 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
3266 sub unprovision_svc {
3269 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3270 return { 'error' => $session } if $context eq 'error';
3272 my $search = { 'custnum' => $custnum };
3273 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3274 my $cust_main = qsearchs('cust_main', $search )
3275 or return { 'error' => "unknown custnum $custnum" };
3277 my $svcnum = $p->{'svcnum'};
3279 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
3280 or return { 'error' => "unknown svcnum $svcnum" };
3282 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
3283 unless $cust_svc->cust_pkg->custnum == $custnum;
3285 my $conf = new FS::Conf;
3287 return { 'svc' => $cust_svc->part_svc->svc,
3288 'error' => $cust_svc->cancel,
3290 small_custview( $cust_main, $conf->config('countrydefault') ),
3295 sub myaccount_passwd {
3297 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3298 return { 'error' => $session } if $context eq 'error';
3300 return { 'error' => "New passwords don't match." }
3301 if $p->{'new_password'} ne $p->{'new_password2'};
3303 return { 'error' => 'Enter new password' }
3304 unless length($p->{'new_password'});
3306 #my $search = { 'custnum' => $custnum };
3307 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3308 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3309 my $search = " AND custnum = $1";
3310 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3312 my $svc_acct = qsearchs( {
3313 'table' => 'svc_acct',
3314 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3315 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3316 'LEFT JOIN cust_main USING ( custnum ) ',
3317 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3318 'extra_sql' => $search, #important
3320 or return { 'error' => "Service not found" };
3324 my $conf = new FS::Conf;
3326 return { 'error' => 'Incorrect current password.' }
3327 if ( exists($p->{'old_password'})
3328 || $conf->exists('selfservice-password_change_oldpass')
3330 && ! $svc_acct->check_password($p->{'old_password'});
3332 $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3333 || $svc_acct->set_password($p->{'new_password'})
3334 || $svc_acct->replace();
3336 #regular pw change in self-service should change contact pw too, otherwise its
3337 #way too confusing. hell its confusing they're separate at all, but alas.
3338 #need to support the "ISP provides email that's used as a contact email" case
3340 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3341 if ( $contact && $contact->custnum == $custnum ) {
3342 #svc_acct was successful but this one returns an error? "shouldn't happen"
3343 #don't recheck is_password_allowed here; if the svc_acct password was
3344 #legal, that's good enough
3345 $error ||= $contact->change_password($p->{'new_password'});
3348 my($label, $value) = $svc_acct->cust_svc->label;
3350 return { 'error' => $error,
3360 my $info = skin_info($p);
3362 my $conf = new FS::Conf;
3363 my $verification = $conf->config('selfservice-password_reset_verification')
3364 or return { %$info, 'error' => 'Password resets disabled' };
3369 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3371 $contact = FS::contact->by_selfservice_email($p->{'email'});
3373 $cust_main = $contact->cust_main if $contact;
3375 #also look for an svc_acct, otherwise it would be super confusing
3377 my($username, $domain) = split('@', $p->{'email'});
3378 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3379 if ( $svc_domain ) {
3380 $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3381 'domsvc' => $svc_domain->svcnum }
3384 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3385 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3387 #precaution: don't change svc_acct password not part of the same
3388 # customer as contact
3389 $svc_acct = '' if ! $cust_pkg
3390 || $cust_pkg->custnum != $cust_main->custnum;
3395 return { %$info, 'error' => 'Email address not found' }
3396 unless $contact || $svc_acct;
3398 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3400 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3401 or return { %$info, 'error' => 'Account not found' };
3403 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3404 'domsvc' => $svc_domain->svcnum }
3406 or return { %$info, 'error' => 'Account not found' };
3408 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3409 or return { %$info, 'error' => 'Account not found' };
3411 $cust_main = $cust_pkg->cust_main;
3416 'email' => sub { 1; },
3418 my( $p, $cust_main ) = @_;
3419 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3420 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3423 my( $p, $cust_main ) = @_;
3424 my $cust_pay = qsearchs({
3425 'table' => 'cust_pay',
3426 'hashref' => { 'custnum' => $cust_main->custnum },
3427 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3431 $p->{'amount'} == $cust_pay->paid;
3434 my( $p, $cust_main ) = @_;
3435 $p->{'zip'} eq $cust_main->zip
3436 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3440 foreach my $verify ( split(',', $verification) ) {
3442 &{ $verify{$verify} }( $p, $cust_main )
3443 or return { %$info, 'error' => 'Account not found' };
3447 #okay, we're verified
3451 my $error = $contact->send_reset_email(
3452 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3456 return { %$info, 'error' => $error }; #????
3459 } elsif ( $svc_acct ) {
3461 #create a unique session
3463 my $reset_session = {
3464 'svcnum' => $svc_acct->svcnum,
3465 'agentnum' => $svc_acct->cust_main->agentnum,
3468 my $timeout = '1 hour'; #?
3470 my $reset_session_id;
3472 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3473 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3476 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3480 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3481 $cust_main->agentnum);
3482 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3483 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3485 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3486 my $error = $msg_template->send( 'cust_main' => $cust_main,
3487 'object' => $svc_acct,
3488 'substitutions' => {
3489 'session_id' => $reset_session_id,
3493 return { %$info, 'error' => $error }; #????
3498 return { %$info, 'error' => '' };
3501 sub check_reset_passwd {
3504 my $conf = new FS::Conf;
3505 my $verification = $conf->config('selfservice-password_reset_verification')
3506 or return { 'error' => 'Password resets disabled' };
3508 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3509 or return { 'error' => "Can't resume session" }; #better error message
3511 if ( $reset_session->{'svcnum'} ) {
3513 my $svcnum = $reset_session->{'svcnum'};
3515 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3516 or return { 'error' => "Service not found" };
3518 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3519 my $info = skin_info($p);
3523 'session_id' => $p->{'session_id'},
3524 'username' => $svc_acct->username,
3527 } elsif ( $reset_session->{'contactnum'} ) {
3529 my $contactnum = $reset_session->{'contactnum'};
3531 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3532 or return { 'error' => "Contact not found" };
3534 my @contact_email = $contact->contact_email;
3535 return { 'error' => 'No contact email' } unless @contact_email;
3537 $p->{'agentnum'} = $contact->cust_main->agentnum;
3538 my $info = skin_info($p);
3542 'session_id' => $p->{'session_id'},
3543 'email' => $contact_email[0]->email, #the first?
3548 return { 'error' => 'No svcnum or contactnum in session' }; #??
3554 sub process_reset_passwd {
3557 my $conf = new FS::Conf;
3558 my $verification = $conf->config('selfservice-password_reset_verification')
3559 or return { 'error' => 'Password resets disabled' };
3561 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3562 or return { 'error' => "Can't resume session" }; #better error message
3567 if ( $reset_session->{'svcnum'} ) {
3569 my $svcnum = $reset_session->{'svcnum'};
3571 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3572 or return { 'error' => "Service not found" };
3574 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3575 $info ||= skin_info($p);
3580 if ( $reset_session->{'contactnum'} ) {
3582 my $contactnum = $reset_session->{'contactnum'};
3584 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3585 or return { 'error' => "Contact not found" };
3587 $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3588 $info ||= skin_info($p);
3592 return { %$info, 'error' => "New passwords don't match." }
3593 if $p->{'new_password'} ne $p->{'new_password2'};
3595 return { %$info, 'error' => 'Enter new password' }
3596 unless length($p->{'new_password'});
3600 my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3601 || $svc_acct->set_password($p->{'new_password'})
3602 || $svc_acct->replace();
3604 return { %$info, 'error' => $error } if $error;
3606 #my($label, $value) = $svc_acct->cust_svc->label;
3607 #return { 'error' => $error,
3608 # #'label' => $label,
3609 # #'value' => $value,
3616 my $error = $contact->is_password_allowed($p->{'new_password'})
3617 || $contact->change_password($p->{'new_password'});
3619 return { %$info, 'error' => $error }; # if $error;
3623 #password changed ,so remove session, don't want it reused
3624 _cache->remove($p->{'session_id'});
3626 return { %$info, 'error' => '' };
3630 sub validate_passwd {
3634 %result = ( 'fieldid' => $p->{'fieldid'} )
3635 if $p->{'fieldid'} =~ /^\w+$/;
3637 return { %result, 'password_invalid' => 'Enter new password' }
3638 unless length($p->{'check_password'});
3641 if ($p->{'svcnum'}) {
3642 # false laziness with myaccount_passwd
3643 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3644 return { %result, 'error' => $session } if $context eq 'error';
3646 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3647 my $search = " AND custnum = $1";
3648 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3650 $svc_acct = qsearchs( {
3651 'table' => 'svc_acct',
3652 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3653 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3654 'LEFT JOIN cust_main USING ( custnum ) ',
3655 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3656 'extra_sql' => $search, #important
3658 or return { %result, 'error' => "Service not found" };
3659 # end false laziness
3662 unless ($svc_acct) {
3663 my $conf = new FS::Conf;
3664 my $agentnum = $p->{'agentnum'};
3665 return { %result, 'password_valid' => 1 }
3666 if $conf->config_bool('password-insecure', $p->{'agentnum'});
3669 $svc_acct ||= new FS::svc_acct {};
3671 my $error = $svc_acct->is_password_allowed($p->{'check_password'});
3672 return { %result, 'password_invalid' => $error } if $error;
3673 return { %result, 'password_valid' => 1 };
3678 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3679 return { 'error' => $session } if $context eq 'error';
3682 if ( $session->{'pkgnum'} ) {
3684 #tickets for specific service with pkg-balances on
3685 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3686 'pkgnum' => $session->{'pkgnum'} })
3687 or return { 'error' => 'unknown package' };
3688 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3689 push @tickets, $cust_svc->tickets( $p->{status} );
3694 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3695 or return { 'error' => "unknown custnum $custnum" };
3697 @tickets = $cust_main->tickets( $p->{status} );
3700 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3701 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3702 my $conf = new FS::Conf;
3703 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3707 ($a->{'_selfservice_priority'} eq '') <=>
3708 ($b->{'_selfservice_priority'} eq '')
3711 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3717 +{ tickets => \@tickets };
3724 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3725 return { 'error' => $session } if $context eq 'error';
3727 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3728 FS::TicketSystem->init();
3730 my $conf = new FS::Conf;
3731 my $queue = $p->{'queue'}
3732 || $conf->config('ticket_system-selfservice_queueid')
3733 || $conf->config('ticket_system-default_queueid');
3735 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3736 my $err_or_ticket = FS::TicketSystem->create_ticket(
3737 '', #create RT session based on FS CurrentUser (fs_selfservice)
3739 'custnum' => $custnum,
3740 'svcnum' => $session->{'svcnum'},
3741 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3744 if ( ref($err_or_ticket) ) {
3745 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3747 return { 'error' => '',
3748 'ticket_id' => $err_or_ticket->id,
3751 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3753 return { 'error' => $err_or_ticket };
3761 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3762 return { 'error' => $session } if $context eq 'error';
3764 return { error => 'requested format not implemented' }
3765 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3767 my $conf = new FS::Conf;
3768 my $age_threshold = 0;
3769 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3770 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3772 my $search = { 'custnum' => $custnum };
3773 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3774 my $cust_main = qsearchs('cust_main', $search )
3775 or return { 'error' => "unknown custnum $custnum" };
3777 # does it make more sense to just run one sql query for this instead of all the
3778 # insanity below? would increase performance greately for large data sets?
3780 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3781 my @part_svc = $cust_pkg->part_svc;
3782 foreach my $part_svc ( @part_svc ) {
3783 if($part_svc->svcdb eq 'svc_phone'){
3784 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3785 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3786 push @svc_phone, $cust_pkg_svc->svc_x
3787 if $cust_pkg_svc->date_inserted >= $age_threshold;
3795 my($xls_r,$xls_c) = (0,0);
3798 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3799 if($p->{'format'} eq 'csv') {
3800 $csv = new Text::CSV_XS { 'always_quote' => 1,
3803 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3804 $content .= $csv->string;
3806 elsif($p->{'format'} eq 'xls') {
3807 my $XLS1 = new IO::Scalar \$content;
3808 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3809 or return { 'error' => "Error opening .xls file: $!" };
3810 $xls = $xls_workbook->add_worksheet('DIDs');
3811 foreach ( @fields ) {
3812 $xls->write(0,$xls_c++,$_);
3817 foreach my $svc_phone ( @svc_phone ) {
3818 my @cols = map { $svc_phone->$_ } @fields;
3819 if($p->{'format'} eq 'csv') {
3820 return { 'error' => 'Unable to create CSV' }
3821 unless $csv->combine(@cols);
3822 $content .= $csv->string;
3824 elsif($p->{'format'} eq 'xls') {
3827 $xls->write($xls_r,$xls_c++,$_);
3833 $xls_workbook->close() if $p->{'format'} eq 'xls';
3835 { content => $content, format => $p->{'format'}, };
3840 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3841 return { 'error' => $session } if $context eq 'error';
3843 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3844 # FS::TicketSystem->init();
3845 # return { 'error' => 'get_ticket configuration error' }
3846 # if $FS::TicketSystem::system ne 'RT_Internal';
3848 # check existence and ownership as part of this
3849 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3850 my $rt_session = FS::TicketSystem->session('');
3851 my $Ticket = FS::TicketSystem->get_ticket_object(
3853 ticket_id => $p->{'ticket_id'},
3856 return { 'error' => 'ticket not found' } if !$Ticket;
3858 if ( length( $p->{'subject'} || '' ) ) {
3860 if ( $p->{'subject'} ne $Ticket->Subject ) {
3861 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3862 return { 'error' => "unable to set subject: $msg" } if !$val;
3866 if(length($p->{'reply'})) {
3867 my @err_or_res = FS::TicketSystem->correspond_ticket(
3869 'ticket_id' => $p->{'ticket_id'},
3870 'content' => $p->{'reply'},
3873 return { 'error' => 'unable to reply to ticket' }
3874 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3877 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3878 my $err_or_ticket = FS::TicketSystem->get_ticket(
3880 'ticket_id' => $p->{'ticket_id'},
3883 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3884 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3886 return { 'error' => $err_or_ticket };
3889 my @custs = @{$err_or_ticket->{'custs'}};
3890 my @txns = @{$err_or_ticket->{'txns'}};
3893 # superseded by check in get_ticket_object
3894 #return { 'error' => 'invalid ticket requested' }
3895 #unless grep($_ eq $custnum, @custs);
3897 foreach my $txn ( @txns ) {
3898 push @filtered_txns, $txn
3899 if ($txn->{'type'} eq 'EmailRecord'
3900 || $txn->{'type'} eq 'Correspond'
3901 || $txn->{'type'} eq 'Create');
3904 warn "$me get_ticket: successful: \n"
3906 return { 'error' => '',
3907 'transactions' => \@filtered_txns,
3908 'ticket_fields' => $err_or_ticket->{'fields'},
3909 'ticket_id' => $p->{'ticket_id'},
3913 sub adjust_ticket_priority {
3915 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3916 return { 'error' => $session } if $context eq 'error';
3918 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3919 # FS::TicketSystem->init;
3920 my $ss_priority = FS::TicketSystem->selfservice_priority;
3922 return { 'error' => 'adjust_ticket_priority configuration error' }
3923 if $FS::TicketSystem::system ne 'RT_Internal'
3926 my $values = $p->{'values'}; #hashref, id => priority value
3929 foreach my $id (keys %$values) {
3930 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3931 my $Ticket = FS::TicketSystem->get_ticket_object('',
3933 'custnum' => $custnum,
3936 $ticket_error{$id} = 'ticket not found';
3940 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3941 # We're not going to implement it for RT_External.
3942 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3943 my $new_value = $values->{$id};
3944 next if $old_value eq $new_value;
3946 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3948 # AddCustomFieldValue works fine (replacing any existing value) if it's
3949 # a single-valued custom field, which it should be. If it's not, you're
3950 # doing something wrong.
3952 if ( length($new_value) ) {
3953 ($val, $msg) = $Ticket->AddCustomFieldValue(
3954 Field => $ss_priority,
3955 Value => $new_value,
3959 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3960 Field => $ss_priority,
3961 Value => $old_value,
3965 $ticket_error{$id} = $msg if !$val;
3966 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3968 return { 'error' => '',
3969 'ticket_error' => \%ticket_error,
3970 %{ customer_info($p) } # send updated customer info back
3976 sub _custoragent_session_custnum {
3979 my($context, $session, $custnum);
3980 if ( $p->{'session_id'} ) {
3982 $context = 'customer';
3983 $session = _cache->get($p->{'session_id'})
3984 or return ( 'error' => "Can't resume session" ); #better error message
3985 $custnum = $session->{'custnum'};
3987 } elsif ( $p->{'agent_session_id'} ) {
3990 my $agent_cache = new FS::ClientAPI_SessionCache( {
3991 'namespace' => 'FS::ClientAPI::Agent',
3993 $session = $agent_cache->get($p->{'agent_session_id'})
3994 or return ( 'error' => "Can't resume session" ); #better error message
3995 $custnum = $p->{'custnum'};
3999 return ( 'error' => "Can't resume session" ); #better error message
4002 ($context, $session, $custnum);