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;
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);
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'} };
1851 qw( weight payby payinfo paycvv paydate payname paystate paytype payip )
1853 next unless exists($p->{$field});
1854 $cust_payby->set($field,$p->{$field});
1857 my $error = $cust_payby->replace;
1859 return { 'error' => $error };
1861 return { 'custpaybynum' => $cust_payby->custpaybynum };
1869 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1870 return { 'error' => $session } if $context eq 'error';
1872 my $cust_payby = qsearchs('cust_payby', {
1873 'custnum' => $custnum,
1874 'custpaybynum' => $p->{'custpaybynum'},
1876 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1878 return { 'error' => $cust_payby->verify };
1885 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1886 return { 'error' => $session } if $context eq 'error';
1888 my $cust_payby = qsearchs('cust_payby', {
1889 'custnum' => $custnum,
1890 'custpaybynum' => $p->{'custpaybynum'},
1892 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1894 my $conf = new FS::Conf;
1895 if (($cust_payby->payby eq "DCHK" || $cust_payby->payby eq "CHEK") && $conf->exists('selfservice-ACH_info_readonly')) {
1896 return { 'error' => "Sorry you do not have permission to delete bank information." };
1899 return { 'error' => $cust_payby->delete };
1905 my $session = _cache->get($p->{'session_id'})
1906 or return { 'error' => "Can't resume session" }; #better error message
1908 my $custnum = $session->{'custnum'};
1910 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1911 or return { 'error' => "unknown custnum $custnum" };
1913 my @errors = $cust_main->cancel( 'quiet'=>1 );
1915 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1917 return { 'error' => $error };
1924 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1925 return { 'error' => $session } if $context eq 'error';
1927 my $pkg = qsearchs({
1928 'table' => 'cust_pkg',
1929 'addl_from' => 'LEFT JOIN part_pkg USING ( pkgpart )',
1931 'custnum' => $custnum,
1932 'pkgnum' => $p->{'pkgnum'},
1935 or return {'error' => 'unknown pkg num $pkgnum'};
1938 pkg_label => $pkg->pkg,
1939 pkgpart => $pkg->pkgpart,
1940 classnum => $pkg->classnum,
1948 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1949 return { 'error' => $session } if $context eq 'error';
1951 my $search = { 'custnum' => $custnum };
1952 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1953 my $cust_main = qsearchs('cust_main', $search )
1954 or return { 'error' => "unknown custnum $custnum" };
1956 my $conf = new FS::Conf;
1957 my $immutable = $conf->exists('selfservice_immutable-package');
1959 # the duplication below is necessary:
1960 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1961 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1962 # non-backwards-compatible change breaking the software of anyone using the API
1963 # instead of the stock selfservice
1964 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1965 if( $conf->exists('selfservice_server-view-wholesale') ) {
1966 return { 'svcnum' => $session->{'svcnum'},
1967 'custnum' => $custnum,
1968 'cust_pkg' => [ map {
1970 immutable => $immutable,
1971 part_pkg => [ map $_->hashref, $_->part_pkg ],
1973 [ map $_->hashref, $_->available_part_svc ],
1975 [ map { my $ref = { $_->hash,
1976 label => [ $_->label ],
1978 $ref->{_password} = $_->svc_x->_password
1979 if $context eq 'agent'
1980 && $conf->exists('agent-showpasswords')
1981 && $_->part_svc->svcdb eq 'svc_acct';
1986 } $cust_main->cust_pkg
1989 small_custview( $cust_main, $conf->config('countrydefault') ),
1990 'wholesale_view' => 1,
1991 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1992 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1993 'lnp' => $conf->exists('svc_phone-lnp'),
1997 { 'svcnum' => $session->{'svcnum'},
1998 'custnum' => $custnum,
1999 'cust_pkg' => [ map {
2000 my $primary_cust_svc = $_->primary_cust_svc;
2003 immutable => $immutable,
2004 pkg_label => $_->pkg_locale,
2005 status => $_->status,
2006 statuscolor => $_->statuscolor,
2008 [ map { $_->hashref }
2009 grep { $_->selfservice_access ne 'hidden' }
2010 $_->available_part_svc
2013 [ map { my $ref = { $_->hash,
2014 label => [ $_->label ],
2016 $ref->{_password} = $_->svc_x->_password
2017 if $context eq 'agent'
2018 && $conf->exists('agent-showpasswords')
2019 && $_->part_svc->svcdb eq 'svc_acct';
2020 $ref->{svchash} = { $_->svc_x->hash } if
2021 $_->part_svc->svcdb eq 'svc_phone';
2022 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
2023 if $_->part_svc->svcdb eq 'svc_phone'; # hack
2026 grep { $_->part_svc->selfservice_access ne 'hidden' }
2031 ? { $primary_cust_svc->hash,
2032 label => [ $primary_cust_svc->label ],
2033 finger => $primary_cust_svc->svc_x->finger, #uuh
2034 $primary_cust_svc->part_svc->hash,
2038 } $cust_main->ncancelled_pkgs
2041 small_custview( $cust_main, $conf->config('countrydefault') ),
2042 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
2050 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2051 return { 'error' => $session } if $context eq 'error';
2053 my $conf = new FS::Conf;
2055 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
2056 my $search = { 'custnum' => $custnum };
2057 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2058 my $cust_main = qsearchs('cust_main', $search )
2059 or return { 'error' => "unknown custnum $custnum" };
2061 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
2062 if ( ! $pkgnum && $p->{'svcnum'} ) {
2063 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
2064 $pkgnum = $cust_svc->pkgnum if $cust_svc;
2068 my @cust_pkg_usage = ();
2069 foreach my $cust_pkg ( $p->{'ncancelled'}
2070 ? $cust_main->ncancelled_pkgs
2071 : $cust_main->unsuspended_pkgs ) {
2072 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
2073 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
2074 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
2077 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
2080 foreach (@cust_pkg_usage) {
2081 my $part = $_->part_pkg_usage;
2082 my $tag = $part->description . ($part->shared ? 1 : 0);
2083 my $row = $usage_pools{$tag}
2084 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
2085 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
2086 $row->[2] += $part->minutes; # minutes total
2088 } # otherwise just leave them empty
2090 if ( $p->{'svcdb'} ) {
2091 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
2093 : ref($p->{'svcdb'}) eq 'ARRAY'
2094 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
2095 : { $p->{'svcdb'} => 1 };
2096 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
2099 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
2102 my @svcs; # stuff to return to the client
2103 my %bytes_used_total; # for _used columns only
2104 foreach my $cust_svc (@cust_svc) {
2105 my $svc_x = $cust_svc->svc_x;
2106 my($label, $value) = $cust_svc->label;
2107 my $part_svc = $cust_svc->part_svc;
2108 my $svcdb = $part_svc->svcdb;
2109 my $cust_pkg = $cust_svc->cust_pkg;
2110 my $part_pkg = $cust_pkg->part_pkg;
2113 'svcnum' => $cust_svc->svcnum,
2114 'display_svcnum' => $cust_svc->display_svcnum,
2118 'pkg_label' => $cust_pkg->pkg_locale,
2119 'pkg_status' => $cust_pkg->status,
2120 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
2123 # would it make sense to put this in a svc_* method?
2125 if (!$hide_usage and grep(/^$svcdb$/, qw(svc_acct svc_broadband)) and $part_svc->part_export_usage) {
2126 my $last_bill = $cust_pkg->last_bill || 0;
2128 my $up_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctInputOctets');
2129 my $down_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctOutputOctets');
2132 'seconds_used' => $cust_svc->seconds_since_sqlradacct($last_bill,$now),
2133 'upbytes_used' => display_bytecount($up_used),
2134 'downbytes_used' => display_bytecount($down_used),
2135 'totalbytes_used' => display_bytecount($up_used + $down_used)
2137 $bytes_used_total{'seconds_used'} += $hash{'seconds_used'};
2138 $bytes_used_total{'upbytes_used'} += $up_used;
2139 $bytes_used_total{'downbytes_used'} += $down_used;
2140 $bytes_used_total{'totalbytes_used'} += $up_used + $down_used;
2143 if ( $svcdb eq 'svc_acct' ) {
2144 foreach (qw(username email finger seconds)) {
2145 $hash{$_} = $svc_x->$_;
2151 'upbytes' => display_bytecount($svc_x->upbytes),
2152 'downbytes' => display_bytecount($svc_x->downbytes),
2153 'totalbytes' => display_bytecount($svc_x->totalbytes),
2155 'recharge_amount' => $part_pkg->option('recharge_amount',1),
2156 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
2157 'recharge_upbytes' =>
2158 display_bytecount($part_pkg->option('recharge_upbytes',1)),
2159 'recharge_downbytes' =>
2160 display_bytecount($part_pkg->option('recharge_downbytes',1)),
2161 'recharge_totalbytes' =>
2162 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
2167 } elsif ( $svcdb eq 'svc_dsl' ) {
2169 $hash{'phonenum'} = $svc_x->phonenum;
2170 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
2171 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
2172 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
2175 $hash{'name'} = $cust_main->name;
2177 # no usage to hide here
2179 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2181 # could potentially show lots of things...
2182 $hash{'outbound'} = 1;
2183 $hash{'inbound'} = 0;
2184 if ( $svcdb eq 'svc_phone' ) {
2185 if ( $part_pkg->plan eq 'voip_inbound' ) {
2186 $hash{'outbound'} = 0;
2187 $hash{'inbound'} = 1;
2188 } elsif ( $part_pkg->option('selfservice_inbound_format')
2189 or $conf->config('selfservice-default_inbound_cdr_format')
2191 $hash{'inbound'} = 1;
2194 foreach (qw(inbound outbound)) {
2195 # hmm...we can't filter by status here, because there might
2196 # not be cdr_terminations at all. have to go by date.
2197 # find all since the last bill date.
2198 # XXX cdr types? we are going to need them.
2200 my $sum_cdr = $svc_x->sum_cdrs(
2201 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
2202 'begin' => ($cust_pkg->last_bill || 0),
2204 'disable_charged_party' => 1,
2206 $hash{$_} = $sum_cdr->hashref;
2209 } # not hiding usage
2213 } # foreach $cust_svc
2215 foreach my $field (keys %bytes_used_total) {
2216 if ($field =~ /bytes/) {
2217 $bytes_used_total{$field} = display_bytecount($bytes_used_total{$field});
2222 'svcnum' => $session->{'svcnum'},
2223 'custnum' => $custnum,
2224 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
2225 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
2227 'bytes_used_total' => \%bytes_used_total,
2229 map { $usage_pools{$_} }
2233 'hide_usage' => $hide_usage,
2238 sub _customer_svc_x {
2239 my($custnum, $svcnum, $table) = (shift, shift, shift);
2240 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
2242 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2243 my $search = " AND custnum = $1";
2244 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2247 'table' => ($table || 'svc_acct'),
2248 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2249 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
2250 #'LEFT JOIN cust_main USING ( custnum ) ',
2251 'hashref' => $hashref,
2252 'extra_sql' => $search, #important
2257 sub svc_status_html {
2260 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2261 return { 'error' => $session } if $context eq 'error';
2263 #XXX only svc_dsl for now
2264 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
2265 or return { 'error' => "Service not found" };
2267 my $html = $svc_x->getstatus_html;
2269 return { 'html' => $html };
2273 sub svc_status_hash {
2276 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2277 return { 'error' => $session } if $context eq 'error';
2279 #XXX only svc_acct for now
2280 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2281 or return { 'error' => "Service not found" };
2283 my ( $html, $hashref ) = $svc_x->export_getstatus;
2288 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
2289 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
2290 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
2291 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
2292 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
2295 my( $p, $method ) = @_;
2297 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2298 return { 'error' => $session } if $context eq 'error';
2300 #XXX only svc_acct for now
2301 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2302 or return { 'error' => "Service not found" };
2304 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
2306 my $error = $svc_x->$method($p); #$p? returns error?
2307 return { 'error' => $error } if $error;
2309 return {}; #? { 'error' => '' }
2313 sub acct_forward_info {
2316 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2317 return { 'error' => $session } if $context eq 'error';
2319 my $svc_forward = _customer_svc_x( $custnum,
2320 { 'srcsvc' => $p->{'svcnum'} },
2323 or return { 'error' => '',
2327 return { 'error' => '',
2328 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2333 sub process_acct_forward {
2335 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2336 return { 'error' => $session } if $context eq 'error';
2338 my $old = _customer_svc_x( $custnum,
2339 { 'srcsvc' => $p->{'svcnum'} },
2343 if ( $p->{'dst'} eq '' ) {
2345 my $error = $old->delete;
2346 return { 'error' => $error };
2348 return { 'error' => '' };
2351 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2352 'dst' => $p->{'dst'},
2357 $new->svcnum($old->svcnum);
2358 my $cust_svc = $old->cust_svc;
2359 $new->svcpart($old->svcpart);
2360 $new->pkgnuym($old->pkgnum);
2361 $error = $new->replace($old);
2363 my $conf = new FS::Conf;
2364 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2366 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2367 or return { 'error' => 'No service' }; #how would we even get here?
2369 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2371 $error = $new->insert;
2374 return { 'error' => $error };
2378 sub list_dsl_devices {
2381 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2382 return { 'error' => $session } if $context eq 'error';
2384 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2385 or return { 'error' => "Service not found" };
2388 'devices' => [ map {
2389 +{ 'mac_addr' => $_->mac_addr };
2390 } $svc_dsl->dsl_device
2396 sub add_dsl_device {
2399 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2400 return { 'error' => $session } if $context eq 'error';
2402 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2403 or return { 'error' => "Service not found" };
2405 return { 'error' => 'No MAC address supplied' }
2406 unless length($p->{'mac_addr'});
2408 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2409 'mac_addr' => scalar($p->{'mac_addr'}),
2411 my $error = $dsl_device->insert;
2412 return { 'error' => $error };
2416 sub delete_dsl_device {
2419 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2420 return { 'error' => $session } if $context eq 'error';
2422 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2423 or return { 'error' => "Service not found" };
2425 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2426 'mac_addr' => scalar($p->{'mac_addr'}),
2429 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2431 my $error = $dsl_device->delete;
2432 return { 'error' => $error };
2438 _usage_details( \&_port_graph, $p,
2439 'svcdb' => 'svc_port',
2444 my($svc_port, $begin, $end) = @_;
2446 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2447 push @usage, { 'png' => $pngOrError };
2451 sub _list_svc_usage {
2452 my($svc_acct, $begin, $end) = @_;
2454 foreach my $part_export (
2455 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2456 qw( sqlradius sqlradius_withdomain )
2458 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2463 sub list_svc_usage {
2464 _usage_details(\&_list_svc_usage, @_);
2467 sub _list_support_usage {
2468 my($svc_acct, $begin, $end) = @_;
2470 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2471 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2473 push @usage, { 'seconds' => $_->seconds,
2474 'support' => $_->support,
2475 '_date' => $_->_date,
2476 'id' => $_->transaction_id,
2477 'creator' => $_->creator,
2478 'subject' => $_->subject,
2479 'status' => $_->status,
2480 'ticketid' => $_->ticketid,
2486 sub list_support_usage {
2487 _usage_details(\&_list_support_usage, @_);
2490 sub _list_cdr_usage {
2491 # XXX CDR type support...
2492 # XXX any way to do a paged search on this?
2493 # we have to return the results all at once...
2494 my($svc_x, $begin, $end, %opt) = @_;
2495 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2499 'disable_charged_party' => 1,
2504 sub list_cdr_usage {
2506 _usage_details( \&_list_cdr_usage, $p );
2509 sub _usage_details {
2510 my($callback, $p, %opt) = @_;
2511 my $conf = FS::Conf->new;
2513 if ( $conf->exists('selfservice_hide-usage') ) {
2514 return { 'error' => 'Viewing usage is not allowed.' };
2517 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2518 return { 'error' => $session } if $context eq 'error';
2520 my $search = { 'svcnum' => $p->{'svcnum'} };
2521 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2523 my $cust_svc = qsearchs( 'cust_svc', $search );
2524 return { 'error' => 'No service selected in list_svc_usage' }
2527 my $svc_x = $cust_svc->svc_x;
2528 my $svcdb = $svc_x->table;
2529 my $cust_pkg = $cust_svc->cust_pkg;
2530 my $freq = $cust_pkg->part_pkg->freq;
2533 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2535 if ( $p->{inbound} ) {
2536 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2537 || $conf->config('selfservice-default_inbound_cdr_format')
2538 || 'source_default';
2539 $callback_opt{inbound} = 1;
2541 $format = $cust_pkg->part_pkg->option('selfservice_format')
2542 || $conf->config('selfservice-default_cdr_format')
2546 $callback_opt{format} = $format;
2547 $callback_opt{use_clid} = 1;
2548 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2551 my $start = $cust_pkg->setup;
2552 #my $end = $cust_pkg->bill; # or time?
2555 unless ( $p->{beginning} ) {
2556 $p->{beginning} = $cust_pkg->last_bill;
2557 $p->{ending} = $end;
2560 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2561 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2563 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2567 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2568 # ugly kludge, I know
2569 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2570 if (defined $delete_col) {
2571 delete($_->[$delete_col]) foreach ($header, @usage);
2575 #kinda false laziness with FS::cust_main::bill, but perhaps
2576 #we should really change this bit to DateTime and DateTime::Duration
2578 #change this bit to use Date::Manip? CAREFUL with timezones (see
2579 # mailing list archive)
2580 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2581 (localtime($p->{ending}) )[0,1,2,3,4,5];
2582 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2583 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2585 if ( $freq =~ /^\d+$/ ) {
2587 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2589 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2590 } elsif ( $freq =~ /^(\d+)w$/ ) {
2592 $nmday += $weeks * 7;
2593 $pmday -= $weeks * 7;
2594 } elsif ( $freq =~ /^(\d+)d$/ ) {
2598 } elsif ( $freq =~ /^(\d+)h$/ ) {
2603 return { 'error' => "unparsable frequency: ". $freq };
2606 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2607 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2611 'svcnum' => $p->{svcnum},
2612 'beginning' => $p->{beginning},
2613 'ending' => $p->{ending},
2614 'inbound' => $p->{inbound},
2615 'previous' => ($previous > $start) ? $previous : $start,
2616 'next' => ($next < $end) ? $next : $end,
2617 'header' => $header,
2625 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2626 return { 'error' => $session } if $context eq 'error';
2628 my $search = { 'custnum' => $custnum };
2629 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2630 my $cust_main = qsearchs('cust_main', $search )
2631 or return { 'error' => "unknown custnum $custnum" };
2633 my $status = $cust_main->status;
2635 my %order_pkg_options = ();
2636 if ( $p->{locationnum} > 0 ) {
2637 $order_pkg_options{locationnum} = delete($p->{locationnum});
2638 } elsif ( $p->{address1} ) {
2639 $order_pkg_options{'cust_location'} = new FS::cust_location {
2640 map { $_ => $p->{$_} }
2641 qw( address1 address2 city county state zip country )
2645 #false laziness w/ClientAPI/Signup.pm
2647 my $cust_pkg = new FS::cust_pkg ( {
2648 'custnum' => $custnum,
2649 'pkgpart' => $p->{'pkgpart'},
2650 'quantity' => $p->{'quantity'} || 1,
2652 my $error = $cust_pkg->check;
2653 return { 'error' => $error } if $error;
2656 unless ( $p->{'svcpart'} eq 'none' ) {
2660 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2662 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2663 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2664 $svcdb = $part_svc->svcdb;
2666 $svcdb = 'svc_acct';
2668 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2671 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2672 'svc_domain' => [ qw( domain ) ],
2673 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2674 'svc_external' => [ qw( id title ) ],
2675 'svc_pbx' => [ qw( id title ) ],
2678 my $svc_x = "FS::$svcdb"->new( {
2679 'svcpart' => $svcpart,
2680 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2683 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2686 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2687 my $acct_snarf = new FS::acct_snarf ( {
2688 'machine' => $p->{"snarf_machine$snarfnum"},
2689 'protocol' => $p->{"snarf_protocol$snarfnum"},
2690 'username' => $p->{"snarf_username$snarfnum"},
2691 '_password' => $p->{"snarf_password$snarfnum"},
2694 push @acct_snarf, $acct_snarf;
2696 $svc_x->child_objects( \@acct_snarf );
2699 my $y = $svc_x->setdefault; # arguably should be in new method
2700 return { 'error' => $y } if $y && !ref($y);
2702 $error = $svc_x->check;
2703 return { 'error' => $error } if $error;
2709 $error = $cust_main->order_pkg(
2710 'cust_pkg' => $cust_pkg,
2715 return { 'error' => $error } if $error;
2717 my $conf = new FS::Conf;
2718 if ( $conf->exists('signup_server-realtime') ) {
2720 my $bill_error = _do_bop_realtime( $cust_main, $status, 'collect'=>$p->{run_bill_events} );
2723 $cust_pkg->cancel('quiet'=>1);
2726 $cust_pkg->reexport;
2730 $cust_pkg->reexport;
2733 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2735 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2742 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2743 return { 'error' => $session } if $context eq 'error';
2745 my $conf = new FS::Conf;
2746 my $immutable = $conf->exists('selfservice_immutable-package');
2747 return { 'error' => "Package modification disabled" } if $immutable;
2749 my $search = { 'custnum' => $custnum };
2750 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2751 my $cust_main = qsearchs('cust_main', $search )
2752 or return { 'error' => "unknown custnum $custnum" };
2754 my $status = $cust_main->status;
2755 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2756 or return { 'error' => "unknown package $p->{pkgnum}" };
2758 #if someone does need self-service package change of suspended packages,
2759 # figure out how to be more discriminating
2760 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2761 if $cust_pkg->status eq 'suspended';
2763 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2764 'quantity' => $p->{'quantity'} || 1,
2767 my $new_pkg = qsearchs('part_pkg', { 'pkgpart' => $p->{pkgpart} } )
2768 or return { 'error' => "unknown package $p->{pkgpart}" };
2770 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2771 unless ref($err_or_cust_pkg);
2774 if ( $conf->exists('signup_server-realtime') ) {
2776 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2779 $err_or_cust_pkg->suspend;
2782 $err_or_cust_pkg->reexport;
2786 $err_or_cust_pkg->reexport;
2789 return { error => '', pkg => $new_pkg->pkg, pkgnum => $err_or_cust_pkg->pkgnum };
2793 sub order_recharge {
2796 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2797 return { 'error' => $session } if $context eq 'error';
2799 my $search = { 'custnum' => $custnum };
2800 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2801 my $cust_main = qsearchs('cust_main', $search )
2802 or return { 'error' => "unknown custnum $custnum" };
2804 my $status = $cust_main->status;
2805 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2806 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2808 my $svc_x = $cust_svc->svc_x;
2809 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2812 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2813 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2814 recharge_totalbytes );
2815 my $amount = $part_pkg->option('recharge_amount', 1);
2817 my ($l, $v, $d) = $cust_svc->label; # blah
2818 my $pkg = "Recharge $v";
2820 my $bill_error = $cust_main->charge($amount, $pkg,
2821 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2822 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2823 $part_pkg->taxclass); #meh
2825 my $conf = new FS::Conf;
2826 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2828 $bill_error = _do_bop_realtime( $cust_main, $status );
2833 my $error = $svc_x->recharge (\%vhash);
2834 return { 'error' => $error } if $error;
2838 my $error = $bill_error;
2839 $error ||= $svc_x->recharge (\%vhash);
2840 return { 'error' => $error } if $error;
2843 return { error => '', svc => $cust_svc->part_svc->svc };
2847 sub _do_bop_realtime {
2848 my ($cust_main, $status, %opt) = @_;
2850 my $old_balance = $cust_main->balance;
2853 my $bill_error = $cust_main->bill(
2854 'return_bill' => \@cust_bill,
2857 $bill_error ||= $cust_main->apply_payments_and_credits;
2859 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1);
2861 if ( $cust_main->balance > $old_balance
2862 && $cust_main->balance > 0
2863 && ( $cust_main->has_cust_payby_auto || $status eq 'suspended' )
2866 unless ( $opt{'no_invoice_void'} ) {
2868 #this used to apply a credit, but now we can void invoices...
2869 foreach my $cust_bill (@cust_bill) {
2870 my $voiderror = $cust_bill->void('automatic payment failed');
2871 warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2876 return { 'error' => '_decline', 'bill_error' => $bill_error };
2879 if ( $opt{'collect'} ) {
2880 my $collect_error = $cust_main->collect();
2881 return { 'error' => '_decline', 'bill_error' => $collect_error }
2882 if $collect_error; #?
2891 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2892 return { 'error' => $session } if $context eq 'error';
2894 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2895 or return { 'error' => "unknown custnum $custnum" };
2897 my @cust_pkg = sort { $a->bill <=> $b->bill }
2898 grep { $_->part_pkg->freq ne '0' }
2899 $cust_main->ncancelled_pkgs;
2901 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2903 my $total = $cust_main->balance;
2906 my $bill = $_->bill;
2907 $total += $_->part_pkg->base_recur($_, \$bill);
2908 my $renew_date = $_->part_pkg->add_freq($_->bill);
2910 'pkgnum' => $_->pkgnum,
2911 'amount' => sprintf('%.2f', $total),
2912 'bill_date' => $_->bill,
2913 'bill_date_pretty' => time2str('%x', $_->bill),
2914 'renew_date' => $renew_date,
2915 'renew_date_pretty' => time2str('%x', $renew_date),
2916 'expire_date' => $_->expire,
2917 'expire_date_pretty' => time2str('%x', $_->expire),
2922 return { 'dates' => \@array };
2926 sub payment_info_renew_info {
2928 my $renew_info = renew_info($p);
2929 my $payment_info = payment_info($p);
2930 return { %$renew_info,
2938 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2939 return { 'error' => $session } if $context eq 'error';
2941 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2942 or return { 'error' => "unknown custnum $custnum" };
2944 my $date = $p->{'date'};
2948 #freeside-daily -n -d $date fs_daily $custnum
2949 $cust_main->bill_and_collect( 'time' => $date,
2950 'invoice_time' => $now,
2951 'actual_time' => $now,
2952 'check_freq' => '1d',
2955 return { 'error' => '' };
2961 my $session = _cache->get($p->{'session_id'})
2962 or return { 'error' => "Can't resume session" }; #better error message
2964 my $custnum = $session->{'custnum'};
2966 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2967 or return { 'error' => "unknown custnum $custnum" };
2969 my $conf = new FS::Conf;
2971 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2972 or return { 'error' => 'Permission denied' };
2974 my $pkgnum = $p->{'pkgnum'};
2976 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2977 'pkgnum' => $pkgnum, } )
2978 or return { 'error' => "unknown pkgnum $pkgnum" };
2980 my $error = $cust_pkg->suspend(reason => $reasonnum);
2981 return { 'error' => $error };
2987 my $session = _cache->get($p->{'session_id'})
2988 or return { 'error' => "Can't resume session" }; #better error message
2990 my $custnum = $session->{'custnum'};
2991 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2992 or return { 'error' => "unknown custnum $custnum" };
2994 my $pkgnum = $p->{'pkgnum'};
2995 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2996 'pkgnum' => $pkgnum, } )
2997 or return { 'error' => "unknown pkgnum $pkgnum" };
2999 my $error = $cust_pkg->cancel( 'quiet' => 1,
3000 'date' => $p->{'date'},
3002 return { 'error' => $error };
3005 sub provision_phone {
3008 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
3010 #editing an existing phone number
3011 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
3012 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3013 return { 'error' => $session } if $context eq 'error';
3015 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
3016 return { 'error' => 'service not found' } unless $svc_phone;
3017 return { 'error' => 'invalid svcnum' }
3018 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
3020 $svc_phone->email($p->{'email'})
3021 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
3022 $svc_phone->forwarddst($p->{'forwarddst'})
3023 if $svc_phone->forwarddst ne $p->{'forwarddst'}
3024 && $p->{'forwarddst'} =~ /^(\d+|)$/;
3025 return { 'error' => $svc_phone->replace };
3029 unless ( $p->{'lnp'} ) {
3030 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
3031 $p->{'lnp_status'} = "portingin";
3032 return _provision( 'FS::svc_phone',
3033 [qw(lnp_desired_due_date lnp_other_provider
3034 lnp_other_provider_account phonenum countrycode lnp_status)],
3035 [qw(phonenum countrycode)],
3041 # single DID order (the usual case)
3042 unless (scalar(@bulkdid)) {
3043 return _provision( 'FS::svc_phone',
3044 [qw(phonenum countrycode)],
3045 [qw(phonenum countrycode)],
3051 # bulk DID order case
3053 foreach my $did ( @bulkdid ) {
3054 $did =~ s/[^0-9]//g;
3055 $error = _provision( 'FS::svc_phone',
3056 [qw(phonenum countrycode)],
3057 [qw(phonenum countrycode)],
3059 'pkgnum' => $p->{'pkgnum'},
3060 'svcpart' => $p->{'svcpart'},
3062 'countrycode' => $p->{'countrycode'},
3063 'session_id' => $p->{'session_id'},
3066 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
3068 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
3073 warn "provision_pbx called\n"
3076 warn "provision_pbx calling _provision\n"
3078 _provision( 'FS::svc_pbx',
3079 [qw(id title max_extensions max_simultaneous ip_addr)],
3080 [qw(id title max_extensions max_simultaneous ip_addr)],
3086 sub provision_acct {
3088 warn "provision_acct called\n"
3091 return { 'error' => gettext('passwords_dont_match') }
3092 if $p->{'_password'} ne $p->{'_password2'};
3093 return { 'error' => gettext('empty_password') }
3094 unless length($p->{'_password'});
3096 if ($p->{'domsvc'}) {
3097 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
3098 qw ( svcpart pkgnum ) );
3099 return { 'error' => gettext('invalid_domain') }
3100 unless ($domains{$p->{'domsvc'}});
3103 warn "provision_acct calling _provision\n"
3105 _provision( 'FS::svc_acct',
3106 [qw(username _password domsvc)],
3107 [qw(username _password domsvc)],
3113 sub provision_external {
3115 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
3116 _provision( 'FS::svc_external',
3124 sub provision_forward {
3126 _provision( 'FS::svc_forward',
3127 ['srcsvc','src','dstsvc','dst'],
3134 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
3135 warn "_provision called for $class\n"
3138 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3139 return { 'error' => $session } if $context eq 'error';
3141 my $search = { 'custnum' => $custnum };
3142 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3143 my $cust_main = qsearchs('cust_main', $search )
3144 or return { 'error' => "unknown custnum $custnum" };
3146 my $pkgnum = $p->{'pkgnum'};
3148 warn "searching for custnum $custnum pkgnum $pkgnum\n"
3150 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3151 'pkgnum' => $pkgnum,
3153 or return { 'error' => "unknown pkgnum $pkgnum" };
3155 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
3157 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
3158 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
3160 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
3161 if $class ne 'FS::'. $part_svc->svcdb;
3163 warn "creating $class record\n"
3165 my $svc_x = $class->new( {
3166 'pkgnum' => $p->{'pkgnum'},
3167 'svcpart' => $p->{'svcpart'},
3168 map { $_ => $p->{$_} } @$fields
3171 my %insert_args = ();
3172 #i shouldn't be a special case here (pass an option or something)
3173 if ( $class eq 'FS::svc_phone'
3174 && grep length($p->{$_}), @location_editable_fields
3177 $insert_args{'cust_location'} = new FS::cust_location {
3178 map { $_ => $p->{$_} } @location_editable_fields
3182 warn "inserting $class record\n"
3184 my $error = $svc_x->insert(%insert_args);
3187 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
3189 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
3192 my $return = { 'svc' => $part_svc->svc,
3194 map { $_ => $svc_x->get($_) } @$return_fields
3196 warn "_provision returning ". Dumper($return). "\n"
3205 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3206 return { 'error' => $session } if $context eq 'error';
3208 my $search = { 'custnum' => $custnum };
3209 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3210 my $cust_main = qsearchs('cust_main', $search )
3211 or return { 'error' => "unknown custnum $custnum" };
3213 my $pkgnum = $p->{'pkgnum'};
3215 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3216 'pkgnum' => $pkgnum,
3218 or return { 'error' => "unknown pkgnum $pkgnum" };
3220 my $svcpart = $p->{'svcpart'};
3222 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
3223 'svcpart' => $svcpart, } )
3224 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
3225 my $part_svc = $pkg_svc->part_svc;
3227 my $conf = new FS::Conf;
3230 'svc' => $part_svc->svc,
3231 'svcdb' => $part_svc->svcdb,
3232 'pkgnum' => $pkgnum,
3233 'svcpart' => $svcpart,
3234 'custnum' => $custnum,
3236 'security_phrase' => 0, #XXX !
3237 'svc_acct_pop' => [], #XXX !
3239 'init_popstate' => '',
3244 small_custview( $cust_main, $conf->config('countrydefault') ),
3248 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
3249 && $ret->{'svcdb'} eq 'svc_phone') {
3250 $ret->{'svcnum'} = $p->{'svcnum'};
3251 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
3252 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
3253 $ret->{'email'} = $svc_phone->email;
3254 $ret->{'forwarddst'} = $svc_phone->forwarddst;
3258 if ($ret->{'svcdb'} eq 'svc_forward') {
3259 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
3265 sub unprovision_svc {
3268 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3269 return { 'error' => $session } if $context eq 'error';
3271 my $search = { 'custnum' => $custnum };
3272 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3273 my $cust_main = qsearchs('cust_main', $search )
3274 or return { 'error' => "unknown custnum $custnum" };
3276 my $svcnum = $p->{'svcnum'};
3278 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
3279 or return { 'error' => "unknown svcnum $svcnum" };
3281 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
3282 unless $cust_svc->cust_pkg->custnum == $custnum;
3284 my $conf = new FS::Conf;
3286 return { 'svc' => $cust_svc->part_svc->svc,
3287 'error' => $cust_svc->cancel,
3289 small_custview( $cust_main, $conf->config('countrydefault') ),
3294 sub myaccount_passwd {
3296 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3297 return { 'error' => $session } if $context eq 'error';
3299 return { 'error' => "New passwords don't match." }
3300 if $p->{'new_password'} ne $p->{'new_password2'};
3302 return { 'error' => 'Enter new password' }
3303 unless length($p->{'new_password'});
3305 #my $search = { 'custnum' => $custnum };
3306 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3307 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3308 my $search = " AND custnum = $1";
3309 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3311 my $svc_acct = qsearchs( {
3312 'table' => 'svc_acct',
3313 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3314 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3315 'LEFT JOIN cust_main USING ( custnum ) ',
3316 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3317 'extra_sql' => $search, #important
3319 or return { 'error' => "Service not found" };
3323 my $conf = new FS::Conf;
3325 return { 'error' => 'Incorrect current password.' }
3326 if ( exists($p->{'old_password'})
3327 || $conf->exists('selfservice-password_change_oldpass')
3329 && ! $svc_acct->check_password($p->{'old_password'});
3331 $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3332 || $svc_acct->set_password($p->{'new_password'})
3333 || $svc_acct->replace();
3335 #regular pw change in self-service should change contact pw too, otherwise its
3336 #way too confusing. hell its confusing they're separate at all, but alas.
3337 #need to support the "ISP provides email that's used as a contact email" case
3339 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3340 if ( $contact && qsearchs('cust_contact', { contactnum=> $contact->contactnum,
3341 custnum => $custnum,
3342 selfservice_access => 'Y',
3346 #svc_acct was successful but this one returns an error? "shouldn't happen"
3347 #don't recheck is_password_allowed here; if the svc_acct password was
3348 #legal, that's good enough
3349 $error ||= $contact->change_password($p->{'new_password'});
3352 my($label, $value) = $svc_acct->cust_svc->label;
3354 return { 'error' => $error,
3364 my $info = skin_info($p);
3366 my $conf = new FS::Conf;
3367 my $verification = $conf->config('selfservice-password_reset_verification')
3368 or return { %$info, 'error' => 'Password resets disabled' };
3373 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3375 $contact = FS::contact->by_selfservice_email($p->{'email'});
3378 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3379 $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
3382 #also look for an svc_acct, otherwise it would be super confusing
3384 my($username, $domain) = split('@', $p->{'email'});
3385 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3386 if ( $svc_domain ) {
3387 $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3388 'domsvc' => $svc_domain->svcnum }
3391 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3392 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3394 #precaution: don't change svc_acct password not part of the same
3395 # customer as contact
3396 $svc_acct = '' if ! $cust_pkg
3397 || $cust_pkg->custnum != $cust_main->custnum;
3402 return { %$info, 'error' => 'Email address not found' }
3403 unless $contact || $svc_acct;
3405 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3407 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3408 or return { %$info, 'error' => 'Account not found' };
3410 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3411 'domsvc' => $svc_domain->svcnum }
3413 or return { %$info, 'error' => 'Account not found' };
3415 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3416 or return { %$info, 'error' => 'Account not found' };
3418 $cust_main = $cust_pkg->cust_main;
3422 return { %$info, 'error' => 'Multi-customer contacts incompatible with customer-based verification' }
3423 if ! $cust_main && $verification ne 'email';
3426 'email' => sub { 1; },
3428 my( $p, $cust_main ) = @_;
3429 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3430 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3433 my( $p, $cust_main ) = @_;
3434 my $cust_pay = qsearchs({
3435 'table' => 'cust_pay',
3436 'hashref' => { 'custnum' => $cust_main->custnum },
3437 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3441 $p->{'amount'} == $cust_pay->paid;
3444 my( $p, $cust_main ) = @_;
3445 $p->{'zip'} eq $cust_main->zip
3446 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3450 foreach my $verify ( split(',', $verification) ) {
3452 &{ $verify{$verify} }( $p, $cust_main )
3453 or return { %$info, 'error' => 'Account not found' };
3457 #okay, we're verified
3461 my $error = $contact->send_reset_email(
3462 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3466 return { %$info, 'error' => $error }; #????
3469 } elsif ( $svc_acct ) {
3471 #create a unique session
3473 my $reset_session = {
3474 'svcnum' => $svc_acct->svcnum,
3475 'agentnum' => $svc_acct->cust_main->agentnum,
3478 my $timeout = '1 hour'; #?
3480 my $reset_session_id;
3482 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3483 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3486 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3490 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3491 $cust_main->agentnum);
3492 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3493 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3495 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3496 my $error = $msg_template->send( 'cust_main' => $cust_main,
3497 'object' => $svc_acct,
3498 'substitutions' => {
3499 'session_id' => $reset_session_id,
3503 return { %$info, 'error' => $error }; #????
3508 return { %$info, 'error' => '' };
3511 sub check_reset_passwd {
3514 my $conf = new FS::Conf;
3515 my $verification = $conf->config('selfservice-password_reset_verification')
3516 or return { 'error' => 'Password resets disabled' };
3518 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3519 or return { 'error' => "Can't resume session" }; #better error message
3521 if ( $reset_session->{'svcnum'} ) {
3523 my $svcnum = $reset_session->{'svcnum'};
3525 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3526 or return { 'error' => "Service not found" };
3528 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3529 my $info = skin_info($p);
3533 'session_id' => $p->{'session_id'},
3534 'username' => $svc_acct->username,
3537 } elsif ( $reset_session->{'contactnum'} ) {
3539 my $contactnum = $reset_session->{'contactnum'};
3541 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3542 or return { 'error' => "Contact not found" };
3544 my @contact_email = $contact->contact_email;
3545 return { 'error' => 'No contact email' } unless @contact_email;
3547 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3548 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3549 if scalar(@cust_contact) == 1;
3550 my $info = skin_info($p);
3554 'session_id' => $p->{'session_id'},
3555 'email' => $contact_email[0]->email, #the first?
3560 return { 'error' => 'No svcnum or contactnum in session' }; #??
3566 sub process_reset_passwd {
3569 my $conf = new FS::Conf;
3570 my $verification = $conf->config('selfservice-password_reset_verification')
3571 or return { 'error' => 'Password resets disabled' };
3573 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3574 or return { 'error' => "Can't resume session" }; #better error message
3579 if ( $reset_session->{'svcnum'} ) {
3581 my $svcnum = $reset_session->{'svcnum'};
3583 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3584 or return { 'error' => "Service not found" };
3586 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3587 $info ||= skin_info($p);
3592 if ( $reset_session->{'contactnum'} ) {
3594 my $contactnum = $reset_session->{'contactnum'};
3596 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3597 or return { 'error' => "Contact not found" };
3599 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3600 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3601 if scalar(@cust_contact) == 1;
3602 $info ||= skin_info($p);
3606 return { %$info, 'error' => "New passwords don't match." }
3607 if $p->{'new_password'} ne $p->{'new_password2'};
3609 return { %$info, 'error' => 'Enter new password' }
3610 unless length($p->{'new_password'});
3614 my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3615 || $svc_acct->set_password($p->{'new_password'})
3616 || $svc_acct->replace();
3618 return { %$info, 'error' => $error } if $error;
3620 #my($label, $value) = $svc_acct->cust_svc->label;
3621 #return { 'error' => $error,
3622 # #'label' => $label,
3623 # #'value' => $value,
3630 my $error = $contact->is_password_allowed($p->{'new_password'})
3631 || $contact->change_password($p->{'new_password'});
3633 return { %$info, 'error' => $error }; # if $error;
3637 #password changed ,so remove session, don't want it reused
3638 _cache->remove($p->{'session_id'});
3640 return { %$info, 'error' => '' };
3644 sub validate_passwd {
3648 %result = ( 'fieldid' => $p->{'fieldid'} )
3649 if $p->{'fieldid'} =~ /^\w+$/;
3651 return { %result, 'password_invalid' => 'Enter new password' }
3652 unless length($p->{'check_password'});
3655 if ($p->{'svcnum'}) {
3656 # false laziness with myaccount_passwd
3657 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3658 return { %result, 'error' => $session } if $context eq 'error';
3660 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3661 my $search = " AND custnum = $1";
3662 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3664 $svc_acct = qsearchs( {
3665 'table' => 'svc_acct',
3666 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3667 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3668 'LEFT JOIN cust_main USING ( custnum ) ',
3669 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3670 'extra_sql' => $search, #important
3672 or return { %result, 'error' => "Service not found" };
3673 # end false laziness
3676 $svc_acct ||= new FS::svc_acct {};
3678 my $error = $svc_acct->is_password_allowed($p->{'check_password'});
3679 return { %result, 'password_invalid' => $error } if $error;
3680 return { %result, 'password_valid' => 1 };
3685 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3686 return { 'error' => $session } if $context eq 'error';
3689 if ( $session->{'pkgnum'} ) {
3691 #tickets for specific service with pkg-balances on
3692 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3693 'pkgnum' => $session->{'pkgnum'} })
3694 or return { 'error' => 'unknown package' };
3695 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3696 push @tickets, $cust_svc->tickets( $p->{status} );
3701 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3702 or return { 'error' => "unknown custnum $custnum" };
3704 @tickets = $cust_main->tickets( $p->{status} );
3707 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3708 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3710 @tickets = grep { $_->{'_selfservice_priority'}
3711 !~ /^\s*(closed?|resolved?|done)\s*/i }
3714 my $conf = new FS::Conf;
3715 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3719 ($a->{'_selfservice_priority'} eq '') <=>
3720 ($b->{'_selfservice_priority'} eq '')
3723 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3729 +{ tickets => \@tickets };
3736 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3737 return { 'error' => $session } if $context eq 'error';
3739 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3740 FS::TicketSystem->init();
3742 my $conf = new FS::Conf;
3743 my $queue = $p->{'queue'}
3744 || $conf->config('ticket_system-selfservice_queueid')
3745 || $conf->config('ticket_system-default_queueid');
3747 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3748 my $err_or_ticket = FS::TicketSystem->create_ticket(
3749 '', #create RT session based on FS CurrentUser (fs_selfservice)
3751 'custnum' => $custnum,
3752 'svcnum' => $session->{'svcnum'},
3753 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3756 if ( ref($err_or_ticket) ) {
3757 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3759 return { 'error' => '',
3760 'ticket_id' => $err_or_ticket->id,
3763 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3765 return { 'error' => $err_or_ticket };
3773 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3774 return { 'error' => $session } if $context eq 'error';
3776 return { error => 'requested format not implemented' }
3777 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3779 my $conf = new FS::Conf;
3780 my $age_threshold = 0;
3781 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3782 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3784 my $search = { 'custnum' => $custnum };
3785 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3786 my $cust_main = qsearchs('cust_main', $search )
3787 or return { 'error' => "unknown custnum $custnum" };
3789 # does it make more sense to just run one sql query for this instead of all the
3790 # insanity below? would increase performance greately for large data sets?
3792 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3793 my @part_svc = $cust_pkg->part_svc;
3794 foreach my $part_svc ( @part_svc ) {
3795 if($part_svc->svcdb eq 'svc_phone'){
3796 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3797 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3798 push @svc_phone, $cust_pkg_svc->svc_x
3799 if $cust_pkg_svc->date_inserted >= $age_threshold;
3807 my($xls_r,$xls_c) = (0,0);
3810 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3811 if($p->{'format'} eq 'csv') {
3812 $csv = new Text::CSV_XS { 'always_quote' => 1,
3815 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3816 $content .= $csv->string;
3818 elsif($p->{'format'} eq 'xls') {
3819 my $XLS1 = new IO::Scalar \$content;
3820 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3821 or return { 'error' => "Error opening .xls file: $!" };
3822 $xls = $xls_workbook->add_worksheet('DIDs');
3823 foreach ( @fields ) {
3824 $xls->write(0,$xls_c++,$_);
3829 foreach my $svc_phone ( @svc_phone ) {
3830 my @cols = map { $svc_phone->$_ } @fields;
3831 if($p->{'format'} eq 'csv') {
3832 return { 'error' => 'Unable to create CSV' }
3833 unless $csv->combine(@cols);
3834 $content .= $csv->string;
3836 elsif($p->{'format'} eq 'xls') {
3839 $xls->write($xls_r,$xls_c++,$_);
3845 $xls_workbook->close() if $p->{'format'} eq 'xls';
3847 { content => $content, format => $p->{'format'}, };
3852 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3853 return { 'error' => $session } if $context eq 'error';
3855 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3856 # FS::TicketSystem->init();
3857 # return { 'error' => 'get_ticket configuration error' }
3858 # if $FS::TicketSystem::system ne 'RT_Internal';
3860 # check existence and ownership as part of this
3861 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3862 my $rt_session = FS::TicketSystem->session('');
3863 my $Ticket = FS::TicketSystem->get_ticket_object(
3865 ticket_id => $p->{'ticket_id'},
3868 return { 'error' => 'ticket not found' } if !$Ticket;
3870 if ( length( $p->{'subject'} || '' ) ) {
3872 if ( $p->{'subject'} ne $Ticket->Subject ) {
3873 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3874 return { 'error' => "unable to set subject: $msg" } if !$val;
3878 if(length($p->{'reply'})) {
3879 my @err_or_res = FS::TicketSystem->correspond_ticket(
3881 'ticket_id' => $p->{'ticket_id'},
3882 'content' => $p->{'reply'},
3885 return { 'error' => 'unable to reply to ticket' }
3886 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3889 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3890 my $err_or_ticket = FS::TicketSystem->get_ticket(
3892 'ticket_id' => $p->{'ticket_id'},
3895 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3896 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3898 return { 'error' => $err_or_ticket };
3901 my @custs = @{$err_or_ticket->{'custs'}};
3902 my @txns = @{$err_or_ticket->{'txns'}};
3905 # superseded by check in get_ticket_object
3906 #return { 'error' => 'invalid ticket requested' }
3907 #unless grep($_ eq $custnum, @custs);
3909 foreach my $txn ( @txns ) {
3910 push @filtered_txns, $txn
3911 if ($txn->{'type'} eq 'EmailRecord'
3912 || $txn->{'type'} eq 'Correspond'
3913 || $txn->{'type'} eq 'Create');
3916 warn "$me get_ticket: successful: \n"
3918 return { 'error' => '',
3919 'transactions' => \@filtered_txns,
3920 'ticket_fields' => $err_or_ticket->{'fields'},
3921 'ticket_id' => $p->{'ticket_id'},
3925 sub adjust_ticket_priority {
3927 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3928 return { 'error' => $session } if $context eq 'error';
3930 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3931 # FS::TicketSystem->init;
3932 my $ss_priority = FS::TicketSystem->selfservice_priority;
3934 return { 'error' => 'adjust_ticket_priority configuration error' }
3935 if $FS::TicketSystem::system ne 'RT_Internal'
3938 my $values = $p->{'values'}; #hashref, id => priority value
3941 foreach my $id (keys %$values) {
3942 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3943 my $Ticket = FS::TicketSystem->get_ticket_object('',
3945 'custnum' => $custnum,
3948 $ticket_error{$id} = 'ticket not found';
3952 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3953 # We're not going to implement it for RT_External.
3954 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3955 my $new_value = $values->{$id};
3956 next if $old_value eq $new_value;
3958 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3960 # AddCustomFieldValue works fine (replacing any existing value) if it's
3961 # a single-valued custom field, which it should be. If it's not, you're
3962 # doing something wrong.
3964 if ( length($new_value) ) {
3965 ($val, $msg) = $Ticket->AddCustomFieldValue(
3966 Field => $ss_priority,
3967 Value => $new_value,
3971 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3972 Field => $ss_priority,
3973 Value => $old_value,
3977 $ticket_error{$id} = $msg if !$val;
3978 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3980 return { 'error' => '',
3981 'ticket_error' => \%ticket_error,
3982 %{ customer_info($p) } # send updated customer info back
3988 sub _custoragent_session_custnum {
3991 my($context, $session, $custnum);
3992 if ( $p->{'session_id'} ) {
3994 $context = 'customer';
3995 $session = _cache->get($p->{'session_id'})
3996 or return ( 'error' => "Can't resume session" ); #better error message
3997 $custnum = $session->{'custnum'};
3999 } elsif ( $p->{'agent_session_id'} ) {
4002 my $agent_cache = new FS::ClientAPI_SessionCache( {
4003 'namespace' => 'FS::ClientAPI::Agent',
4005 $session = $agent_cache->get($p->{'agent_session_id'})
4006 or return ( 'error' => "Can't resume session" ); #better error message
4007 $custnum = $p->{'custnum'};
4011 return ( 'error' => "Can't resume session" ); #better error message
4014 ($context, $session, $custnum);