1 package FS::ClientAPI::MyAccount;
3 use 5.008; #require 5.8+ for Time::Local 1.05+
5 use vars qw( $cache $DEBUG $me );
6 use subs qw( _cache _provision );
9 use Digest::MD5 qw(md5_hex);
10 use Digest::SHA qw(sha512_hex);
13 use Time::Local qw(timelocal_nocheck);
14 use Business::CreditCard 0.35;
17 use Spreadsheet::WriteExcel;
18 use OLE::Storage_Lite;
19 use FS::UI::Web::small_custview qw(small_custview); #less doh
21 use FS::UI::bytecount qw( display_bytecount );
24 use FS::Record qw(qsearch qsearchs dbh);
25 use FS::Msgcat qw(gettext);
26 use FS::Misc qw(card_types money_pretty);
27 use FS::Misc::DateTime qw(parse_datetime);
29 use FS::ClientAPI_SessionCache;
41 use FS::legacy_cust_bill;
42 use FS::cust_main_county;
46 use FS::acct_rt_transaction;
50 use FS::cust_location;
53 # for code organization
54 use FS::ClientAPI::MyAccount::contact;
55 use FS::ClientAPI::MyAccount::quotation;
58 $me = '[FS::ClientAPI::MyAccount]';
60 use vars qw( @cust_main_editable_fields @location_editable_fields );
61 @cust_main_editable_fields = qw(
62 first last company daytime night fax mobile
64 ss stateid stateid_state
66 @location_editable_fields = qw(
67 address1 address2 city county state zip country
71 BEGIN { #preload to reduce time customer_info takes
72 if ( $FS::TicketSystem::system ) {
73 warn "$me: initializing ticket system\n" if $DEBUG;
74 FS::TicketSystem->init();
79 $cache ||= new FS::ClientAPI_SessionCache( {
80 'namespace' => 'FS::ClientAPI::MyAccount',
87 my($context, $session, $custnum) = _custoragent_session_custnum($p);
88 #return { 'error' => $session } if $context eq 'error';
90 my $domain = $session->{'domain'};
93 if ( $context eq 'customer' && $custnum ) {
95 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
98 $sth->execute($custnum) or die $sth->errstr;
100 $agentnum = $sth->fetchrow_arrayref->[0]
101 or die "no agentnum for custnum $custnum";
103 #} elsif ( $context eq 'agent' ) {
104 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
107 $p->{'agentnum'} = $agentnum;
109 my $conf = new FS::Conf;
110 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
111 #false laziness w/Signup.pm
113 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
115 if ( $skin_info_cache_agent ) {
117 warn "$me loading cached skin info for agentnum $agentnum\n"
122 warn "$me populating skin info cache for agentnum $agentnum\n"
125 my $menu = $conf->config("ng_selfservice-menu", $agentnum );
127 $skin_info_cache_agent = {
128 'agentnum' => $agentnum,
129 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
130 qw( company_name date_format ) ),
131 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
132 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
133 text_color link_color vlink_color hlink_color alink_color
134 font title_color title_align title_size menu_bgcolor menu_fontsize
137 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
138 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
139 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo enable_payment_without_balance )
141 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
142 qw( title_left_image title_right_image
143 menu_top_image menu_body_image menu_bottom_image
146 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
147 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
148 qw( head body_header body_footer company_address ) ),
149 'money_char' => $conf->config("money_char") || '$',
150 'menu' => _menu($domain,$menu),
153 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent, $timeout);
157 #{ %$skin_info_cache_agent };
158 $skin_info_cache_agent;
162 ## checks if page is in menu listing, if not sends to main with error.
167 return if $p->{'page'} eq "index.php";
168 return if $p->{'page'} eq "ip_login.php";
170 return if substr($p->{'page'}, 0, length("process_")) eq "process_";
172 my $conf = new FS::Conf;
174 my($context, $session, $custnum) = _custoragent_session_custnum($p);
176 my $domain = ref($session) ? $session->{'domain'} : '';
179 if ( $context eq 'customer' && $custnum ) {
181 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
184 $sth->execute($custnum) or die $sth->errstr;
186 $agentnum = $sth->fetchrow_arrayref->[0]
187 or die "no agentnum for custnum $custnum";
189 #} elsif ( $context eq 'agent' ) {
190 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
193 $p->{'agentnum'} = $agentnum;
195 my $menu = $conf->config("ng_selfservice-menu", $agentnum );
197 my $allowed_pages = _menu($domain,$menu);
200 my @lines = split /\n/, $allowed_pages;
201 foreach my $line (@lines) {
202 chomp; # remove newlines
203 $line =~ s/^\s+//; # remove leading whitespace
204 next unless length($line);
205 my (@pages) = split(/ /, $line, 2);
206 $allowed{$pages[0]} = $pages[1];
209 $error = "You do not have access to the page ".$allowed{$p->{page}} unless $allowed{$p->{page}};
211 return { 'error' => $error, };
221 if ($p eq 'ip_mac') {
222 $menu = 'main.php Home
225 payment_cc.php Credit Card Payment
226 payment_ach.php Electronic Check Payment
227 payment_paypal.php PayPal Payment
228 payment_webpay.php Webpay Payments
236 $menu = join("\n", $m ) ||
239 services.php Services
240 services.php My Services
241 services_new.php Order a new service
244 personal.php Personal Information
245 password.php Change Password
248 payment_cc.php Credit Card Payment
249 payment_ach.php Electronic Check Payment
250 payment_paypal.php PayPal Payment
251 payment_webpay.php Webpay Payments
254 usage_data.php Data usage
255 usage_cdr.php Call usage
257 tickets.php Help Desk
258 tickets.php Open Tickets
259 tickets_resolved.php Resolved Tickets
260 ticket_create.php Create a new ticket
270 sub get_mac_address {
273 ## access radius exports acct tables to get mac
274 my @part_export = ();
276 qsearch( 'part_export', { 'exporttype' => 'sqlradius' } ),
277 qsearch( 'part_export', { 'exporttype' => 'sqlradius_withdomain' } ),
278 qsearch( 'part_export', { 'exporttype' => 'broadband_sqlradius' } ),
282 foreach my $part_export (@part_export) {
283 push @sessions, ( @{ $part_export->usage_sessions( {
285 'session_status' => 'open',
289 return { 'mac_address' => $sessions[0]->{'callingstationid'}, };
295 my $conf = new FS::Conf;
299 'phone_login' => $conf->exists('selfservice_server-phone_login'),
300 'single_domain' => scalar($conf->config('selfservice_server-single_domain')),
301 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
302 'banner_image_md5' =>
303 md5_hex($conf->config_binary('selfservice-login_banner_image')),
310 sub login_banner_image {
312 my $conf = new FS::Conf;
313 my $image = $conf->config_binary('selfservice-login_banner_image');
315 'md5' => md5_hex($image),
320 #false laziness w/FS::ClientAPI::passwd::passwd
324 my $conf = new FS::Conf;
328 if ( $p->{'domain'} eq 'svc_phone'
329 && $conf->exists('selfservice_server-phone_login') ) {
331 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
332 return { error => 'Number not found.' } unless $svc_phone;
335 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
336 #return { error => 'Only primary user may log in.' }
337 # if $conf->exists('selfservice_server-primary_only')
338 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
340 return { error => 'Incorrect PIN.' }
341 unless $svc_phone->check_pin($p->{'password'});
345 } elsif ( $p->{'domain'} eq 'ip_mac' ) {
347 return { error => 'MAC address empty '.$p->{'username'} }
348 unless $p->{'username'};
350 my $mac_address = $p->{'username'};
351 $mac_address =~ s/[\:\,\-\. ]//g;
352 $mac_address =~ tr/[a-z]/[A-Z/;
354 my $svc_broadband = qsearchs( 'svc_broadband', { 'mac_addr' => $mac_address } );
355 return { error => 'MAC address not found '.$p->{'username'} }
356 unless $svc_broadband;
357 $svc_x = $svc_broadband;
359 $session->{'domain'} = $p->{'domain'};
361 } elsif ( $p->{email}
362 && (my $contact = FS::contact->by_selfservice_email($p->{email}))
365 return { error => 'Incorrect contact password.' }
366 unless $contact->authenticate_password($p->{'password'});
368 $session->{'contactnum'} = $contact->contactnum;
370 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
371 if ( scalar(@cust_contact) == 1 ) {
372 $session->{'custnum'} = $cust_contact[0]->custnum;
373 } elsif ( scalar(@cust_contact) ) {
374 $session->{'customers'} = { map { $_->custnum => $_->cust_main->name }
378 return { error => 'No customer self-service access for contact' }; #??
383 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
385 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
386 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
388 my @svc_acct = qsearch( 'svc_acct', { 'username' => $p->{'username'},
389 'domsvc' => $svc_domain->svcnum, }
392 if ( $conf->exists('selfservice_server-login_svcpart') ) {
393 my @svcpart = $conf->config('selfservice_server-login_svcpart');
394 @svc_acct = grep { my $svcpart = $_->cust_svc->svcpart;
395 scalar( grep( $_ eq $svcpart, @svcpart ) );
400 if ( $conf->exists('selfservice_server-primary_only') ) {
403 my $cust_svc = $_->cust_svc;
404 $cust_svc->cust_pkg->part_pkg->svcpart([qw( svc_acct svc_phone )])
405 == $cust_svc->svcpart
410 return { error => 'User not found.' } unless @svc_acct;
412 return { error => 'Multiple users.' } if scalar(@svc_acct) > 1;
414 my $svc_acct = $svc_acct[0];
416 if ( $conf->exists('selfservice_server-login_svcpart') ) {
417 my @svcpart = $conf->config('selfservice_server-login_svcpart');
418 my $svcpart = $svc_acct->cust_svc->svcpart;
419 return { error => 'Invalid user.' }
420 unless grep($_ eq $svcpart, @svcpart);
423 return { error => 'Incorrect password.' }
424 unless $svc_acct->check_password($p->{'password'});
432 $session->{'svcnum'} = $svc_x->svcnum;
434 my $cust_svc = $svc_x->cust_svc;
435 my $cust_pkg = $cust_svc->cust_pkg;
437 my $cust_main = $cust_pkg->cust_main;
438 $session->{'custnum'} = $cust_main->custnum;
439 if ( $conf->exists('pkg-balances') ) {
440 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
441 $cust_main->ncancelled_pkgs;
442 $session->{'pkgnum'} = $cust_pkg->pkgnum
443 if scalar(@cust_pkg) > 1;
447 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
448 #return { error => 'Only primary user may log in.' }
449 # if $conf->exists('selfservice_server-primary_only')
450 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
451 my $part_pkg = $cust_pkg->part_pkg;
452 return { error => 'Only primary user may log in.' }
453 if $conf->exists('selfservice_server-primary_only')
454 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
460 $session_id = sha512_hex(time(). {}. rand(). $$)
461 } until ( ! defined _cache->get($session_id) ); #just in case
463 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
464 _cache->set( $session_id, $session, $timeout );
466 return { 'error' => '',
467 'session_id' => $session_id,
474 my $skin_info = skin_info($p);
475 if ( $p->{'session_id'} ) {
476 _cache->remove($p->{'session_id'});
477 return { %$skin_info, 'error' => '' };
479 return { %$skin_info, 'error' => "Can't resume session" }; #better error message
486 my($context, $session, $custnum) = _custoragent_session_custnum($p);
487 return { 'error' => $session } if $context eq 'error';
489 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
490 or return { 'error' => "Service not found" };
492 $session->{'svcnum'} = $svc_acct->svcnum;
494 my $conf = new FS::Conf;
495 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
496 _cache->set( $p->{'session_id'}, $session, $timeout );
498 return { 'error' => '' };
504 my($context, $session, $custnum) = _custoragent_session_custnum($p);
505 return { 'error' => $session } if $context eq 'error';
507 $session->{'custnum'} = $p->{'custnum'}
508 if exists $session->{'customers'}{ $p->{'custnum'} };
510 my $conf = new FS::Conf;
511 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
512 _cache->set( $p->{'session_id'}, $session, $timeout );
514 return { 'error' => '',
515 %{ customer_info( { session_id=>$p->{'session_id'} } ) },
519 sub payment_gateway {
521 # takes a cust_main and a cust_payby entry, returns the payment_gateway
522 my $conf = new FS::Conf;
523 my $cust_main = shift;
524 my $cust_payby = shift;
525 return '' if ! FS::payby->realtime($cust_payby);
526 my $pg = $cust_main->agent->payment_gateway(
527 'method' => FS::payby->payby2bop($cust_payby),
536 my $conf = new FS::Conf;
538 my $info = skin_info($p);
540 use vars qw( $cust_paybys ); #cache for performance
541 unless ( $cust_paybys ) {
543 my %cust_paybys = map { $_ => 1 }
544 map { FS::payby->payby2payment($_) }
545 $conf->config('signup_server-payby');
547 $cust_paybys = [ keys %cust_paybys ];
550 $info->{'cust_paybys'} = $cust_paybys;
552 my($context, $session, $custnum) = _custoragent_session_custnum($p);
553 return { 'error' => $session } if $context eq 'error';
555 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } );
557 $info->{'hide_payment_fields'} = [
559 my $pg = $cust_main && payment_gateway($cust_main, $_);
560 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
561 } @{ $info->{cust_paybys} }
564 $info->{'self_suspend_reason'} =
565 $conf->config('selfservice-self_suspend_reason',
566 $cust_main ? $cust_main->agentnum : ''
569 $info->{'edit_ticket_subject'} =
570 $conf->exists('ticket_system-selfservice_edit_subject') &&
571 $cust_main && $cust_main->edit_subject;
573 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
575 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
578 'custnum' => $custnum,
579 'access_pkgnum' => $session->{'pkgnum'},
580 'access_svcnum' => $session->{'svcnum'},
587 my($context, $session, $custnum) = _custoragent_session_custnum($p);
588 return { 'error' => $session } if $context eq 'error';
592 my $conf = new FS::Conf;
593 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
595 # if ( $FS::TicketSystem::system ) {
596 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
597 # FS::TicketSystem->init();
600 if ( $custnum ) { #customer record
602 %return = ( %return, %{ customer_info_short($p) } );
604 #redundant with customer_info_short, but we need it for several things below
605 my $search = { 'custnum' => $custnum };
606 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
607 my $cust_main = qsearchs('cust_main', $search )
608 or return { 'error' => "customer_info: unknown custnum $custnum" };
610 my $list_tickets = list_tickets($p);
611 $return{'tickets'} = $list_tickets->{'tickets'};
613 if ( $session->{'pkgnum'} ) {
614 #XXX open invoices in the pkg-balances case
616 $return{'money_char'} = $conf->config("money_char") || '$';
619 invnum => $_->invnum,
620 date => time2str("%b %o, %Y", $_->_date),
622 charged => $_->charged,
624 } $cust_main->open_cust_bill;
625 $return{open_invoices} = \@open;
627 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
628 my $sth = dbh->prepare($sql) or die dbh->errstr;
629 $sth->execute($custnum) or die $sth->errstr;
630 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
631 $return{'last_invoice_date_pretty'} =
632 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
635 #customer_info_short always has nobalance on..
636 $return{small_custview} =
637 small_custview( $cust_main,
638 $return{countrydefault},
639 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
642 $return{has_ship_address} = $cust_main->has_ship_address;
643 $return{status} = $cust_main->status_label; #$cust_main->status; #better to break anyone obscurely testing for strings in self-service than to have to upgrade every front-end to get the new status to display
644 $return{statuscolor} = $cust_main->statuscolor;
645 $return{status_label} = $cust_main->status_label;
647 # compatibility: some places in selfservice use this to determine
648 # if there's a ship address
649 if ( $return{has_ship_address} ) {
650 $return{ship_last} = $cust_main->last;
651 $return{ship_first} = $cust_main->first;
654 if (scalar($conf->config('support_packages'))) {
655 my @support_services = ();
656 foreach ($cust_main->support_services) {
657 my $seconds = $_->svc_x->seconds || 0;
658 my $time_remaining = (($seconds < 0) ? '-' : '' ).
659 int(abs($seconds)/3600)."h".
660 sprintf("%02d",(abs($seconds)%3600)/60)."m";
661 my $cust_pkg = $_->cust_pkg;
664 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
665 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
666 push @support_services, { svcnum => $_->svcnum,
667 time => $time_remaining,
672 $return{support_services} = \@support_services;
675 if ( $conf->config('prepayment_discounts-credit_type') ) {
677 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
680 } elsif ( $session->{'svcnum'} ) { #no customer record
682 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
683 or die "unknown svcnum";
684 $return{name} = $svc_acct->email;
688 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
692 return { 'error' => '',
693 'custnum' => $custnum,
699 sub customer_info_short {
702 my($context, $session, $custnum) = _custoragent_session_custnum($p);
703 return { 'error' => $session } if $context eq 'error';
707 my $conf = new FS::Conf;
709 if ( $custnum ) { #customer record
711 my $search = { 'custnum' => $custnum };
712 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
713 my $cust_main = qsearchs('cust_main', $search )
714 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
716 $return{display_custnum} = $cust_main->display_custnum;
717 $return{max_invnum} = $cust_main->max_invnum;
719 if ( $session->{'pkgnum'} ) {
720 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
721 #next_bill_date from cust_pkg?
723 $return{balance} = $cust_main->balance;
724 $return{next_bill_date} = $cust_main->next_bill_date;
725 $return{next_bill_date_pretty} =
726 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
729 $return{balance_pretty} = money_pretty($return{balance});
731 $return{countrydefault} = scalar($conf->config('countrydefault'));
733 $return{small_custview} =
734 small_custview( $cust_main,
735 $return{countrydefault},
739 $return{first} = $cust_main->first;
740 $return{'last'} = $cust_main->get('last');
741 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
743 #none of these are terribly expensive if we want 'em...
744 for (@cust_main_editable_fields) {
745 $return{$_} = $cust_main->get($_);
747 $return{$_} = $cust_main->masked($_) for qw/ss stateid/;
749 #maybe a little more expensive, but it should be cached by now
750 for (@location_editable_fields) {
751 $return{$_} = $cust_main->bill_location->get($_)
752 if $cust_main->bill_locationnum;
753 $return{'ship_'.$_} = $cust_main->ship_location->get($_)
754 if $cust_main->ship_locationnum;
757 my @invoicing_list = $cust_main->invoicing_list;
758 $return{'invoicing_list'} =
759 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
760 $return{'postal_invoicing'} =
761 0 < ( grep { $_ eq 'POST' } @invoicing_list );
763 if ( $session->{'svcnum'} ) {
764 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
765 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
766 $return{'svcnum'} = $session->{'svcnum'};
769 } elsif ( $session->{'svcnum'} ) { #no customer record
771 #uuh, not supproted yet... die?
772 return { 'error' => 'customer_info_short not yet supported as agent' };
776 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
780 # this is here because this routine is called by both fs_ and ng_ main pages, where it appears
781 # it is not customer-specific, though it is only shown to authenticated customers
782 # it is not currently agent-specific, though at some point it might be
783 $return{'announcement'} = join(' ',$conf->config('selfservice-announcement')) || '';
785 return { 'error' => '',
786 'custnum' => $custnum,
791 sub customer_recurring {
794 my($context, $session, $custnum) = _custoragent_session_custnum($p);
795 return { 'error' => $session } if $context eq 'error';
799 my $conf = new FS::Conf;
801 my $search = { 'custnum' => $custnum };
802 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
803 my $cust_main = qsearchs('cust_main', $search )
804 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
806 $return{'display_recurring'} = [ $cust_main->display_recurring ];
808 return { 'error' => '',
809 'custnum' => $custnum,
814 sub billing_history {
817 my($context, $session, $custnum) = _custoragent_session_custnum($p);
818 return { 'error' => $session } if $context eq 'error';
820 return { 'error' => 'No customer' } unless $custnum;
822 my $search = { 'custnum' => $custnum };
823 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
824 my $cust_main = qsearchs('cust_main', $search )
825 or return { 'error' => "unknown custnum $custnum" };
829 if ( $session->{'pkgnum'} ) {
830 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
831 #next_bill_date from cust_pkg?
832 return { 'error' => 'No history for package' };
835 $return{balance} = $cust_main->balance;
836 $return{balance_pretty} = money_pretty($return{balance});
837 $return{next_bill_date} = $cust_main->next_bill_date;
838 $return{next_bill_date_pretty} =
839 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
842 my $conf = new FS::Conf;
844 $return{'history'} = [
845 $cust_main->payment_history(
846 'line_items' => $conf->exists('selfservice-billing_history-line_items'),
851 $return{'money_char'} = $conf->config("money_char") || '$',
859 my $session = _cache->get($p->{'session_id'})
860 or return { 'error' => "Can't resume session" }; #better error message
862 my $custnum = $session->{'custnum'}
863 or return { 'error' => "no customer record" };
865 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
866 or return { 'error' => "unknown custnum $custnum" };
868 my $conf = new FS::Conf;
869 if (($p->{payby} eq "CHEK" || $p->{payby} eq "DCHEK") && $conf->exists('selfservice-ACH_info_readonly')) {
870 return { 'error' => "You do not have authority to add a bank account" };
873 my $new = new FS::cust_main { $cust_main->hash };
875 $new->set( $_ => $p->{$_} )
876 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
878 if ( exists($p->{address1}) ) {
879 my $bill_location = FS::cust_location->new({
880 map { $_ => $p->{$_} } @location_editable_fields
882 # if this is unchanged from before, cust_main::replace will ignore it
883 $new->set('bill_location' => $bill_location);
886 if ( exists($p->{ship_address1}) ) {
887 my $ship_location = FS::cust_location->new({
888 map { $_ => $p->{"ship_$_"} } @location_editable_fields
890 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
891 # Selfservice unfortunately tries to indicate "same as billing
892 # address" by sending all fields empty. Did this ever work?
893 $ship_location = $cust_main->bill_location;
895 $new->set('ship_location' => $ship_location);
897 # but if it hasn't been passed in at all, leave ship_location alone--
898 # DON'T change it to match bill_location.
901 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
902 #false laziness with httemplate/edit/process/cust_main.cgi
903 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
904 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
906 @invoicing_list = $cust_main->invoicing_list;
909 my $error = $new->replace($cust_main, \@invoicing_list);
910 return { 'error' => $error } if $error;
913 return { 'error' => '' };
918 my $session = _cache->get($p->{'session_id'})
919 or return { 'error' => "Can't resume session" }; #better error message
925 my $conf = new FS::Conf;
926 use vars qw($payment_info); #cache for performance
927 unless ( $payment_info ) {
929 my %states = map { $_->state => 1 }
930 qsearch('cust_main_county', {
931 'country' => $conf->config('countrydefault') || 'US'
934 my %cust_paybys = map { $_ => 1 }
935 map { FS::payby->payby2payment($_) }
936 $conf->config('signup_server-payby');
938 my @cust_paybys = keys %cust_paybys;
942 #list all counties/states/countries
943 'cust_main_county' =>
944 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
946 #shortcut for one-country folks
948 [ sort { $a cmp $b } keys %states ],
950 'card_types' => card_types(),
952 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
953 'require_cvv' => $conf->exists('selfservice-require_cvv'),
954 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
956 'paytypes' => [ FS::cust_payby::paytypes ],
958 'paybys' => [ $conf->config('signup_server-payby') ],
959 'cust_paybys' => \@cust_paybys,
961 'stateid_label' => FS::Msgcat::_gettext('stateid'),
962 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
964 'show_ss' => $conf->exists('show_ss'),
965 'show_stateid' => $conf->exists('show_stateid'),
966 'show_paystate' => $conf->exists('show_bankstate'),
968 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
969 'ach_read_only' => $conf->exists('selfservice-ACH_info_readonly'),
979 my %return = %$payment_info;
981 delete $return{'cust_main_county'} if $p->{'omit_cust_main_county'};
983 my $custnum = $session->{'custnum'};
985 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
986 or return { 'error' => "unknown custnum $custnum" };
988 $return{'hide_payment_fields'} = [
990 my $pg = payment_gateway($cust_main, $_);
991 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
992 } @{ $return{cust_paybys} }
995 $return{balance} = $cust_main->balance; #XXX pkg-balances?
997 $return{$_} = $cust_main->bill_location->get($_)
998 for qw(address1 address2 city state zip);
1000 # look for stored cust_payby info
1001 # only if we've been given a clear payment_payby (to avoid payname conflicts)
1002 if ($p->{'payment_payby'} =~ /^(CARD|CHEK)$/) {
1003 my @search_payby = ($p->{'payment_payby'} eq 'CARD') ? ('CARD','DCRD') : ('CHEK','DCHK');
1004 my ($cust_payby) = $cust_main->cust_payby(@search_payby);
1006 $return{payname} = $cust_payby->payname
1007 || ( $cust_main->first. ' '. $cust_main->get('last') );
1008 $return{custpaybynum} = $cust_payby->custpaybynum;
1010 if ( $cust_payby->payby =~ /^(CARD|DCRD)$/ ) {
1011 $return{card_type} = cardtype($cust_payby->payinfo);
1012 $return{payinfo} = $cust_payby->paymask;
1014 @return{'month', 'year'} = $cust_payby->paydate_monthyear;
1018 if ( $cust_payby->payby =~ /^(CHEK|DCHK)$/ ) {
1019 my ($payinfo1, $payinfo2) = split '@', $cust_payby->paymask;
1020 $return{payinfo1} = $payinfo1;
1021 $return{payinfo2} = $payinfo2;
1022 $return{paytype} = $cust_payby->paytype;
1023 $return{paystate} = $cust_payby->paystate;
1024 $return{payname} = $cust_payby->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
1029 if ( $conf->config('prepayment_discounts-credit_type') ) {
1031 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
1034 #doubleclick protection
1036 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
1037 $return{paybatch} = $return{payunique}; #back compat
1039 $return{credit_card_surcharge_percentage} = $conf->config('credit-card-surcharge-percentage', $cust_main->agentnum);
1040 $return{credit_card_surcharge_flatfee} = $conf->config('credit-card-surcharge-flatfee', $cust_main->agentnum);
1042 return { 'error' => '',
1048 #some false laziness with httemplate/process/payment.cgi - look there for
1049 #ACH and CVV support stuff
1051 sub validate_payment {
1054 my $session = _cache->get($p->{'session_id'})
1055 or return { 'error' => "Can't resume session" }; #better error message
1057 my $custnum = $session->{'custnum'};
1059 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1060 or return { 'error' => "unknown custnum $custnum" };
1062 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
1063 or return { 'error' => gettext('illegal_amount') };
1065 return { error => 'Amount must be greater than 0' } unless $amount > 0;
1067 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
1068 #changing the hidden form values
1069 my $conf = new FS::Conf;
1070 my $fee_display = $conf->config('selfservice_process-display') || 'add';
1071 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1072 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1073 if ( $fee_display eq 'add'
1075 and ! $fee_skip_first || scalar($cust_main->cust_pay)
1078 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
1079 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
1082 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
1083 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
1084 my $discount_term = $1;
1086 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
1087 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
1090 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1091 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
1094 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1095 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
1098 $payunique = $paybatch if ! length($payunique) && length($paybatch);
1100 $p->{'payby'} ||= 'CARD';
1101 $p->{'payby'} =~ /^([A-Z]{4})$/
1102 or return { 'error' => "illegal_payby " . $p->{'payby'} };
1105 #false laziness w/process/payment.cgi
1108 my $replace_cust_payby;
1109 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
1111 $p->{'payinfo1'} =~ /^([\dx]+)$/
1112 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1114 $p->{'payinfo2'} =~ /^([\dx]+)$/
1115 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1117 $payinfo = $payinfo1. '@'. $payinfo2;
1120 foreach my $cust_payby ($cust_main->cust_payby('CHEK','DCHK')) {
1121 if ( $cust_payby->paymask eq $payinfo ) {
1122 $payinfo = $cust_payby->payinfo;
1123 $replace_cust_payby = $cust_payby;
1129 if ($conf->exists('selfservice-ACH_info_readonly') && !$achonfile) {
1130 return { 'error' => "You are not allowed to change your payment information." };
1133 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1135 $payinfo = $p->{'payinfo'};
1139 #more intelligent matching will be needed here if you change
1140 #card_masking_method and don't remove existing paymasks
1141 foreach my $cust_payby ($cust_main->cust_payby('CARD','DCRD')) {
1142 if ( $cust_payby->paymask eq $payinfo ) {
1143 $payinfo = $cust_payby->payinfo;
1144 $replace_cust_payby = $cust_payby;
1150 $payinfo =~ s/\D//g;
1151 $payinfo =~ /^(\d{13,19}|\d{8,9})$/
1152 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1156 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1157 return { 'error' => gettext('unknown_card_type') }
1158 if !$cust_main->tokenized($payinfo) && cardtype($payinfo) eq "Unknown";
1160 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1161 if ( cardtype($payinfo) eq 'American Express card' ) {
1162 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1163 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1166 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1167 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1170 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1171 return { 'error' => 'CVV2 is required' };
1172 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1173 return { 'error' => 'CVV2 is required' };
1177 die "unknown payby $payby";
1180 my %payby2fields = (
1181 'CARD' => [ qw( paystart_month paystart_year payissue payip
1182 address1 address2 city state zip country ) ],
1183 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1186 my %replace = ( 'replace' => $replace_cust_payby, );
1189 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1192 'cust_main' => $cust_main, #XXX or just custnum??
1193 'amount' => sprintf('%.2f', $amount),
1195 'payinfo' => $payinfo,
1196 'paymask' => FS::payinfo_Mixin->mask_payinfo( $payby, $payinfo ),
1197 'card_type' => $card_type,
1198 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1199 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1200 'month' => $p->{'month'},
1201 'year' => $p->{'year'},
1202 'payname' => $payname,
1203 'payunique' => $payunique,
1204 'paybatch' => $paybatch,
1205 'paycvv' => $paycvv,
1206 'payname' => $payname,
1207 'discount_term' => $discount_term,
1208 'pkgnum' => $session->{'pkgnum'},
1210 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1220 my $validate = validate_payment($p);
1221 return $validate if $validate->{'error'};
1223 my $conf = new FS::Conf;
1224 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1225 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1227 +{ map { $_=>$validate->{$_} }
1228 qw( card_type paymask payname paydate_pretty month year amount
1229 address1 address2 city state zip country
1235 sub process_stored_payment {
1238 my $session_id = $p->{'session_id'};
1240 my $payment_info = _cache->get( "payment_$session_id" )
1241 or return { 'error' => "Can't resume session" }; #better error message
1243 do_process_payment($payment_info);
1247 sub process_payment {
1250 my $payment_info = validate_payment($p);
1251 return $payment_info if $payment_info->{'error'};
1253 do_process_payment($payment_info);
1257 sub do_process_payment {
1258 my $validate = shift;
1260 my $cust_main = $validate->{'cust_main'};
1262 my $amount = delete $validate->{'amount'};
1265 my $payby = delete $validate->{'payby'};
1267 if ( $validate->{'save'} ) {
1270 foreach my $field ( qw( auto payinfo paymask payname payip ) ) {
1271 $saveopt{$field} = $validate->{$field};
1274 if ( $payby eq 'CARD' ) {
1275 my $bill_location = FS::cust_location->new({
1276 map { $_ => $validate->{$_} }
1277 qw(address1 address2 city state country zip)
1279 $saveopt{'bill_location'} = $bill_location;
1280 foreach my $field ( qw( paydate paystart_month paystart_year payissue ) ) {
1281 $saveopt{$field} = $validate->{$field};
1284 # stateid/stateid_state won't be saved, might be broken as of 4.x
1285 foreach my $field ( qw( paytype paystate ) ) {
1286 $saveopt{$field} = $validate->{$field};
1290 my $error = $cust_main->save_cust_payby(
1291 'payment_payby' => $payby,
1292 'replace' => $validate->{'replace'}, # cust_payby object to replace
1297 #no, this causes customers to process their payments again
1298 #return { 'error' => $error };
1299 #XXX just warn verosely for now so i can figure out how these happen in
1300 # the first place, eventually should redirect them to the "change
1301 #address" page but indicate if the payment processed?
1302 delete($validate->{'payinfo'}); #don't want to log this!
1303 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1305 "SAVEOPT: ".Dumper(\%saveopt)."\n".
1306 "CUST_MAIN: ". Dumper($cust_main)."\n".
1307 "PACKET: ". Dumper($validate)."\n";
1311 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1315 'paynum_ref' => \$paynum,
1318 return { 'error' => $error } if $error;
1320 #no error, so order the fee package if applicable...
1321 my $conf = new FS::Conf;
1322 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1323 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1325 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1327 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1329 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1330 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1333 #and generate an invoice for it now too
1334 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1335 return { 'error' => "payment processed and fee ordered successfully, but error billing fee: $error" }
1340 $cust_main->apply_payments;
1343 my $receipt_html = '';
1345 # currently supported for realtime CC only; send receipt data to SS
1346 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1349 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1352 <TD ALIGN="right">Payment#</TD>
1353 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1357 <TD ALIGN="right">Date</TD>
1359 <TD BGCOLOR="#FFFFFF"><B>! .
1360 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1366 <TD ALIGN="right">Amount</TD>
1367 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1372 <TD ALIGN="right">Payment method</TD>
1373 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1386 'amount' => sprintf('%.2f', $cust_pay->paid),
1387 'date' => $cust_pay->_date,
1388 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1389 'time_pretty' => time2str('%T', $cust_pay->_date),
1390 'auth_num' => $cust_pay->auth,
1391 'order_num' => $cust_pay->order_number,
1392 'receipt_html' => $receipt_html,
1399 'receipt_html' => '',
1406 sub realtime_collect {
1409 my $session = _cache->get($p->{'session_id'})
1410 or return { 'error' => "Can't resume session" }; #better error message
1412 my $custnum = $session->{'custnum'};
1414 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1415 or return { 'error' => "unknown custnum $custnum" };
1418 if ( $p->{'amount'} ) {
1419 $amount = $p->{'amount'};
1421 elsif ( $session->{'pkgnum'} ) {
1422 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1425 $amount = $cust_main->balance;
1428 my $error = $cust_main->realtime_collect(
1429 'method' => $p->{'method'},
1430 'amount' => $amount,
1431 'pkgnum' => $session->{'pkgnum'},
1432 'session_id' => $p->{'session_id'},
1436 return { 'error' => $error } unless ref( $error );
1438 return { 'error' => '', amount => $amount, %$error };
1441 sub start_thirdparty {
1443 my $session = _cache->get($p->{'session_id'})
1444 or return { 'error' => "Can't resume session" }; #better error message
1445 my $custnum = $session->{'custnum'};
1446 my $cust_main = FS::cust_main->by_key($custnum);
1448 my $amount = $p->{'amount'}
1449 or return { error => 'no amount' };
1451 my $result = $cust_main->create_payment(
1452 'method' => $p->{'method'},
1453 'amount' => $p->{'amount'},
1454 'pkgnum' => $session->{'pkgnum'},
1455 'session_id' => $p->{'session_id'},
1458 if ( ref($result) ) { # hashref or error
1461 return { error => $result };
1465 sub finish_thirdparty {
1467 my $session_id = delete $p->{'session_id'};
1468 my $session = _cache->get($session_id)
1469 or return { 'error' => "Can't resume session" };
1470 my $custnum = $session->{'custnum'};
1471 my $cust_main = FS::cust_main->by_key($custnum);
1473 if ( $p->{_cancel} ) {
1474 # customer backed out of making a payment
1475 return $cust_main->cancel_payment( $session_id );
1477 my $result = $cust_main->execute_payment( $session_id, %$p );
1478 if ( ref($result) ) {
1481 return { error => $result };
1485 sub process_payment_order_pkg {
1488 my $hr = process_payment($p);
1489 return $hr if $hr->{'error'};
1494 sub process_payment_order_renew {
1497 my $hr = process_payment($p);
1498 return $hr if $hr->{'error'};
1503 sub process_prepay {
1507 my $session = _cache->get($p->{'session_id'})
1508 or return { 'error' => "Can't resume session" }; #better error message
1512 my $custnum = $session->{'custnum'};
1514 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1515 or return { 'error' => "unknown custnum $custnum" };
1517 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1518 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1526 return { 'error' => $error } if $error;
1528 return { 'error' => '',
1529 'amount' => $amount,
1530 'seconds' => $seconds,
1531 'duration' => duration_exact($seconds),
1532 'upbytes' => $upbytes,
1533 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1534 'downbytes' => $downbytes,
1535 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1536 'totalbytes'=> $totalbytes,
1537 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1544 my $session = _cache->get($p->{'session_id'})
1545 or return { 'error' => "Can't resume session" }; #better error message
1547 my $custnum = $session->{'custnum'};
1549 my $invnum = $p->{'invnum'};
1551 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1552 'custnum' => $custnum } )
1553 or return { 'error' => "Can't find invnum" };
1557 return { 'error' => '',
1558 'invnum' => $invnum,
1559 'invoice_text' => join('', $cust_bill->print_text ),
1560 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1567 my $session = _cache->get($p->{'session_id'})
1568 or return { 'error' => "Can't resume session" }; #better error message
1570 my $custnum = $session->{'custnum'};
1572 my $invnum = $p->{'invnum'};
1574 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1575 'custnum' => $custnum } )
1576 or return { 'error' => "Can't find invnum" };
1580 return { 'error' => '',
1581 'invnum' => $invnum,
1582 'invoice_pdf' => $cust_bill->print_pdf({
1583 'unsquelch_cdr' => 1,
1584 'locale' => $p->{'locale'},
1590 sub legacy_invoice {
1592 my $session = _cache->get($p->{'session_id'})
1593 or return { 'error' => "Can't resume session" }; #better error message
1595 my $custnum = $session->{'custnum'};
1597 my $legacyinvnum = $p->{'legacyinvnum'};
1600 'legacyinvnum' => $legacyinvnum,
1601 'custnum' => $custnum,
1604 my $legacy_cust_bill =
1605 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1606 || qsearchs('legacy_cust_bill', \%hash )
1607 or return { 'error' => "Can't find legacyinvnum" };
1611 return { 'error' => '',
1612 'legacyinvnum' => $legacyinvnum,
1613 'legacyid' => $legacy_cust_bill->legacyid,
1614 'invoice_html' => $legacy_cust_bill->content_html,
1619 sub legacy_invoice_pdf {
1621 my $session = _cache->get($p->{'session_id'})
1622 or return { 'error' => "Can't resume session" }; #better error message
1624 my $custnum = $session->{'custnum'};
1626 my $legacyinvnum = $p->{'legacyinvnum'};
1628 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1629 'legacyinvnum' => $legacyinvnum,
1630 'custnum' => $custnum,
1631 }) or return { 'error' => "Can't find legacyinvnum" };
1635 return { 'error' => '',
1636 'legacyinvnum' => $legacyinvnum,
1637 'legacyid' => $legacy_cust_bill->legacyid,
1638 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1646 #sessioning for this? how do we get the session id to the backend invoice
1647 # template so it can add it to the link, blah
1650 if ( $p->{'invnum'} ) {
1651 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1652 or return { 'error' => 'unknown invnum' };
1653 $agentnum = $cust_bill->cust_main->agentnum;
1656 my $templatename = $p->{'template'} || $p->{'templatename'};
1658 #false laziness-ish w/view/cust_bill-logo.cgi
1660 my $conf = new FS::Conf;
1661 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1662 $templatename = "_$1";
1667 my $filename = "logo$templatename.png";
1669 return { 'error' => '',
1670 'logo' => $conf->config_binary($filename, $agentnum),
1671 'content_type' => 'image/png', #should allow gif, jpg too
1677 my $session = _cache->get($p->{'session_id'})
1678 or return { 'error' => "Can't resume session" }; #better error message
1680 my $custnum = $session->{'custnum'};
1682 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1683 or return { 'error' => "unknown custnum $custnum" };
1685 my $conf = new FS::Conf;
1687 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1689 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1694 #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1695 my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1696 my $owed = $_->owed;
1698 +{ 'invnum' => $_->invnum,
1699 '_date' => $_->_date,
1700 'date' => time2str("%b %o, %Y", $_->_date),
1701 'date_short' => time2str("%m-%d-%Y", $_->_date),
1702 'previous' => sprintf('%.2f', ($_->previous)[0]),
1703 'charged' => sprintf('%.2f', $_->charged),
1704 'owed' => sprintf('%.2f', $owed),
1705 'balance' => sprintf('%.2f', $balance),
1706 'lastpay' => @payments_and_credits
1707 ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1713 return { 'error' => '',
1714 'balance' => $cust_main->balance,
1715 'money_char' => $conf->config("money_char") || '$',
1716 'invoices' => $invoices,
1717 'legacy_invoices' => [
1719 +{ 'legacyinvnum' => $_->legacyinvnum,
1720 'legacyid' => $_->legacyid,
1721 '_date' => $_->_date,
1722 'date' => time2str("%b %o, %Y", $_->_date),
1723 'date_short' => time2str("%m-%d-%Y", $_->_date),
1724 'charged' => sprintf('%.2f', $_->charged),
1725 'has_content' => ( length($_->content_pdf)
1726 || length($_->content_html) ),
1736 my $session = _cache->get($p->{'session_id'})
1737 or return { 'error' => "Can't resume session" }; #better error message
1739 my $custnum = $session->{'custnum'};
1741 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1742 or return { 'error' => "unknown custnum $custnum" };
1744 return { 'error' => '',
1745 'balance' => $cust_main->balance,
1746 'money_char' => FS::Conf->new->config("money_char") || '$',
1747 'payments' => [ map $_->SSAPI_getinfo, $cust_main->cust_pay ],
1751 sub payment_receipt {
1753 my $session = _cache->get($p->{'session_id'})
1754 or return { 'error' => "Can't resume session" }; #better error message
1756 my $custnum = $session->{'custnum'};
1758 my $cust_pay = qsearchs('cust_pay', { 'custnum' => $custnum,
1759 'paynum' => $p->{'paynum'},
1762 or return { 'error' => "unknown payment ". $p->{'paynum'} };
1766 %{ $cust_pay->SSAPI_getinfo },
1773 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1774 return { 'error' => $session } if $context eq 'error';
1776 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1777 or return { 'error' => "unknown custnum $custnum" };
1781 my $cust_payby = $_;
1783 map { $_ => $cust_payby->$_ }
1784 qw( custpaybynum weight payby paymask paydate
1785 payname paystate paytype
1789 $cust_main->cust_payby
1797 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1798 return { 'error' => $session } if $context eq 'error';
1800 #XXX payinfo1 + payinfo2 for CHEK?
1801 #or take the opportunity to use separate, more well- named fields?
1802 if ($p->{'payby'} eq 'CHEK') {
1803 $p->{'payinfo1'} =~ /^([\dx]+)$/
1804 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1806 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
1807 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1809 $p->{'payinfo'} = $payinfo1. '@'. $payinfo2;
1812 my $cust_payby = new FS::cust_payby {
1813 'custnum' => $custnum,
1814 map { $_ => $p->{$_} } qw( weight payby payinfo paycvv paydate payname
1815 paystate paytype payip
1819 my $error = $cust_payby->insert;
1821 return { 'error' => $error };
1823 return { 'custpaybynum' => $cust_payby->custpaybynum };
1831 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1832 return { 'error' => $session } if $context eq 'error';
1834 if ($p->{'payby'} eq 'CHEK') {
1835 $p->{'payinfo1'} =~ /^([\dx]+)$/
1836 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1838 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
1839 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1841 $p->{'payinfo'} = $payinfo1. '@'. $payinfo2;
1844 my $cust_payby = qsearchs('cust_payby', {
1845 'custnum' => $custnum,
1846 'custpaybynum' => $p->{'custpaybynum'},
1848 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1850 my $cust_main = qsearchs( 'cust_main', {custnum => $cust_payby->custnum} )
1851 or return { 'error' => 'unknown custnum '.$cust_payby->custnum };
1854 qw( weight payby payinfo paycvv paydate payname paystate paytype payip )
1856 next unless exists($p->{$field});
1857 $cust_payby->set($field,$p->{$field});
1859 $cust_payby->set( 'paymask' => $cust_payby->mask_payinfo );
1861 # Update column if given a value, and the given value wasn't
1862 # the value generated by $cust_main->masked($column);
1863 $cust_main->set( $_, $p->{$_} )
1864 for grep{ $p->{$_} !~ /^x/i; }
1865 grep{ exists $p->{$_} }
1868 # Perform updates within a transaction
1869 local $FS::UID::AutoCommit = 0;
1871 if ( my $error = $cust_payby->replace || $cust_main->replace ) {
1873 return { error => $error };
1877 return { custpaybynum => $cust_payby->custpaybynum };
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 return { 'error' => $cust_payby->verify };
1899 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1900 return { 'error' => $session } if $context eq 'error';
1902 my $cust_payby = qsearchs('cust_payby', {
1903 'custnum' => $custnum,
1904 'custpaybynum' => $p->{'custpaybynum'},
1906 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1908 my $conf = new FS::Conf;
1909 if (($cust_payby->payby eq "DCHK" || $cust_payby->payby eq "CHEK") && $conf->exists('selfservice-ACH_info_readonly')) {
1910 return { 'error' => "Sorry you do not have permission to delete bank information." };
1913 return { 'error' => $cust_payby->delete };
1919 my $session = _cache->get($p->{'session_id'})
1920 or return { 'error' => "Can't resume session" }; #better error message
1922 my $custnum = $session->{'custnum'};
1924 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1925 or return { 'error' => "unknown custnum $custnum" };
1927 my @errors = $cust_main->cancel( 'quiet'=>1 );
1929 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1931 return { 'error' => $error };
1938 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1939 return { 'error' => $session } if $context eq 'error';
1941 my $pkg = qsearchs({
1942 'table' => 'cust_pkg',
1943 'addl_from' => 'LEFT JOIN part_pkg USING ( pkgpart )',
1945 'custnum' => $custnum,
1946 'pkgnum' => $p->{'pkgnum'},
1949 or return {'error' => 'unknown pkg num $pkgnum'};
1952 pkg_label => $pkg->pkg,
1953 pkgpart => $pkg->pkgpart,
1954 classnum => $pkg->classnum,
1962 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1963 return { 'error' => $session } if $context eq 'error';
1965 my $search = { 'custnum' => $custnum };
1966 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1967 my $cust_main = qsearchs('cust_main', $search )
1968 or return { 'error' => "unknown custnum $custnum" };
1970 my $conf = new FS::Conf;
1971 my $immutable = $conf->exists('selfservice_immutable-package');
1973 # the duplication below is necessary:
1974 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1975 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1976 # non-backwards-compatible change breaking the software of anyone using the API
1977 # instead of the stock selfservice
1978 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1979 if( $conf->exists('selfservice_server-view-wholesale') ) {
1980 return { 'svcnum' => $session->{'svcnum'},
1981 'custnum' => $custnum,
1982 'cust_pkg' => [ map {
1984 immutable => $immutable,
1985 part_pkg => [ map $_->hashref, $_->part_pkg ],
1987 [ map $_->hashref, $_->available_part_svc ],
1989 [ map { my $ref = { $_->hash,
1990 label => [ $_->label ],
1992 $ref->{_password} = $_->svc_x->_password
1993 if $context eq 'agent'
1994 && $conf->exists('agent-showpasswords')
1995 && $_->part_svc->svcdb eq 'svc_acct';
2000 } $cust_main->cust_pkg
2003 small_custview( $cust_main, $conf->config('countrydefault') ),
2004 'wholesale_view' => 1,
2005 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
2006 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
2007 'lnp' => $conf->exists('svc_phone-lnp'),
2011 { 'svcnum' => $session->{'svcnum'},
2012 'custnum' => $custnum,
2013 'cust_pkg' => [ map {
2014 my $primary_cust_svc = $_->primary_cust_svc;
2017 immutable => $immutable,
2018 pkg_label => $_->pkg_locale,
2019 status => $_->status,
2020 statuscolor => $_->statuscolor,
2022 [ map { $_->hashref }
2023 grep { $_->selfservice_access ne 'hidden' }
2024 $_->available_part_svc
2027 [ map { my $ref = { $_->hash,
2028 label => [ $_->label ],
2030 $ref->{_password} = $_->svc_x->_password
2031 if $context eq 'agent'
2032 && $conf->exists('agent-showpasswords')
2033 && $_->part_svc->svcdb eq 'svc_acct';
2034 $ref->{svchash} = { $_->svc_x->hash } if
2035 $_->part_svc->svcdb eq 'svc_phone';
2036 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
2037 if $_->part_svc->svcdb eq 'svc_phone'; # hack
2040 grep { $_->part_svc->selfservice_access ne 'hidden' }
2045 ? { $primary_cust_svc->hash,
2046 label => [ $primary_cust_svc->label ],
2047 finger => $primary_cust_svc->svc_x->finger, #uuh
2048 $primary_cust_svc->part_svc->hash,
2052 } $cust_main->ncancelled_pkgs
2055 small_custview( $cust_main, $conf->config('countrydefault') ),
2056 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
2064 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2065 return { 'error' => $session } if $context eq 'error';
2067 my $conf = new FS::Conf;
2069 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
2070 my $search = { 'custnum' => $custnum };
2071 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2072 my $cust_main = qsearchs('cust_main', $search )
2073 or return { 'error' => "unknown custnum $custnum" };
2075 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
2076 if ( ! $pkgnum && $p->{'svcnum'} ) {
2077 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
2078 $pkgnum = $cust_svc->pkgnum if $cust_svc;
2082 my @cust_pkg_usage = ();
2083 foreach my $cust_pkg ( $p->{'ncancelled'}
2084 ? $cust_main->ncancelled_pkgs
2085 : $cust_main->unsuspended_pkgs ) {
2086 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
2087 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
2088 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
2091 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
2094 foreach (@cust_pkg_usage) {
2095 my $part = $_->part_pkg_usage;
2096 my $tag = $part->description . ($part->shared ? 1 : 0);
2097 my $row = $usage_pools{$tag}
2098 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
2099 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
2100 $row->[2] += $part->minutes; # minutes total
2102 } # otherwise just leave them empty
2104 if ( $p->{'svcdb'} ) {
2105 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
2107 : ref($p->{'svcdb'}) eq 'ARRAY'
2108 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
2109 : { $p->{'svcdb'} => 1 };
2110 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
2113 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
2116 my @svcs; # stuff to return to the client
2117 my %bytes_used_total; # for _used columns only
2118 foreach my $cust_svc (@cust_svc) {
2119 my $svc_x = $cust_svc->svc_x;
2120 my($label, $value) = $cust_svc->label;
2121 my $part_svc = $cust_svc->part_svc;
2122 my $svcdb = $part_svc->svcdb;
2123 my $cust_pkg = $cust_svc->cust_pkg;
2124 my $part_pkg = $cust_pkg->part_pkg;
2127 'svcnum' => $cust_svc->svcnum,
2128 'display_svcnum' => $cust_svc->display_svcnum,
2132 'pkg_label' => $cust_pkg->pkg_locale,
2133 'pkg_status' => $cust_pkg->status,
2134 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
2137 # would it make sense to put this in a svc_* method?
2139 if (!$hide_usage and grep(/^$svcdb$/, qw(svc_acct svc_broadband)) and $part_svc->part_export_usage) {
2140 my $last_bill = $cust_pkg->last_bill || 0;
2142 my $up_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctInputOctets');
2143 my $down_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctOutputOctets');
2146 'seconds_used' => $cust_svc->seconds_since_sqlradacct($last_bill,$now),
2147 'upbytes_used' => display_bytecount($up_used),
2148 'downbytes_used' => display_bytecount($down_used),
2149 'totalbytes_used' => display_bytecount($up_used + $down_used)
2151 $bytes_used_total{'seconds_used'} += $hash{'seconds_used'};
2152 $bytes_used_total{'upbytes_used'} += $up_used;
2153 $bytes_used_total{'downbytes_used'} += $down_used;
2154 $bytes_used_total{'totalbytes_used'} += $up_used + $down_used;
2157 if ( $svcdb eq 'svc_acct' ) {
2158 foreach (qw(username email finger seconds)) {
2159 $hash{$_} = $svc_x->$_;
2165 'upbytes' => display_bytecount($svc_x->upbytes),
2166 'downbytes' => display_bytecount($svc_x->downbytes),
2167 'totalbytes' => display_bytecount($svc_x->totalbytes),
2169 'recharge_amount' => $part_pkg->option('recharge_amount',1),
2170 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
2171 'recharge_upbytes' =>
2172 display_bytecount($part_pkg->option('recharge_upbytes',1)),
2173 'recharge_downbytes' =>
2174 display_bytecount($part_pkg->option('recharge_downbytes',1)),
2175 'recharge_totalbytes' =>
2176 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
2181 } elsif ( $svcdb eq 'svc_dsl' ) {
2183 $hash{'phonenum'} = $svc_x->phonenum;
2184 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
2185 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
2186 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
2189 $hash{'name'} = $cust_main->name;
2191 # no usage to hide here
2193 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2195 # could potentially show lots of things...
2196 $hash{'outbound'} = 1;
2197 $hash{'inbound'} = 0;
2198 if ( $svcdb eq 'svc_phone' ) {
2199 if ( $part_pkg->plan eq 'voip_inbound' ) {
2200 $hash{'outbound'} = 0;
2201 $hash{'inbound'} = 1;
2202 } elsif ( $part_pkg->option('selfservice_inbound_format')
2203 or $conf->config('selfservice-default_inbound_cdr_format')
2205 $hash{'inbound'} = 1;
2208 foreach (qw(inbound outbound)) {
2209 # hmm...we can't filter by status here, because there might
2210 # not be cdr_terminations at all. have to go by date.
2211 # find all since the last bill date.
2212 # XXX cdr types? we are going to need them.
2214 my $sum_cdr = $svc_x->sum_cdrs(
2215 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
2216 'begin' => ($cust_pkg->last_bill || 0),
2218 'disable_charged_party' => 1,
2220 $hash{$_} = $sum_cdr->hashref;
2223 } # not hiding usage
2227 } # foreach $cust_svc
2229 foreach my $field (keys %bytes_used_total) {
2230 if ($field =~ /bytes/) {
2231 $bytes_used_total{$field} = display_bytecount($bytes_used_total{$field});
2236 'svcnum' => $session->{'svcnum'},
2237 'custnum' => $custnum,
2238 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
2239 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
2241 'bytes_used_total' => \%bytes_used_total,
2243 map { $usage_pools{$_} }
2247 'hide_usage' => $hide_usage,
2252 sub _customer_svc_x {
2253 my($custnum, $svcnum, $table) = (shift, shift, shift);
2254 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
2256 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2257 my $search = " AND custnum = $1";
2258 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2261 'table' => ($table || 'svc_acct'),
2262 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2263 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
2264 #'LEFT JOIN cust_main USING ( custnum ) ',
2265 'hashref' => $hashref,
2266 'extra_sql' => $search, #important
2271 sub svc_status_html {
2274 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2275 return { 'error' => $session } if $context eq 'error';
2277 #XXX only svc_dsl for now
2278 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
2279 or return { 'error' => "Service not found" };
2281 my $html = $svc_x->getstatus_html;
2283 return { 'html' => $html };
2287 sub svc_status_hash {
2290 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2291 return { 'error' => $session } if $context eq 'error';
2293 #XXX only svc_acct for now
2294 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2295 or return { 'error' => "Service not found" };
2297 my ( $html, $hashref ) = $svc_x->export_getstatus;
2302 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
2303 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
2304 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
2305 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
2306 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
2309 my( $p, $method ) = @_;
2311 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2312 return { 'error' => $session } if $context eq 'error';
2314 #XXX only svc_acct for now
2315 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2316 or return { 'error' => "Service not found" };
2318 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
2320 my $error = $svc_x->$method($p); #$p? returns error?
2321 return { 'error' => $error } if $error;
2323 return {}; #? { 'error' => '' }
2327 sub acct_forward_info {
2330 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2331 return { 'error' => $session } if $context eq 'error';
2333 my $svc_forward = _customer_svc_x( $custnum,
2334 { 'srcsvc' => $p->{'svcnum'} },
2337 or return { 'error' => '',
2341 return { 'error' => '',
2342 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2347 sub process_acct_forward {
2349 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2350 return { 'error' => $session } if $context eq 'error';
2352 my $old = _customer_svc_x( $custnum,
2353 { 'srcsvc' => $p->{'svcnum'} },
2357 if ( $p->{'dst'} eq '' ) {
2359 my $error = $old->delete;
2360 return { 'error' => $error };
2362 return { 'error' => '' };
2365 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2366 'dst' => $p->{'dst'},
2371 $new->svcnum($old->svcnum);
2372 my $cust_svc = $old->cust_svc;
2373 $new->svcpart($old->svcpart);
2374 $new->pkgnuym($old->pkgnum);
2375 $error = $new->replace($old);
2377 my $conf = new FS::Conf;
2378 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2380 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2381 or return { 'error' => 'No service' }; #how would we even get here?
2383 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2385 $error = $new->insert;
2388 return { 'error' => $error };
2392 sub list_dsl_devices {
2395 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2396 return { 'error' => $session } if $context eq 'error';
2398 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2399 or return { 'error' => "Service not found" };
2402 'devices' => [ map {
2403 +{ 'mac_addr' => $_->mac_addr };
2404 } $svc_dsl->dsl_device
2410 sub add_dsl_device {
2413 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2414 return { 'error' => $session } if $context eq 'error';
2416 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2417 or return { 'error' => "Service not found" };
2419 return { 'error' => 'No MAC address supplied' }
2420 unless length($p->{'mac_addr'});
2422 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2423 'mac_addr' => scalar($p->{'mac_addr'}),
2425 my $error = $dsl_device->insert;
2426 return { 'error' => $error };
2430 sub delete_dsl_device {
2433 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2434 return { 'error' => $session } if $context eq 'error';
2436 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2437 or return { 'error' => "Service not found" };
2439 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2440 'mac_addr' => scalar($p->{'mac_addr'}),
2443 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2445 my $error = $dsl_device->delete;
2446 return { 'error' => $error };
2452 _usage_details( \&_port_graph, $p,
2453 'svcdb' => 'svc_port',
2458 my($svc_port, $begin, $end) = @_;
2460 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2461 push @usage, { 'png' => $pngOrError };
2465 sub _list_svc_usage {
2466 my($svc_acct, $begin, $end) = @_;
2468 foreach my $part_export (
2469 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2470 qw( sqlradius sqlradius_withdomain )
2472 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2477 sub list_svc_usage {
2478 _usage_details(\&_list_svc_usage, @_);
2481 sub _list_support_usage {
2482 my($svc_acct, $begin, $end) = @_;
2484 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2485 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2487 push @usage, { 'seconds' => $_->seconds,
2488 'support' => $_->support,
2489 '_date' => $_->_date,
2490 'id' => $_->transaction_id,
2491 'creator' => $_->creator,
2492 'subject' => $_->subject,
2493 'status' => $_->status,
2494 'ticketid' => $_->ticketid,
2500 sub list_support_usage {
2501 _usage_details(\&_list_support_usage, @_);
2504 sub _list_cdr_usage {
2505 # XXX CDR type support...
2506 # XXX any way to do a paged search on this?
2507 # we have to return the results all at once...
2508 my($svc_x, $begin, $end, %opt) = @_;
2509 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2513 'disable_charged_party' => 1,
2518 sub list_cdr_usage {
2520 _usage_details( \&_list_cdr_usage, $p );
2523 sub _usage_details {
2524 my($callback, $p, %opt) = @_;
2525 my $conf = FS::Conf->new;
2527 if ( $conf->exists('selfservice_hide-usage') ) {
2528 return { 'error' => 'Viewing usage is not allowed.' };
2531 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2532 return { 'error' => $session } if $context eq 'error';
2534 my $search = { 'svcnum' => $p->{'svcnum'} };
2535 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2537 my $cust_svc = qsearchs( 'cust_svc', $search );
2538 return { 'error' => 'No service selected in list_svc_usage' }
2541 my $svc_x = $cust_svc->svc_x;
2542 my $svcdb = $svc_x->table;
2543 my $cust_pkg = $cust_svc->cust_pkg;
2544 my $freq = $cust_pkg->part_pkg->freq;
2547 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2549 if ( $p->{inbound} ) {
2550 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2551 || $conf->config('selfservice-default_inbound_cdr_format')
2552 || 'source_default';
2553 $callback_opt{inbound} = 1;
2555 $format = $cust_pkg->part_pkg->option('selfservice_format')
2556 || $conf->config('selfservice-default_cdr_format')
2560 $callback_opt{format} = $format;
2561 $callback_opt{use_clid} = 1;
2562 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2565 my $start = $cust_pkg->setup;
2566 #my $end = $cust_pkg->bill; # or time?
2569 unless ( $p->{beginning} ) {
2570 $p->{beginning} = $cust_pkg->last_bill;
2571 $p->{ending} = $end;
2574 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2575 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2577 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2581 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2582 # ugly kludge, I know
2583 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2584 if (defined $delete_col) {
2585 delete($_->[$delete_col]) foreach ($header, @usage);
2589 #kinda false laziness with FS::cust_main::bill, but perhaps
2590 #we should really change this bit to DateTime and DateTime::Duration
2592 #change this bit to use Date::Manip? CAREFUL with timezones (see
2593 # mailing list archive)
2594 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2595 (localtime($p->{ending}) )[0,1,2,3,4,5];
2596 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2597 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2599 if ( $freq =~ /^\d+$/ ) {
2601 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2603 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2604 } elsif ( $freq =~ /^(\d+)w$/ ) {
2606 $nmday += $weeks * 7;
2607 $pmday -= $weeks * 7;
2608 } elsif ( $freq =~ /^(\d+)d$/ ) {
2612 } elsif ( $freq =~ /^(\d+)h$/ ) {
2617 return { 'error' => "unparsable frequency: ". $freq };
2620 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2621 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2625 'svcnum' => $p->{svcnum},
2626 'beginning' => $p->{beginning},
2627 'ending' => $p->{ending},
2628 'inbound' => $p->{inbound},
2629 'previous' => ($previous > $start) ? $previous : $start,
2630 'next' => ($next < $end) ? $next : $end,
2631 'header' => $header,
2639 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2640 return { 'error' => $session } if $context eq 'error';
2642 my $search = { 'custnum' => $custnum };
2643 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2644 my $cust_main = qsearchs('cust_main', $search )
2645 or return { 'error' => "unknown custnum $custnum" };
2647 my $status = $cust_main->status;
2649 my %order_pkg_options = ();
2650 if ( $p->{locationnum} > 0 ) {
2651 $order_pkg_options{locationnum} = delete($p->{locationnum});
2652 } elsif ( $p->{address1} ) {
2653 $order_pkg_options{'cust_location'} = new FS::cust_location {
2654 map { $_ => $p->{$_} }
2655 qw( address1 address2 city county state zip country )
2659 #false laziness w/ClientAPI/Signup.pm
2661 my $cust_pkg = new FS::cust_pkg ( {
2662 'custnum' => $custnum,
2663 'pkgpart' => $p->{'pkgpart'},
2664 'quantity' => $p->{'quantity'} || 1,
2666 my $error = $cust_pkg->check;
2667 return { 'error' => $error } if $error;
2670 unless ( $p->{'svcpart'} eq 'none' ) {
2674 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2676 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2677 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2678 $svcdb = $part_svc->svcdb;
2680 $svcdb = 'svc_acct';
2682 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2685 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2686 'svc_domain' => [ qw( domain ) ],
2687 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2688 'svc_external' => [ qw( id title ) ],
2689 'svc_pbx' => [ qw( id title ) ],
2692 my $svc_x = "FS::$svcdb"->new( {
2693 'svcpart' => $svcpart,
2694 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2697 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2700 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2701 my $acct_snarf = new FS::acct_snarf ( {
2702 'machine' => $p->{"snarf_machine$snarfnum"},
2703 'protocol' => $p->{"snarf_protocol$snarfnum"},
2704 'username' => $p->{"snarf_username$snarfnum"},
2705 '_password' => $p->{"snarf_password$snarfnum"},
2708 push @acct_snarf, $acct_snarf;
2710 $svc_x->child_objects( \@acct_snarf );
2713 my $y = $svc_x->setdefault; # arguably should be in new method
2714 return { 'error' => $y } if $y && !ref($y);
2716 $error = $svc_x->check;
2717 return { 'error' => $error } if $error;
2723 $error = $cust_main->order_pkg(
2724 'cust_pkg' => $cust_pkg,
2729 return { 'error' => $error } if $error;
2731 my $conf = new FS::Conf;
2732 if ( $conf->exists('signup_server-realtime') ) {
2734 my $bill_error = _do_bop_realtime( $cust_main, $status, 'collect'=>$p->{run_bill_events} );
2737 $cust_pkg->cancel('quiet'=>1);
2740 $cust_pkg->reexport;
2744 $cust_pkg->reexport;
2747 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2749 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2756 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2757 return { 'error' => $session } if $context eq 'error';
2759 my $conf = new FS::Conf;
2760 my $immutable = $conf->exists('selfservice_immutable-package');
2761 return { 'error' => "Package modification disabled" } if $immutable;
2763 my $search = { 'custnum' => $custnum };
2764 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2765 my $cust_main = qsearchs('cust_main', $search )
2766 or return { 'error' => "unknown custnum $custnum" };
2768 my $status = $cust_main->status;
2769 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2770 or return { 'error' => "unknown package $p->{pkgnum}" };
2772 #if someone does need self-service package change of suspended packages,
2773 # figure out how to be more discriminating
2774 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2775 if $cust_pkg->status eq 'suspended';
2777 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2778 'quantity' => $p->{'quantity'} || 1,
2781 my $new_pkg = qsearchs('part_pkg', { 'pkgpart' => $p->{pkgpart} } )
2782 or return { 'error' => "unknown package $p->{pkgpart}" };
2784 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2785 unless ref($err_or_cust_pkg);
2788 if ( $conf->exists('signup_server-realtime') ) {
2790 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2793 $err_or_cust_pkg->suspend;
2796 $err_or_cust_pkg->reexport;
2800 $err_or_cust_pkg->reexport;
2803 return { error => '', pkg => $new_pkg->pkg, pkgnum => $err_or_cust_pkg->pkgnum };
2807 sub order_recharge {
2810 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2811 return { 'error' => $session } if $context eq 'error';
2813 my $search = { 'custnum' => $custnum };
2814 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2815 my $cust_main = qsearchs('cust_main', $search )
2816 or return { 'error' => "unknown custnum $custnum" };
2818 my $status = $cust_main->status;
2819 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2820 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2822 my $svc_x = $cust_svc->svc_x;
2823 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2826 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2827 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2828 recharge_totalbytes );
2829 my $amount = $part_pkg->option('recharge_amount', 1);
2831 my ($l, $v, $d) = $cust_svc->label; # blah
2832 my $pkg = "Recharge $v";
2834 my $bill_error = $cust_main->charge($amount, $pkg,
2835 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2836 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2837 $part_pkg->taxclass); #meh
2839 my $conf = new FS::Conf;
2840 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2842 $bill_error = _do_bop_realtime( $cust_main, $status );
2847 my $error = $svc_x->recharge (\%vhash);
2848 return { 'error' => $error } if $error;
2852 my $error = $bill_error;
2853 $error ||= $svc_x->recharge (\%vhash);
2854 return { 'error' => $error } if $error;
2857 return { error => '', svc => $cust_svc->part_svc->svc };
2861 sub _do_bop_realtime {
2862 my ($cust_main, $status, %opt) = @_;
2864 my $old_balance = $cust_main->balance;
2867 my $bill_error = $cust_main->bill(
2868 'return_bill' => \@cust_bill,
2871 $bill_error ||= $cust_main->apply_payments_and_credits;
2873 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1);
2875 if ( $cust_main->balance > $old_balance
2876 && $cust_main->balance > 0
2877 && ( $cust_main->has_cust_payby_auto || $status eq 'suspended' )
2880 unless ( $opt{'no_invoice_void'} ) {
2882 #this used to apply a credit, but now we can void invoices...
2883 foreach my $cust_bill (@cust_bill) {
2884 my $voiderror = $cust_bill->void('automatic payment failed');
2885 warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2890 return { 'error' => '_decline', 'bill_error' => $bill_error };
2893 if ( $opt{'collect'} ) {
2894 my $collect_error = $cust_main->collect();
2895 return { 'error' => '_decline', 'bill_error' => $collect_error }
2896 if $collect_error; #?
2905 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2906 return { 'error' => $session } if $context eq 'error';
2908 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2909 or return { 'error' => "unknown custnum $custnum" };
2911 my @cust_pkg = sort { $a->bill <=> $b->bill }
2912 grep { $_->part_pkg->freq ne '0' }
2913 $cust_main->ncancelled_pkgs;
2915 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2917 my $total = $cust_main->balance;
2920 my $bill = $_->bill;
2921 $total += $_->part_pkg->base_recur($_, \$bill);
2922 my $renew_date = $_->part_pkg->add_freq($_->bill);
2924 'pkgnum' => $_->pkgnum,
2925 'amount' => sprintf('%.2f', $total),
2926 'bill_date' => $_->bill,
2927 'bill_date_pretty' => time2str('%x', $_->bill),
2928 'renew_date' => $renew_date,
2929 'renew_date_pretty' => time2str('%x', $renew_date),
2930 'expire_date' => $_->expire,
2931 'expire_date_pretty' => time2str('%x', $_->expire),
2936 return { 'dates' => \@array };
2940 sub payment_info_renew_info {
2942 my $renew_info = renew_info($p);
2943 my $payment_info = payment_info($p);
2944 return { %$renew_info,
2952 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2953 return { 'error' => $session } if $context eq 'error';
2955 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2956 or return { 'error' => "unknown custnum $custnum" };
2958 my $date = $p->{'date'};
2962 #freeside-daily -n -d $date fs_daily $custnum
2963 $cust_main->bill_and_collect( 'time' => $date,
2964 'invoice_time' => $now,
2965 'actual_time' => $now,
2966 'check_freq' => '1d',
2969 return { 'error' => '' };
2975 my $session = _cache->get($p->{'session_id'})
2976 or return { 'error' => "Can't resume session" }; #better error message
2978 my $custnum = $session->{'custnum'};
2980 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2981 or return { 'error' => "unknown custnum $custnum" };
2983 my $conf = new FS::Conf;
2985 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2986 or return { 'error' => 'Permission denied' };
2988 my $pkgnum = $p->{'pkgnum'};
2990 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2991 'pkgnum' => $pkgnum, } )
2992 or return { 'error' => "unknown pkgnum $pkgnum" };
2994 my $error = $cust_pkg->suspend(reason => $reasonnum);
2995 return { 'error' => $error };
3001 my $session = _cache->get($p->{'session_id'})
3002 or return { 'error' => "Can't resume session" }; #better error message
3004 my $custnum = $session->{'custnum'};
3005 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3006 or return { 'error' => "unknown custnum $custnum" };
3008 my $pkgnum = $p->{'pkgnum'};
3009 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3010 'pkgnum' => $pkgnum, } )
3011 or return { 'error' => "unknown pkgnum $pkgnum" };
3013 my $error = $cust_pkg->cancel( 'quiet' => 1,
3014 'date' => $p->{'date'},
3016 return { 'error' => $error };
3019 sub provision_phone {
3022 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
3024 #editing an existing phone number
3025 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
3026 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3027 return { 'error' => $session } if $context eq 'error';
3029 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
3030 return { 'error' => 'service not found' } unless $svc_phone;
3031 return { 'error' => 'invalid svcnum' }
3032 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
3034 $svc_phone->email($p->{'email'})
3035 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
3036 $svc_phone->forwarddst($p->{'forwarddst'})
3037 if $svc_phone->forwarddst ne $p->{'forwarddst'}
3038 && $p->{'forwarddst'} =~ /^(\d+|)$/;
3039 return { 'error' => $svc_phone->replace };
3043 unless ( $p->{'lnp'} ) {
3044 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
3045 $p->{'lnp_status'} = "portingin";
3046 return _provision( 'FS::svc_phone',
3047 [qw(lnp_desired_due_date lnp_other_provider
3048 lnp_other_provider_account phonenum countrycode lnp_status)],
3049 [qw(phonenum countrycode)],
3055 # single DID order (the usual case)
3056 unless (scalar(@bulkdid)) {
3057 return _provision( 'FS::svc_phone',
3058 [qw(phonenum countrycode)],
3059 [qw(phonenum countrycode)],
3065 # bulk DID order case
3067 foreach my $did ( @bulkdid ) {
3068 $did =~ s/[^0-9]//g;
3069 $error = _provision( 'FS::svc_phone',
3070 [qw(phonenum countrycode)],
3071 [qw(phonenum countrycode)],
3073 'pkgnum' => $p->{'pkgnum'},
3074 'svcpart' => $p->{'svcpart'},
3076 'countrycode' => $p->{'countrycode'},
3077 'session_id' => $p->{'session_id'},
3080 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
3082 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
3087 warn "provision_pbx called\n"
3090 warn "provision_pbx calling _provision\n"
3092 _provision( 'FS::svc_pbx',
3093 [qw(id title max_extensions max_simultaneous ip_addr)],
3094 [qw(id title max_extensions max_simultaneous ip_addr)],
3100 sub provision_acct {
3102 warn "provision_acct called\n"
3105 return { 'error' => gettext('passwords_dont_match') }
3106 if $p->{'_password'} ne $p->{'_password2'};
3107 return { 'error' => gettext('empty_password') }
3108 unless length($p->{'_password'});
3110 if ($p->{'domsvc'}) {
3111 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
3112 qw ( svcpart pkgnum ) );
3113 return { 'error' => gettext('invalid_domain') }
3114 unless ($domains{$p->{'domsvc'}});
3117 warn "provision_acct calling _provision\n"
3119 _provision( 'FS::svc_acct',
3120 [qw(username _password domsvc)],
3121 [qw(username _password domsvc)],
3127 sub provision_external {
3129 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
3130 _provision( 'FS::svc_external',
3138 sub provision_forward {
3140 _provision( 'FS::svc_forward',
3141 ['srcsvc','src','dstsvc','dst'],
3148 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
3149 warn "_provision called for $class\n"
3152 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3153 return { 'error' => $session } if $context eq 'error';
3155 my $search = { 'custnum' => $custnum };
3156 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3157 my $cust_main = qsearchs('cust_main', $search )
3158 or return { 'error' => "unknown custnum $custnum" };
3160 my $pkgnum = $p->{'pkgnum'};
3162 warn "searching for custnum $custnum pkgnum $pkgnum\n"
3164 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3165 'pkgnum' => $pkgnum,
3167 or return { 'error' => "unknown pkgnum $pkgnum" };
3169 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
3171 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
3172 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
3174 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
3175 if $class ne 'FS::'. $part_svc->svcdb;
3177 warn "creating $class record\n"
3179 my $svc_x = $class->new( {
3180 'pkgnum' => $p->{'pkgnum'},
3181 'svcpart' => $p->{'svcpart'},
3182 map { $_ => $p->{$_} } @$fields
3185 my %insert_args = ();
3186 #i shouldn't be a special case here (pass an option or something)
3187 if ( $class eq 'FS::svc_phone'
3188 && grep length($p->{$_}), @location_editable_fields
3191 $insert_args{'cust_location'} = new FS::cust_location {
3192 map { $_ => $p->{$_} } @location_editable_fields
3196 warn "inserting $class record\n"
3198 my $error = $svc_x->insert(%insert_args);
3201 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
3203 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
3206 my $return = { 'svc' => $part_svc->svc,
3208 map { $_ => $svc_x->get($_) } @$return_fields
3210 warn "_provision returning ". Dumper($return). "\n"
3219 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3220 return { 'error' => $session } if $context eq 'error';
3222 my $search = { 'custnum' => $custnum };
3223 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3224 my $cust_main = qsearchs('cust_main', $search )
3225 or return { 'error' => "unknown custnum $custnum" };
3227 my $pkgnum = $p->{'pkgnum'};
3229 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3230 'pkgnum' => $pkgnum,
3232 or return { 'error' => "unknown pkgnum $pkgnum" };
3234 my $svcpart = $p->{'svcpart'};
3236 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
3237 'svcpart' => $svcpart, } )
3238 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
3239 my $part_svc = $pkg_svc->part_svc;
3241 my $conf = new FS::Conf;
3244 'svc' => $part_svc->svc,
3245 'svcdb' => $part_svc->svcdb,
3246 'pkgnum' => $pkgnum,
3247 'svcpart' => $svcpart,
3248 'custnum' => $custnum,
3250 'security_phrase' => 0, #XXX !
3251 'svc_acct_pop' => [], #XXX !
3253 'init_popstate' => '',
3258 small_custview( $cust_main, $conf->config('countrydefault') ),
3262 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
3263 && $ret->{'svcdb'} eq 'svc_phone') {
3264 $ret->{'svcnum'} = $p->{'svcnum'};
3265 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
3266 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
3267 $ret->{'email'} = $svc_phone->email;
3268 $ret->{'forwarddst'} = $svc_phone->forwarddst;
3272 if ($ret->{'svcdb'} eq 'svc_forward') {
3273 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
3279 sub unprovision_svc {
3282 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3283 return { 'error' => $session } if $context eq 'error';
3285 my $search = { 'custnum' => $custnum };
3286 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3287 my $cust_main = qsearchs('cust_main', $search )
3288 or return { 'error' => "unknown custnum $custnum" };
3290 my $svcnum = $p->{'svcnum'};
3292 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
3293 or return { 'error' => "unknown svcnum $svcnum" };
3295 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
3296 unless $cust_svc->cust_pkg->custnum == $custnum;
3298 my $conf = new FS::Conf;
3300 return { 'svc' => $cust_svc->part_svc->svc,
3301 'error' => $cust_svc->cancel,
3303 small_custview( $cust_main, $conf->config('countrydefault') ),
3308 sub myaccount_passwd {
3310 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3311 return { 'error' => $session } if $context eq 'error';
3313 return { 'error' => "New passwords don't match." }
3314 if $p->{'new_password'} ne $p->{'new_password2'};
3316 return { 'error' => 'Enter new password' }
3317 unless length($p->{'new_password'});
3319 #my $search = { 'custnum' => $custnum };
3320 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3321 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3322 my $search = " AND custnum = $1";
3323 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3325 my $svc_acct = qsearchs( {
3326 'table' => 'svc_acct',
3327 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3328 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3329 'LEFT JOIN cust_main USING ( custnum ) ',
3330 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3331 'extra_sql' => $search, #important
3333 or return { 'error' => "Service not found" };
3337 my $conf = new FS::Conf;
3339 return { 'error' => 'Incorrect current password.' }
3340 if ( exists($p->{'old_password'})
3341 || $conf->exists('selfservice-password_change_oldpass')
3343 && ! $svc_acct->check_password($p->{'old_password'});
3345 $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3346 || $svc_acct->set_password($p->{'new_password'})
3347 || $svc_acct->replace();
3349 #regular pw change in self-service should change contact pw too, otherwise its
3350 #way too confusing. hell its confusing they're separate at all, but alas.
3351 #need to support the "ISP provides email that's used as a contact email" case
3353 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3354 if ( $contact && qsearchs('cust_contact', { contactnum=> $contact->contactnum,
3355 custnum => $custnum,
3356 selfservice_access => 'Y',
3360 #svc_acct was successful but this one returns an error? "shouldn't happen"
3361 #don't recheck is_password_allowed here; if the svc_acct password was
3362 #legal, that's good enough
3363 $error ||= $contact->change_password($p->{'new_password'});
3366 my($label, $value) = $svc_acct->cust_svc->label;
3368 return { 'error' => $error,
3378 my $info = skin_info($p);
3380 my $conf = new FS::Conf;
3381 my $verification = $conf->config('selfservice-password_reset_verification')
3382 or return { %$info, 'error' => 'Password resets disabled' };
3387 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3389 $contact = FS::contact->by_selfservice_email($p->{'email'});
3392 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3393 $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
3396 #also look for an svc_acct, otherwise it would be super confusing
3398 my($username, $domain) = split('@', $p->{'email'});
3399 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3400 if ( $svc_domain ) {
3401 $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3402 'domsvc' => $svc_domain->svcnum }
3405 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3406 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3408 #precaution: don't change svc_acct password not part of the same
3409 # customer as contact
3410 $svc_acct = '' if ! $cust_pkg
3411 || $cust_pkg->custnum != $cust_main->custnum;
3416 return { %$info, 'error' => 'Email address not found' }
3417 unless $contact || $svc_acct;
3419 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3421 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3422 or return { %$info, 'error' => 'Account not found' };
3424 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3425 'domsvc' => $svc_domain->svcnum }
3427 or return { %$info, 'error' => 'Account not found' };
3429 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3430 or return { %$info, 'error' => 'Account not found' };
3432 $cust_main = $cust_pkg->cust_main;
3436 return { %$info, 'error' => 'Multi-customer contacts incompatible with customer-based verification' }
3437 if ! $cust_main && $verification ne 'email';
3440 'email' => sub { 1; },
3442 my( $p, $cust_main ) = @_;
3443 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3444 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3447 my( $p, $cust_main ) = @_;
3448 my $cust_pay = qsearchs({
3449 'table' => 'cust_pay',
3450 'hashref' => { 'custnum' => $cust_main->custnum },
3451 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3455 $p->{'amount'} == $cust_pay->paid;
3458 my( $p, $cust_main ) = @_;
3459 $p->{'zip'} eq $cust_main->zip
3460 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3464 foreach my $verify ( split(',', $verification) ) {
3466 &{ $verify{$verify} }( $p, $cust_main )
3467 or return { %$info, 'error' => 'Account not found' };
3471 #okay, we're verified
3475 my $error = $contact->send_reset_email(
3476 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3480 return { %$info, 'error' => $error }; #????
3483 } elsif ( $svc_acct ) {
3485 #create a unique session
3487 my $reset_session = {
3488 'svcnum' => $svc_acct->svcnum,
3489 'agentnum' => $svc_acct->cust_main->agentnum,
3492 my $timeout = '1 hour'; #?
3494 my $reset_session_id;
3496 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3497 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3500 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3504 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3505 $cust_main->agentnum);
3506 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3507 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3509 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3510 my $error = $msg_template->send( 'cust_main' => $cust_main,
3511 'object' => $svc_acct,
3512 'substitutions' => {
3513 'session_id' => $reset_session_id,
3517 return { %$info, 'error' => $error }; #????
3522 return { %$info, 'error' => '' };
3525 sub check_reset_passwd {
3528 my $conf = new FS::Conf;
3529 my $verification = $conf->config('selfservice-password_reset_verification')
3530 or return { 'error' => 'Password resets disabled' };
3532 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3533 or return { 'error' => "Can't resume session" }; #better error message
3535 if ( $reset_session->{'svcnum'} ) {
3537 my $svcnum = $reset_session->{'svcnum'};
3539 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3540 or return { 'error' => "Service not found" };
3542 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3543 my $info = skin_info($p);
3547 'session_id' => $p->{'session_id'},
3548 'username' => $svc_acct->username,
3551 } elsif ( $reset_session->{'contactnum'} ) {
3553 my $contactnum = $reset_session->{'contactnum'};
3555 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3556 or return { 'error' => "Contact not found" };
3558 my @contact_email = $contact->contact_email;
3559 return { 'error' => 'No contact email' } unless @contact_email;
3561 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3562 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3563 if scalar(@cust_contact) == 1;
3564 my $info = skin_info($p);
3568 'session_id' => $p->{'session_id'},
3569 'email' => $contact_email[0]->email, #the first?
3574 return { 'error' => 'No svcnum or contactnum in session' }; #??
3580 sub process_reset_passwd {
3583 my $conf = new FS::Conf;
3584 my $verification = $conf->config('selfservice-password_reset_verification')
3585 or return { 'error' => 'Password resets disabled' };
3587 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3588 or return { 'error' => "Can't resume session" }; #better error message
3593 if ( $reset_session->{'svcnum'} ) {
3595 my $svcnum = $reset_session->{'svcnum'};
3597 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3598 or return { 'error' => "Service not found" };
3600 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3601 $info ||= skin_info($p);
3606 if ( $reset_session->{'contactnum'} ) {
3608 my $contactnum = $reset_session->{'contactnum'};
3610 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3611 or return { 'error' => "Contact not found" };
3613 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3614 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3615 if scalar(@cust_contact) == 1;
3616 $info ||= skin_info($p);
3620 return { %$info, 'error' => "New passwords don't match." }
3621 if $p->{'new_password'} ne $p->{'new_password2'};
3623 return { %$info, 'error' => 'Enter new password' }
3624 unless length($p->{'new_password'});
3628 my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3629 || $svc_acct->set_password($p->{'new_password'})
3630 || $svc_acct->replace();
3632 return { %$info, 'error' => $error } if $error;
3634 #my($label, $value) = $svc_acct->cust_svc->label;
3635 #return { 'error' => $error,
3636 # #'label' => $label,
3637 # #'value' => $value,
3644 my $error = $contact->is_password_allowed($p->{'new_password'})
3645 || $contact->change_password($p->{'new_password'});
3647 return { %$info, 'error' => $error }; # if $error;
3651 #password changed ,so remove session, don't want it reused
3652 _cache->remove($p->{'session_id'});
3654 return { %$info, 'error' => '' };
3658 sub validate_passwd {
3662 %result = ( 'fieldid' => $p->{'fieldid'} )
3663 if $p->{'fieldid'} =~ /^\w+$/;
3665 return { %result, 'password_invalid' => 'Enter new password' }
3666 unless length($p->{'check_password'});
3669 if ($p->{'svcnum'}) {
3670 # false laziness with myaccount_passwd
3671 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3672 return { %result, 'error' => $session } if $context eq 'error';
3674 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3675 my $search = " AND custnum = $1";
3676 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3678 $svc_acct = qsearchs( {
3679 'table' => 'svc_acct',
3680 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3681 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3682 'LEFT JOIN cust_main USING ( custnum ) ',
3683 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3684 'extra_sql' => $search, #important
3686 or return { %result, 'error' => "Service not found" };
3687 # end false laziness
3690 $svc_acct ||= new FS::svc_acct {};
3692 my $error = $svc_acct->is_password_allowed($p->{'check_password'});
3693 return { %result, 'password_invalid' => $error } if $error;
3694 return { %result, 'password_valid' => 1 };
3699 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3700 return { 'error' => $session } if $context eq 'error';
3703 if ( $session->{'pkgnum'} ) {
3705 #tickets for specific service with pkg-balances on
3706 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3707 'pkgnum' => $session->{'pkgnum'} })
3708 or return { 'error' => 'unknown package' };
3709 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3710 push @tickets, $cust_svc->tickets( $p->{status} );
3715 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3716 or return { 'error' => "unknown custnum $custnum" };
3718 @tickets = $cust_main->tickets( $p->{status} );
3721 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3722 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3724 @tickets = grep { $_->{'_selfservice_priority'}
3725 !~ /^\s*(closed?|resolved?|done)\s*/i }
3728 my $conf = new FS::Conf;
3729 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3733 ($a->{'_selfservice_priority'} eq '') <=>
3734 ($b->{'_selfservice_priority'} eq '')
3737 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3743 +{ tickets => \@tickets };
3750 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3751 return { 'error' => $session } if $context eq 'error';
3753 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3754 FS::TicketSystem->init();
3756 my $conf = new FS::Conf;
3757 my $queue = $p->{'queue'}
3758 || $conf->config('ticket_system-selfservice_queueid')
3759 || $conf->config('ticket_system-default_queueid');
3761 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3762 my $err_or_ticket = FS::TicketSystem->create_ticket(
3763 '', #create RT session based on FS CurrentUser (fs_selfservice)
3765 'custnum' => $custnum,
3766 'svcnum' => $session->{'svcnum'},
3767 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3770 if ( ref($err_or_ticket) ) {
3771 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3773 return { 'error' => '',
3774 'ticket_id' => $err_or_ticket->id,
3777 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3779 return { 'error' => $err_or_ticket };
3787 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3788 return { 'error' => $session } if $context eq 'error';
3790 return { error => 'requested format not implemented' }
3791 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3793 my $conf = new FS::Conf;
3794 my $age_threshold = 0;
3795 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3796 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3798 my $search = { 'custnum' => $custnum };
3799 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3800 my $cust_main = qsearchs('cust_main', $search )
3801 or return { 'error' => "unknown custnum $custnum" };
3803 # does it make more sense to just run one sql query for this instead of all the
3804 # insanity below? would increase performance greately for large data sets?
3806 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3807 my @part_svc = $cust_pkg->part_svc;
3808 foreach my $part_svc ( @part_svc ) {
3809 if($part_svc->svcdb eq 'svc_phone'){
3810 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3811 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3812 push @svc_phone, $cust_pkg_svc->svc_x
3813 if $cust_pkg_svc->date_inserted >= $age_threshold;
3821 my($xls_r,$xls_c) = (0,0);
3824 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3825 if($p->{'format'} eq 'csv') {
3826 $csv = new Text::CSV_XS { 'always_quote' => 1,
3829 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3830 $content .= $csv->string;
3832 elsif($p->{'format'} eq 'xls') {
3833 my $XLS1 = new IO::Scalar \$content;
3834 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3835 or return { 'error' => "Error opening .xls file: $!" };
3836 $xls = $xls_workbook->add_worksheet('DIDs');
3837 foreach ( @fields ) {
3838 $xls->write(0,$xls_c++,$_);
3843 foreach my $svc_phone ( @svc_phone ) {
3844 my @cols = map { $svc_phone->$_ } @fields;
3845 if($p->{'format'} eq 'csv') {
3846 return { 'error' => 'Unable to create CSV' }
3847 unless $csv->combine(@cols);
3848 $content .= $csv->string;
3850 elsif($p->{'format'} eq 'xls') {
3853 $xls->write($xls_r,$xls_c++,$_);
3859 $xls_workbook->close() if $p->{'format'} eq 'xls';
3861 { content => $content, format => $p->{'format'}, };
3866 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3867 return { 'error' => $session } if $context eq 'error';
3869 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3870 # FS::TicketSystem->init();
3871 # return { 'error' => 'get_ticket configuration error' }
3872 # if $FS::TicketSystem::system ne 'RT_Internal';
3874 # check existence and ownership as part of this
3875 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3876 my $rt_session = FS::TicketSystem->session('');
3877 my $Ticket = FS::TicketSystem->get_ticket_object(
3879 ticket_id => $p->{'ticket_id'},
3882 return { 'error' => 'ticket not found' } if !$Ticket;
3884 if ( length( $p->{'subject'} || '' ) ) {
3886 if ( $p->{'subject'} ne $Ticket->Subject ) {
3887 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3888 return { 'error' => "unable to set subject: $msg" } if !$val;
3892 if(length($p->{'reply'})) {
3893 my @err_or_res = FS::TicketSystem->correspond_ticket(
3895 'ticket_id' => $p->{'ticket_id'},
3896 'content' => $p->{'reply'},
3899 return { 'error' => 'unable to reply to ticket' }
3900 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3903 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3904 my $err_or_ticket = FS::TicketSystem->get_ticket(
3906 'ticket_id' => $p->{'ticket_id'},
3909 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3910 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3912 return { 'error' => $err_or_ticket };
3915 my @custs = @{$err_or_ticket->{'custs'}};
3916 my @txns = @{$err_or_ticket->{'txns'}};
3919 # superseded by check in get_ticket_object
3920 #return { 'error' => 'invalid ticket requested' }
3921 #unless grep($_ eq $custnum, @custs);
3923 foreach my $txn ( @txns ) {
3924 push @filtered_txns, $txn
3925 if ($txn->{'type'} eq 'EmailRecord'
3926 || $txn->{'type'} eq 'Correspond'
3927 || $txn->{'type'} eq 'Create');
3930 warn "$me get_ticket: successful: \n"
3932 return { 'error' => '',
3933 'transactions' => \@filtered_txns,
3934 'ticket_fields' => $err_or_ticket->{'fields'},
3935 'ticket_id' => $p->{'ticket_id'},
3939 sub adjust_ticket_priority {
3941 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3942 return { 'error' => $session } if $context eq 'error';
3944 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3945 # FS::TicketSystem->init;
3946 my $ss_priority = FS::TicketSystem->selfservice_priority;
3948 return { 'error' => 'adjust_ticket_priority configuration error' }
3949 if $FS::TicketSystem::system ne 'RT_Internal'
3952 my $values = $p->{'values'}; #hashref, id => priority value
3955 foreach my $id (keys %$values) {
3956 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3957 my $Ticket = FS::TicketSystem->get_ticket_object('',
3959 'custnum' => $custnum,
3962 $ticket_error{$id} = 'ticket not found';
3966 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3967 # We're not going to implement it for RT_External.
3968 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3969 my $new_value = $values->{$id};
3970 next if $old_value eq $new_value;
3972 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3974 # AddCustomFieldValue works fine (replacing any existing value) if it's
3975 # a single-valued custom field, which it should be. If it's not, you're
3976 # doing something wrong.
3978 if ( length($new_value) ) {
3979 ($val, $msg) = $Ticket->AddCustomFieldValue(
3980 Field => $ss_priority,
3981 Value => $new_value,
3985 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3986 Field => $ss_priority,
3987 Value => $old_value,
3991 $ticket_error{$id} = $msg if !$val;
3992 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3994 return { 'error' => '',
3995 'ticket_error' => \%ticket_error,
3996 %{ customer_info($p) } # send updated customer info back
4002 sub _custoragent_session_custnum {
4005 my($context, $session, $custnum);
4006 if ( $p->{'session_id'} ) {
4008 $context = 'customer';
4009 $session = _cache->get($p->{'session_id'})
4010 or return ( 'error' => "Can't resume session" ); #better error message
4011 $custnum = $session->{'custnum'};
4013 } elsif ( $p->{'agent_session_id'} ) {
4016 my $agent_cache = new FS::ClientAPI_SessionCache( {
4017 'namespace' => 'FS::ClientAPI::Agent',
4019 $session = $agent_cache->get($p->{'agent_session_id'})
4020 or return ( 'error' => "Can't resume session" ); #better error message
4021 $custnum = $p->{'custnum'};
4025 return ( 'error' => "Can't resume session" ); #better error message
4028 ($context, $session, $custnum);