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);
12 use Time::Local qw(timelocal_nocheck);
13 use Business::CreditCard;
16 use Spreadsheet::WriteExcel;
17 use FS::UI::Web::small_custview qw(small_custview); #less doh
19 use FS::UI::bytecount qw( display_bytecount );
22 use FS::Record qw(qsearch qsearchs dbh);
23 use FS::Msgcat qw(gettext);
24 use FS::Misc qw(card_types);
25 use FS::Misc::DateTime qw(parse_datetime);
27 use FS::ClientAPI_SessionCache;
39 use FS::legacy_cust_bill;
40 use FS::cust_main_county;
43 use FS::acct_rt_transaction;
47 $me = '[FS::ClientAPI::MyAccount]';
49 use vars qw( @cust_main_editable_fields );
50 @cust_main_editable_fields = qw(
51 first last company address1 address2 city
52 county state zip country
53 daytime night fax mobile
54 ship_first ship_last ship_company ship_address1 ship_address2 ship_city
55 ship_state ship_zip ship_country
56 ship_daytime ship_night ship_fax ship_mobile
58 payby payinfo payname paystart_month paystart_year payissue payip
59 ss paytype paystate stateid stateid_state
62 BEGIN { #preload to reduce time customer_info takes
63 if ( $FS::TicketSystem::system ) {
64 warn "$me: initializing ticket system\n" if $DEBUG;
65 FS::TicketSystem->init();
70 $cache ||= new FS::ClientAPI_SessionCache( {
71 'namespace' => 'FS::ClientAPI::MyAccount',
78 my($context, $session, $custnum) = _custoragent_session_custnum($p);
79 #return { 'error' => $session } if $context eq 'error';
82 if ( $context eq 'customer' ) {
84 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
87 $sth->execute($custnum) or die $sth->errstr;
89 $agentnum = $sth->fetchrow_arrayref->[0]
90 or die "no agentnum for custnum $custnum";
92 #} elsif ( $context eq 'agent' ) {
93 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
97 my $conf = new FS::Conf;
99 #false laziness w/Signup.pm
101 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
103 if ( $skin_info_cache_agent ) {
105 warn "$me loading cached skin info for agentnum $agentnum\n"
110 warn "$me populating skin info cache for agentnum $agentnum\n"
113 $skin_info_cache_agent = {
114 'agentnum' => $agentnum,
115 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
116 qw( company_name date_format ) ),
117 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
118 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
119 text_color link_color vlink_color hlink_color alink_color
120 font title_color title_align title_size menu_bgcolor menu_fontsize
123 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
124 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo )
126 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
127 qw( title_left_image title_right_image
128 menu_top_image menu_body_image menu_bottom_image
131 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
132 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
133 qw( head body_header body_footer company_address ) ),
136 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
140 #{ %$skin_info_cache_agent };
141 $skin_info_cache_agent;
148 my $conf = new FS::Conf;
152 'phone_login' => $conf->exists('selfservice_server-phone_login'),
153 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
154 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
155 'banner_image_md5' =>
156 md5_hex($conf->config_binary('selfservice-login_banner_image')),
163 sub login_banner_image {
165 my $conf = new FS::Conf;
166 my $image = $conf->config_binary('selfservice-login_banner_image');
168 'md5' => md5_hex($image),
173 #false laziness w/FS::ClientAPI::passwd::passwd
177 my $conf = new FS::Conf;
180 if ( $p->{'domain'} eq 'svc_phone'
181 && $conf->exists('selfservice_server-phone_login') ) {
183 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
184 return { error => 'Number not found.' } unless $svc_phone;
187 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
188 #return { error => 'Only primary user may log in.' }
189 # if $conf->exists('selfservice_server-primary_only')
190 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
192 return { error => 'Incorrect PIN.' }
193 unless $svc_phone->check_pin($p->{'password'});
201 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
202 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
204 my $svc_acct = qsearchs( 'svc_acct', { 'username' => $p->{'username'},
205 'domsvc' => $svc_domain->svcnum, }
207 return { error => 'User not found.' } unless $svc_acct;
209 if($conf->exists('selfservice_server-login_svcpart')) {
210 my @svcpart = $conf->config('selfservice_server-login_svcpart');
211 my $svcpart = $svc_acct->cust_svc->svcpart;
212 return { error => 'Invalid user.' }
213 unless grep($_ eq $svcpart, @svcpart);
216 return { error => 'Incorrect password.' }
217 unless $svc_acct->check_password($p->{'password'});
224 'svcnum' => $svc_x->svcnum,
227 my $cust_svc = $svc_x->cust_svc;
228 my $cust_pkg = $cust_svc->cust_pkg;
230 my $cust_main = $cust_pkg->cust_main;
231 $session->{'custnum'} = $cust_main->custnum;
232 if ( $conf->exists('pkg-balances') ) {
233 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
234 $cust_main->ncancelled_pkgs;
235 $session->{'pkgnum'} = $cust_pkg->pkgnum
236 if scalar(@cust_pkg) > 1;
240 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
241 #return { error => 'Only primary user may log in.' }
242 # if $conf->exists('selfservice_server-primary_only')
243 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
244 my $part_pkg = $cust_pkg->part_pkg;
245 return { error => 'Only primary user may log in.' }
246 if $conf->exists('selfservice_server-primary_only')
247 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
251 $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
252 } until ( ! defined _cache->get($session_id) ); #just in case
254 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
255 _cache->set( $session_id, $session, $timeout );
257 return { 'error' => '',
258 'session_id' => $session_id,
264 if ( $p->{'session_id'} ) {
265 _cache->remove($p->{'session_id'});
266 return { %{ skin_info($p) }, 'error' => '' };
268 return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
275 my($context, $session, $custnum) = _custoragent_session_custnum($p);
276 return { 'error' => $session } if $context eq 'error';
278 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
279 or return { 'error' => "Service not found" };
281 $session->{'svcnum'} = $svc_acct->svcnum;
283 my $conf = new FS::Conf;
284 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
285 _cache->set( $p->{'session_id'}, $session, $timeout );
287 return { 'error' => '' };
291 sub payment_gateway {
293 # takes a cust_main and a cust_payby entry, returns the payment_gateway
294 my $conf = new FS::Conf;
295 my $cust_main = shift;
296 my $cust_payby = shift;
297 my $gatewaynum = $conf->config('selfservice-payment_gateway');
299 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
300 die "configured gatewaynum $gatewaynum not found!" if !$pg;
304 return '' if ! FS::payby->realtime($cust_payby);
305 my $pg = $cust_main->agent->payment_gateway(
306 'method' => FS::payby->payby2bop($cust_payby),
316 my $conf = new FS::Conf;
318 my $info = skin_info($p);
320 use vars qw( $cust_paybys ); #cache for performance
321 unless ( $cust_paybys ) {
323 my %cust_paybys = map { $_ => 1 }
324 map { FS::payby->payby2payment($_) }
325 $conf->config('signup_server-payby');
327 $cust_paybys = [ keys %cust_paybys ];
330 $info->{'cust_paybys'} = $cust_paybys;
332 my($context, $session, $custnum) = _custoragent_session_custnum($p);
333 return { 'error' => $session } if $context eq 'error';
335 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
336 or return { 'error' => "unknown custnum $custnum" };
338 $info->{'hide_payment_fields'} = [
340 my $pg = payment_gateway($cust_main, $_);
341 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
342 } @{ $info->{cust_paybys} }
345 $info->{'self_suspend_reason'} =
346 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
348 $info->{'edit_ticket_subject'} =
349 $conf->exists('ticket_system-selfservice_edit_subject') &&
350 $cust_main->edit_subject;
353 'custnum' => $custnum,
354 'access_pkgnum' => $session->{'pkgnum'},
355 'access_svcnum' => $session->{'svcnum'},
362 my($context, $session, $custnum) = _custoragent_session_custnum($p);
363 return { 'error' => $session } if $context eq 'error';
367 my $conf = new FS::Conf;
368 if ($conf->exists('cust_main-require_address2')) {
369 $return{'require_address2'} = '1';
371 $return{'require_address2'} = '';
374 if ( $FS::TicketSystem::system ) {
375 warn "$me customer_info: initializing ticket system\n" if $DEBUG;
376 FS::TicketSystem->init();
379 if ( $custnum ) { #customer record
381 my $search = { 'custnum' => $custnum };
382 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
383 my $cust_main = qsearchs('cust_main', $search )
384 or return { 'error' => "unknown custnum $custnum" };
386 $return{display_custnum} = $cust_main->display_custnum;
388 if ( $session->{'pkgnum'} ) {
389 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
390 #next_bill_date from cust_pkg?
392 $return{balance} = $cust_main->balance;
393 $return{next_bill_date} = $cust_main->next_bill_date;
394 $return{next_bill_date_pretty} =
395 time2str('%m/%d/%Y', $return{next_bill_date} );
398 my @tickets = $cust_main->tickets;
399 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
400 if ( FS::TicketSystem->selfservice_priority ) {
401 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
405 ($a->{'_selfservice_priority'} eq '') <=>
406 ($b->{'_selfservice_priority'} eq '')
409 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
415 $return{tickets} = \@tickets;
418 unless ( $session->{'pkgnum'} ) {
421 invnum => $_->invnum,
422 date => time2str("%b %o, %Y", $_->_date),
425 } $cust_main->open_cust_bill;
426 $return{open_invoices} = \@open;
428 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
429 my $sth = dbh->prepare($sql) or die dbh->errstr;
430 $sth->execute($custnum) or die $sth->errstr;
431 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
432 $return{'last_invoice_date_pretty'} =
433 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
436 $return{countrydefault} = scalar($conf->config('countrydefault'));
438 $return{small_custview} =
439 small_custview( $cust_main,
440 $return{countrydefault},
441 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
444 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
445 $return{ship_name} = $cust_main->ship_first. ' '. $cust_main->get('ship_last');
447 $return{has_ship_address} = $cust_main->has_ship_address;
448 $return{status} = $cust_main->status;
449 $return{statuscolor} = $cust_main->statuscolor;
451 for (@cust_main_editable_fields) {
452 $return{$_} = $cust_main->get($_);
455 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
456 $return{payinfo} = $cust_main->paymask;
457 @return{'month', 'year'} = $cust_main->paydate_monthyear;
460 $return{'invoicing_list'} =
461 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
462 $return{'postal_invoicing'} =
463 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
465 if (scalar($conf->config('support_packages'))) {
466 my @support_services = ();
467 foreach ($cust_main->support_services) {
468 my $seconds = $_->svc_x->seconds;
469 my $time_remaining = (($seconds < 0) ? '-' : '' ).
470 int(abs($seconds)/3600)."h".
471 sprintf("%02d",(abs($seconds)%3600)/60)."m";
472 my $cust_pkg = $_->cust_pkg;
475 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
476 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
477 push @support_services, { svcnum => $_->svcnum,
478 time => $time_remaining,
483 $return{support_services} = \@support_services;
486 if ( $conf->config('prepayment_discounts-credit_type') ) {
488 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
491 if ( $session->{'svcnum'} ) {
492 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
493 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
494 $return{'svcnum'} = $session->{'svcnum'};
497 } elsif ( $session->{'svcnum'} ) { #no customer record
499 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
500 or die "unknown svcnum";
501 $return{name} = $svc_acct->email;
505 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
509 return { 'error' => '',
510 'custnum' => $custnum,
516 sub customer_info_short {
519 my($context, $session, $custnum) = _custoragent_session_custnum($p);
520 return { 'error' => $session } if $context eq 'error';
524 my $conf = new FS::Conf;
526 if ( $custnum ) { #customer record
528 my $search = { 'custnum' => $custnum };
529 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
530 my $cust_main = qsearchs('cust_main', $search )
531 or return { 'error' => "unknown custnum $custnum" };
533 $return{display_custnum} = $cust_main->display_custnum;
535 $return{countrydefault} = scalar($conf->config('countrydefault'));
537 $return{small_custview} =
538 small_custview( $cust_main,
539 $return{countrydefault},
543 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
544 $return{ship_name} = $cust_main->ship_first. ' '. $cust_main->get('ship_last');
546 $return{payby} = $cust_main->payby;
548 #none of these are terribly expensive if we want 'em...
549 for (@cust_main_editable_fields) {
550 $return{$_} = $cust_main->get($_);
553 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
554 $return{payinfo} = $cust_main->paymask;
555 @return{'month', 'year'} = $cust_main->paydate_monthyear;
558 $return{'invoicing_list'} =
559 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
560 #$return{'postal_invoicing'} =
561 # 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
563 if ( $session->{'svcnum'} ) {
564 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
565 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
566 $return{'svcnum'} = $session->{'svcnum'};
569 } elsif ( $session->{'svcnum'} ) { #no customer record
571 #uuh, not supproted yet... die?
572 return { 'error' => 'customer_info_short not yet supported as agent' };
576 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
580 return { 'error' => '',
581 'custnum' => $custnum,
586 sub billing_history {
589 my($context, $session, $custnum) = _custoragent_session_custnum($p);
590 return { 'error' => $session } if $context eq 'error';
592 return { 'error' => 'No customer' } unless $custnum;
594 my $search = { 'custnum' => $custnum };
595 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
596 my $cust_main = qsearchs('cust_main', $search )
597 or return { 'error' => "unknown custnum $custnum" };
601 if ( $session->{'pkgnum'} ) {
602 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
603 #next_bill_date from cust_pkg?
604 return { 'error' => 'No history for package' };
607 $return{balance} = $cust_main->balance;
608 $return{next_bill_date} = $cust_main->next_bill_date;
609 $return{next_bill_date_pretty} =
610 time2str('%m/%d/%Y', $return{next_bill_date} );
614 my $conf = new FS::Conf;
616 if ( $conf->exists('selfservice-billing_history-line_items') ) {
618 foreach my $cust_bill ( $cust_main->cust_bill ) {
621 'type' => 'Line item',
622 'description' => $_->desc. ( $_->sdate && $_->edate
623 ? ' '. time2str('%d-%b-%Y', $_->sdate).
624 ' To '. time2str('%d-%b-%Y', $_->edate)
627 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
628 'date' => $cust_bill->_date,
629 'date_pretty' => time2str('%m/%d/%Y', $cust_bill->_date ),
631 foreach $cust_bill->cust_bill_pkg;
639 'description' => 'Invoice #'. $_->display_invnum,
640 'amount' => sprintf('%.2f', $_->charged ),
642 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
644 foreach $cust_main->cust_bill;
650 'description' => 'Payment', #XXX type
651 'amount' => sprintf('%.2f', 0 - $_->paid ),
653 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
655 foreach $cust_main->cust_pay;
659 'description' => 'Credit', #more info?
660 'amount' => sprintf('%.2f', 0 -$_->amount ),
662 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
664 foreach $cust_main->cust_credit;
668 'description' => 'Refund', #more info? type, like payment?
669 'amount' => $_->refund,
671 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
673 foreach $cust_main->cust_refund;
675 @history = sort { $b->{'date'} <=> $a->{'date'} } @history;
677 $return{'history'} = \@history;
685 my $session = _cache->get($p->{'session_id'})
686 or return { 'error' => "Can't resume session" }; #better error message
688 my $custnum = $session->{'custnum'}
689 or return { 'error' => "no customer record" };
691 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
692 or return { 'error' => "unknown custnum $custnum" };
694 my $new = new FS::cust_main { $cust_main->hash };
695 # Avoid accidentally changing the service address.
696 if ( !$new->has_ship_address ) {
697 $new->set( $_ => $new->get($_) )
698 foreach $new->addr_fields;
701 $new->set( $_ => $p->{$_} )
702 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
705 if (exists($p->{'payby'})) {
706 $p->{'payby'} =~ /^([A-Z]{4})$/
707 or return { 'error' => "illegal_payby " . $p->{'payby'} };
711 if ( $payby =~ /^(CARD|DCRD)$/ ) {
713 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
715 if ( $new->payinfo eq $cust_main->paymask ) {
716 $new->payinfo($cust_main->payinfo);
718 $new->payinfo($p->{'payinfo'});
721 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
723 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
726 $p->{'payinfo1'} =~ /^([\dx]+)$/
727 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
729 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
730 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
732 $payinfo = $payinfo1. '@'. $payinfo2;
734 $new->payinfo( ($payinfo eq $cust_main->paymask)
735 ? $cust_main->payinfo
739 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
741 } elsif ( $payby =~ /^(BILL)$/ ) {
743 } elsif ( $payby ) { #notyet ready
744 return { 'error' => "unknown payby $payby" };
748 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
749 #false laziness with httemplate/edit/process/cust_main.cgi
750 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
751 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
753 @invoicing_list = $cust_main->invoicing_list;
756 my $error = $new->replace($cust_main, \@invoicing_list);
757 return { 'error' => $error } if $error;
760 return { 'error' => '' };
765 my $session = _cache->get($p->{'session_id'})
766 or return { 'error' => "Can't resume session" }; #better error message
772 my $conf = new FS::Conf;
773 use vars qw($payment_info); #cache for performance
774 unless ( $payment_info ) {
776 my %states = map { $_->state => 1 }
777 qsearch('cust_main_county', {
778 'country' => $conf->config('countrydefault') || 'US'
781 my %cust_paybys = map { $_ => 1 }
782 map { FS::payby->payby2payment($_) }
783 $conf->config('signup_server-payby');
785 my @cust_paybys = keys %cust_paybys;
789 #list all counties/states/countries
790 'cust_main_county' =>
791 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
793 #shortcut for one-country folks
795 [ sort { $a cmp $b } keys %states ],
797 'card_types' => card_types(),
799 'paytypes' => [ @FS::cust_main::paytypes ],
801 'paybys' => [ $conf->config('signup_server-payby') ],
802 'cust_paybys' => \@cust_paybys,
804 'stateid_label' => FS::Msgcat::_gettext('stateid'),
805 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
807 'show_ss' => $conf->exists('show_ss'),
808 'show_stateid' => $conf->exists('show_stateid'),
809 'show_paystate' => $conf->exists('show_bankstate'),
811 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
813 'credit_card_surcharge_percentage' => $conf->config('credit-card-surcharge-percentage'),
822 my %return = %$payment_info;
824 my $custnum = $session->{'custnum'};
826 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
827 or return { 'error' => "unknown custnum $custnum" };
829 $return{'hide_payment_fields'} = [
831 my $pg = payment_gateway($cust_main, $_);
832 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
833 } @{ $return{cust_paybys} }
836 $return{balance} = $cust_main->balance; #XXX pkg-balances?
838 $return{payname} = $cust_main->payname
839 || ( $cust_main->first. ' '. $cust_main->get('last') );
841 $return{$_} = $cust_main->get($_) for qw(address1 address2 city state zip);
843 $return{payby} = $cust_main->payby;
844 $return{stateid_state} = $cust_main->stateid_state;
846 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
847 $return{card_type} = cardtype($cust_main->payinfo);
848 $return{payinfo} = $cust_main->paymask;
850 @return{'month', 'year'} = $cust_main->paydate_monthyear;
854 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
855 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
856 $return{payinfo1} = $payinfo1;
857 $return{payinfo2} = $payinfo2;
858 $return{paytype} = $cust_main->paytype;
859 $return{paystate} = $cust_main->paystate;
860 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
863 if ( $conf->config('prepayment_discounts-credit_type') ) {
865 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
868 #doubleclick protection
870 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
872 return { 'error' => '',
878 #some false laziness with httemplate/process/payment.cgi - look there for
879 #ACH and CVV support stuff
881 sub validate_payment {
884 my $session = _cache->get($p->{'session_id'})
885 or return { 'error' => "Can't resume session" }; #better error message
887 my $custnum = $session->{'custnum'};
889 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
890 or return { 'error' => "unknown custnum $custnum" };
892 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
893 or return { 'error' => gettext('illegal_amount') };
895 return { error => 'Amount must be greater than 0' } unless $amount > 0;
897 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
898 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
899 my $discount_term = $1;
901 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
902 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
905 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
906 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
909 $p->{'payby'} ||= 'CARD';
910 $p->{'payby'} =~ /^([A-Z]{4})$/
911 or return { 'error' => "illegal_payby " . $p->{'payby'} };
914 #false laziness w/process/payment.cgi
917 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
919 $p->{'payinfo1'} =~ /^([\dx]+)$/
920 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
922 $p->{'payinfo2'} =~ /^([\dx]+)$/
923 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
925 $payinfo = $payinfo1. '@'. $payinfo2;
927 $payinfo = $cust_main->payinfo
928 if $cust_main->paymask eq $payinfo;
930 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
932 $payinfo = $p->{'payinfo'};
934 #more intelligent matching will be needed here if you change
935 #card_masking_method and don't remove existing paymasks
936 $payinfo = $cust_main->payinfo
937 if $cust_main->paymask eq $payinfo;
940 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
941 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
945 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
946 return { 'error' => gettext('unknown_card_type') }
947 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
949 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
950 if ( cardtype($payinfo) eq 'American Express card' ) {
951 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
952 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
955 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
956 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
962 die "unknown payby $payby";
966 'CARD' => [ qw( paystart_month paystart_year payissue payip
967 address1 address2 city state zip country ) ],
968 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
972 $card_type = cardtype($payinfo) if $payby eq 'CARD';
975 'cust_main' => $cust_main, #XXX or just custnum??
978 'payinfo' => $payinfo,
979 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
980 'card_type' => $card_type,
981 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
982 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
983 'payname' => $payname,
984 'paybatch' => $paybatch, #this doesn't actually do anything
986 'payname' => $payname,
987 'discount_term' => $discount_term,
988 'pkgnum' => $session->{'pkgnum'},
989 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
999 my $validate = validate_payment($p);
1000 return $validate if $validate->{'error'};
1002 my $conf = new FS::Conf;
1003 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1004 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1006 +{ map { $_=>$validate->{$_} }
1007 qw( card_type paymask payname paydate_pretty amount )
1012 sub process_stored_payment {
1015 my $session_id = $p->{'session_id'};
1017 my $payment_info = _cache->get( "payment_$session_id" )
1018 or return { 'error' => "Can't resume session" }; #better error message
1020 do_process_payment($payment_info);
1024 sub process_payment {
1027 my $payment_info = validate_payment($p);
1028 return $payment_info if $payment_info->{'error'};
1030 do_process_payment($payment_info);
1034 sub do_process_payment {
1035 my $validate = shift;
1037 my $cust_main = $validate->{'cust_main'};
1039 my $amount = delete $validate->{'amount'};
1042 my $payby = delete $validate->{'payby'};
1044 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1047 'paynum_ref' => \$paynum,
1050 return { 'error' => $error } if $error;
1052 $cust_main->apply_payments;
1054 if ( $validate->{'save'} ) {
1055 my $new = new FS::cust_main { $cust_main->hash };
1056 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1057 $new->set( $_ => $validate->{$_} )
1058 foreach qw( payname paystart_month paystart_year payissue payip );
1059 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1061 # Avoid accidentally changing the service address.
1062 if ( !$new->has_ship_address ) {
1063 $new->set( "ship_$_" => $new->get($_) )
1064 foreach $new->addr_fields;
1066 $new->set( $_ => $validate->{$_} )
1067 foreach qw(address1 address2 city state country zip);
1069 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1070 $new->set( $_ => $validate->{$_} )
1071 foreach qw( payname payip paytype paystate
1072 stateid stateid_state );
1073 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1075 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1076 $new->set( 'paydate' => $validate->{'paydate'} );
1077 my $error = $new->replace($cust_main);
1079 #no, this causes customers to process their payments again
1080 #return { 'error' => $error };
1081 #XXX just warn verosely for now so i can figure out how these happen in
1082 # the first place, eventually should redirect them to the "change
1083 #address" page but indicate the payment did process??
1084 delete($validate->{'payinfo'}); #don't want to log this!
1085 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1086 "NEW: ". Dumper($new)."\n".
1087 "OLD: ". Dumper($cust_main)."\n".
1088 "PACKET: ". Dumper($validate)."\n";
1096 my $receipt_html = '';
1098 # currently supported for realtime CC only; send receipt data to SS
1099 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1102 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1105 <TD ALIGN="right">Payment#</TD>
1106 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1110 <TD ALIGN="right">Date</TD>
1112 <TD BGCOLOR="#FFFFFF"><B>! .
1113 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1119 <TD ALIGN="right">Amount</TD>
1120 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1125 <TD ALIGN="right">Payment method</TD>
1126 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1137 my($gw, $auth, $order) = split(':', $cust_pay->paybatch);
1141 'amount' => sprintf('%.2f', $cust_pay->paid),
1142 'date' => $cust_pay->_date,
1143 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1144 'time_pretty' => time2str('%T', $cust_pay->_date),
1145 'auth_num' => $auth,
1146 'order_num' => $order,
1147 'receipt_html' => $receipt_html,
1154 'receipt_html' => '',
1161 sub realtime_collect {
1164 my $session = _cache->get($p->{'session_id'})
1165 or return { 'error' => "Can't resume session" }; #better error message
1167 my $custnum = $session->{'custnum'};
1169 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1170 or return { 'error' => "unknown custnum $custnum" };
1173 if ( $p->{'amount'} ) {
1174 $amount = $p->{'amount'};
1176 elsif ( $session->{'pkgnum'} ) {
1177 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1180 $amount = $cust_main->balance;
1183 my $error = $cust_main->realtime_collect(
1184 'method' => $p->{'method'},
1185 'amount' => $amount,
1186 'pkgnum' => $session->{'pkgnum'},
1187 'session_id' => $p->{'session_id'},
1191 return { 'error' => $error } unless ref( $error );
1193 return { 'error' => '', amount => $amount, %$error };
1196 sub process_payment_order_pkg {
1199 my $hr = process_payment($p);
1200 return $hr if $hr->{'error'};
1205 sub process_payment_order_renew {
1208 my $hr = process_payment($p);
1209 return $hr if $hr->{'error'};
1214 sub process_prepay {
1218 my $session = _cache->get($p->{'session_id'})
1219 or return { 'error' => "Can't resume session" }; #better error message
1223 my $custnum = $session->{'custnum'};
1225 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1226 or return { 'error' => "unknown custnum $custnum" };
1228 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1229 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1237 return { 'error' => $error } if $error;
1239 return { 'error' => '',
1240 'amount' => $amount,
1241 'seconds' => $seconds,
1242 'duration' => duration_exact($seconds),
1243 'upbytes' => $upbytes,
1244 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1245 'downbytes' => $downbytes,
1246 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1247 'totalbytes'=> $totalbytes,
1248 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1255 my $session = _cache->get($p->{'session_id'})
1256 or return { 'error' => "Can't resume session" }; #better error message
1258 my $custnum = $session->{'custnum'};
1260 my $invnum = $p->{'invnum'};
1262 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1263 'custnum' => $custnum } )
1264 or return { 'error' => "Can't find invnum" };
1268 return { 'error' => '',
1269 'invnum' => $invnum,
1270 'invoice_text' => join('', $cust_bill->print_text ),
1271 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1278 my $session = _cache->get($p->{'session_id'})
1279 or return { 'error' => "Can't resume session" }; #better error message
1281 my $custnum = $session->{'custnum'};
1283 my $invnum = $p->{'invnum'};
1285 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1286 'custnum' => $custnum } )
1287 or return { 'error' => "Can't find invnum" };
1291 return { 'error' => '',
1292 'invnum' => $invnum,
1293 'invoice_pdf' => $cust_bill->print_pdf({
1294 'unsquelch_cdr' => 1,
1295 'locale' => $p->{'locale'},
1301 sub legacy_invoice {
1303 my $session = _cache->get($p->{'session_id'})
1304 or return { 'error' => "Can't resume session" }; #better error message
1306 my $custnum = $session->{'custnum'};
1308 my $legacyinvnum = $p->{'legacyinvnum'};
1311 'legacyinvnum' => $legacyinvnum,
1312 'custnum' => $custnum,
1315 my $legacy_cust_bill =
1316 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1317 || qsearchs('legacy_cust_bill', \%hash )
1318 or return { 'error' => "Can't find legacyinvnum" };
1322 return { 'error' => '',
1323 'legacyinvnum' => $legacyinvnum,
1324 'legacyid' => $legacy_cust_bill->legacyid,
1325 'invoice_html' => $legacy_cust_bill->content_html,
1330 sub legacy_invoice_pdf {
1332 my $session = _cache->get($p->{'session_id'})
1333 or return { 'error' => "Can't resume session" }; #better error message
1335 my $custnum = $session->{'custnum'};
1337 my $legacyinvnum = $p->{'legacyinvnum'};
1339 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1340 'legacyinvnum' => $legacyinvnum,
1341 'custnum' => $custnum,
1342 }) or return { 'error' => "Can't find legacyinvnum" };
1346 return { 'error' => '',
1347 'legacyinvnum' => $legacyinvnum,
1348 'legacyid' => $legacy_cust_bill->legacyid,
1349 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1357 #sessioning for this? how do we get the session id to the backend invoice
1358 # template so it can add it to the link, blah
1361 if ( $p->{'invnum'} ) {
1362 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1363 or return { 'error' => 'unknown invnum' };
1364 $agentnum = $cust_bill->cust_main->agentnum;
1367 my $templatename = $p->{'template'} || $p->{'templatename'};
1369 #false laziness-ish w/view/cust_bill-logo.cgi
1371 my $conf = new FS::Conf;
1372 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1373 $templatename = "_$1";
1378 my $filename = "logo$templatename.png";
1380 return { 'error' => '',
1381 'logo' => $conf->config_binary($filename, $agentnum),
1382 'content_type' => 'image/png', #should allow gif, jpg too
1389 my $session = _cache->get($p->{'session_id'})
1390 or return { 'error' => "Can't resume session" }; #better error message
1392 my $custnum = $session->{'custnum'};
1394 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1395 or return { 'error' => "unknown custnum $custnum" };
1397 my $conf = new FS::Conf;
1399 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1401 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1405 return { 'error' => '',
1406 'balance' => $cust_main->balance,
1409 my $owed = $_->owed;
1411 +{ 'invnum' => $_->invnum,
1412 '_date' => $_->_date,
1413 'date' => time2str("%b %o, %Y", $_->_date),
1414 'date_short' => time2str("%m-%d-%Y", $_->_date),
1415 'previous' => sprintf('%.2f', ($_->previous)[0]),
1416 'charged' => sprintf('%.2f', $_->charged),
1417 'owed' => sprintf('%.2f', $owed),
1418 'balance' => sprintf('%.2f', $balance),
1423 'legacy_invoices' => [
1425 +{ 'legacyinvnum' => $_->legacyinvnum,
1426 'legacyid' => $_->legacyid,
1427 '_date' => $_->_date,
1428 'date' => time2str("%b %o, %Y", $_->_date),
1429 'date_short' => time2str("%m-%d-%Y", $_->_date),
1430 'charged' => sprintf('%.2f', $_->charged),
1431 'has_content' => ( length($_->content_pdf)
1432 || length($_->content_html) ),
1442 my $session = _cache->get($p->{'session_id'})
1443 or return { 'error' => "Can't resume session" }; #better error message
1445 my $custnum = $session->{'custnum'};
1447 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1448 or return { 'error' => "unknown custnum $custnum" };
1450 my @errors = $cust_main->cancel( 'quiet'=>1 );
1452 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1454 return { 'error' => $error };
1461 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1462 return { 'error' => $session } if $context eq 'error';
1464 my $search = { 'custnum' => $custnum };
1465 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1466 my $cust_main = qsearchs('cust_main', $search )
1467 or return { 'error' => "unknown custnum $custnum" };
1469 my $conf = new FS::Conf;
1471 # the duplication below is necessary:
1472 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1473 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1474 # non-backwards-compatible change breaking the software of anyone using the API
1475 # instead of the stock selfservice
1476 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1477 if( $conf->exists('selfservice_server-view-wholesale') ) {
1478 return { 'svcnum' => $session->{'svcnum'},
1479 'custnum' => $custnum,
1480 'cust_pkg' => [ map {
1482 part_pkg => [ map $_->hashref, $_->part_pkg ],
1484 [ map $_->hashref, $_->available_part_svc ],
1486 [ map { my $ref = { $_->hash,
1487 label => [ $_->label ],
1489 $ref->{_password} = $_->svc_x->_password
1490 if $context eq 'agent'
1491 && $conf->exists('agent-showpasswords')
1492 && $_->part_svc->svcdb eq 'svc_acct';
1497 } $cust_main->cust_pkg
1500 small_custview( $cust_main, $conf->config('countrydefault') ),
1501 'wholesale_view' => 1,
1502 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1503 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1504 'lnp' => $conf->exists('svc_phone-lnp'),
1508 { 'svcnum' => $session->{'svcnum'},
1509 'custnum' => $custnum,
1510 'cust_pkg' => [ map {
1511 my $primary_cust_svc = $_->primary_cust_svc;
1514 status => $_->status,
1516 [ map $_->hashref, $_->available_part_svc ],
1518 [ map { my $ref = { $_->hash,
1519 label => [ $_->label ],
1521 $ref->{_password} = $_->svc_x->_password
1522 if $context eq 'agent'
1523 && $conf->exists('agent-showpasswords')
1524 && $_->part_svc->svcdb eq 'svc_acct';
1525 $ref->{svchash} = { $_->svc_x->hash } if
1526 $_->part_svc->svcdb eq 'svc_phone';
1527 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1528 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1534 ? { $primary_cust_svc->hash,
1535 label => [ $primary_cust_svc->label ],
1536 finger => $primary_cust_svc->svc_x->finger, #uuh
1537 $primary_cust_svc->part_svc->hash,
1541 } $cust_main->ncancelled_pkgs
1544 small_custview( $cust_main, $conf->config('countrydefault') ),
1552 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1553 return { 'error' => $session } if $context eq 'error';
1555 my $search = { 'custnum' => $custnum };
1556 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1557 my $cust_main = qsearchs('cust_main', $search )
1558 or return { 'error' => "unknown custnum $custnum" };
1560 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1561 if ( ! $pkgnum && $p->{'svcnum'} ) {
1562 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1563 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1567 #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1568 foreach my $cust_pkg ( $p->{'ncancelled'}
1569 ? $cust_main->ncancelled_pkgs
1570 : $cust_main->unsuspended_pkgs ) {
1571 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1572 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1575 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1577 if ( $p->{'svcdb'} ) {
1578 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1580 : ref($p->{'svcdb'}) eq 'ARRAY'
1581 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1582 : { $p->{'svcdb'} => 1 };
1583 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1586 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1589 my $conf = new FS::Conf;
1592 'svcnum' => $session->{'svcnum'},
1593 'custnum' => $custnum,
1594 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1595 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1598 my $svc_x = $_->svc_x;
1599 my($label, $value) = $_->label;
1600 my $part_svc = $_->part_svc;
1601 my $svcdb = $part_svc->svcdb;
1602 my $cust_pkg = $_->cust_pkg;
1603 my $part_pkg = $cust_pkg->part_pkg;
1606 'svcnum' => $_->svcnum,
1607 'display_svcnum' => $_->display_svcnum,
1611 'pkg_label' => $cust_pkg->pkg_label,
1612 'pkg_status' => $cust_pkg->status,
1613 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1616 if ( $svcdb eq 'svc_acct' ) {
1619 'username' => $svc_x->username,
1620 'email' => $svc_x->email,
1621 'finger' => $svc_x->finger,
1622 'seconds' => $svc_x->seconds,
1623 'upbytes' => display_bytecount($svc_x->upbytes),
1624 'downbytes' => display_bytecount($svc_x->downbytes),
1625 'totalbytes' => display_bytecount($svc_x->totalbytes),
1627 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1628 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1629 'recharge_upbytes' =>
1630 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1631 'recharge_downbytes' =>
1632 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1633 'recharge_totalbytes' =>
1634 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1638 } elsif ( $svcdb eq 'svc_dsl' ) {
1639 $hash{'phonenum'} = $svc_x->phonenum;
1640 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1641 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1642 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1645 $hash{'name'} = $cust_main->name;
1648 # elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1662 sub _customer_svc_x {
1663 my($custnum, $svcnum, $table) = (shift, shift, shift);
1664 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1666 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1667 my $search = " AND custnum = $1";
1668 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1671 'table' => ($table || 'svc_acct'),
1672 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1673 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1674 #'LEFT JOIN cust_main USING ( custnum ) ',
1675 'hashref' => $hashref,
1676 'extra_sql' => $search, #important
1681 sub svc_status_html {
1684 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1685 return { 'error' => $session } if $context eq 'error';
1687 #XXX only svc_dsl for now
1688 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1689 or return { 'error' => "Service not found" };
1691 my $html = $svc_x->getstatus_html;
1693 return { 'html' => $html };
1697 sub svc_status_hash {
1700 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1701 return { 'error' => $session } if $context eq 'error';
1703 #XXX only svc_acct for now
1704 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1705 or return { 'error' => "Service not found" };
1707 my ( $html, $hashref ) = $svc_x->export_getstatus;
1712 sub set_svc_status_hash {
1715 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1716 return { 'error' => $session } if $context eq 'error';
1718 #XXX only svc_acct for now
1719 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1720 or return { 'error' => "Service not found" };
1722 warn "set_svc_status_hash ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1724 my $error = $svc_x->export_setstatus($p); #$p? returns error?
1725 return { 'error' => $error } if $error;
1727 return {}; #? { 'error' => '' }
1732 sub acct_forward_info {
1735 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1736 return { 'error' => $session } if $context eq 'error';
1738 my $svc_forward = _customer_svc_x( $custnum,
1739 { 'srcsvc' => $p->{'svcnum'} },
1742 or return { 'error' => '',
1746 return { 'error' => '',
1747 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1752 sub process_acct_forward {
1754 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1755 return { 'error' => $session } if $context eq 'error';
1757 my $old = _customer_svc_x( $custnum,
1758 { 'srcsvc' => $p->{'svcnum'} },
1762 if ( $p->{'dst'} eq '' ) {
1764 my $error = $old->delete;
1765 return { 'error' => $error };
1767 return { 'error' => '' };
1770 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1771 'dst' => $p->{'dst'},
1776 $new->svcnum($old->svcnum);
1777 my $cust_svc = $old->cust_svc;
1778 $new->svcpart($old->svcpart);
1779 $new->pkgnuym($old->pkgnum);
1780 $error = $new->replace($old);
1782 my $conf = new FS::Conf;
1783 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
1785 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
1786 or return { 'error' => 'No service' }; #how would we even get here?
1788 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
1790 $error = $new->insert;
1793 return { 'error' => $error };
1797 sub list_dsl_devices {
1800 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1801 return { 'error' => $session } if $context eq 'error';
1803 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1804 or return { 'error' => "Service not found" };
1807 'devices' => [ map {
1808 +{ 'mac_addr' => $_->mac_addr };
1809 } $svc_dsl->dsl_device
1815 sub add_dsl_device {
1818 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1819 return { 'error' => $session } if $context eq 'error';
1821 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1822 or return { 'error' => "Service not found" };
1824 return { 'error' => 'No MAC address supplied' }
1825 unless length($p->{'mac_addr'});
1827 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
1828 'mac_addr' => scalar($p->{'mac_addr'}),
1830 my $error = $dsl_device->insert;
1831 return { 'error' => $error };
1835 sub delete_dsl_device {
1838 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1839 return { 'error' => $session } if $context eq 'error';
1841 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1842 or return { 'error' => "Service not found" };
1844 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
1845 'mac_addr' => scalar($p->{'mac_addr'}),
1848 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
1850 my $error = $dsl_device->delete;
1851 return { 'error' => $error };
1857 _usage_details( \&_port_graph, $p,
1858 'svcdb' => 'svc_port',
1863 my($svc_port, $begin, $end) = @_;
1865 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
1866 push @usage, { 'png' => $pngOrError };
1870 sub _list_svc_usage {
1871 my($svc_acct, $begin, $end) = @_;
1873 foreach my $part_export (
1874 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1875 qw( sqlradius sqlradius_withdomain )
1877 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1882 sub list_svc_usage {
1883 _usage_details(\&_list_svc_usage, @_);
1886 sub _list_support_usage {
1887 my($svc_acct, $begin, $end) = @_;
1889 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1890 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1892 push @usage, { 'seconds' => $_->seconds,
1893 'support' => $_->support,
1894 '_date' => $_->_date,
1895 'id' => $_->transaction_id,
1896 'creator' => $_->creator,
1897 'subject' => $_->subject,
1898 'status' => $_->status,
1899 'ticketid' => $_->ticketid,
1905 sub list_support_usage {
1906 _usage_details(\&_list_support_usage, @_);
1909 sub _list_cdr_usage {
1910 # XXX CDR type support...
1911 my($svc_phone, $begin, $end, %opt) = @_;
1912 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
1913 $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1916 sub list_cdr_usage {
1918 _usage_details( \&_list_cdr_usage, $p,
1919 'svcdb' => 'svc_phone',
1923 sub _usage_details {
1924 my($callback, $p, %opt) = @_;
1926 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1927 return { 'error' => $session } if $context eq 'error';
1929 my $search = { 'svcnum' => $p->{'svcnum'} };
1930 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1932 my $svcdb = $opt{'svcdb'} || 'svc_acct';
1934 my $svc_x = qsearchs( $svcdb, $search );
1935 return { 'error' => 'No service selected in list_svc_usage' }
1938 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1939 my $freq = $cust_pkg->part_pkg->freq;
1942 if ( $svcdb eq 'svc_phone' ) {
1943 my $format = $cust_pkg->part_pkg->option('output_format') || '';
1944 $format = '' if $format =~ /^sum_/;
1945 # sensible default if there is no format or it's a summary format
1946 if ( $cust_pkg->part_pkg->plan eq 'voip_inbound' ) {
1947 $format ||= 'source_default';
1948 $callback_opt{inbound} = 1;
1951 $format ||= 'default';
1954 $callback_opt{format} = $format;
1955 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
1958 my $start = $cust_pkg->setup;
1959 #my $end = $cust_pkg->bill; # or time?
1962 unless ( $p->{beginning} ) {
1963 $p->{beginning} = $cust_pkg->last_bill;
1964 $p->{ending} = $end;
1967 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
1971 #kinda false laziness with FS::cust_main::bill, but perhaps
1972 #we should really change this bit to DateTime and DateTime::Duration
1974 #change this bit to use Date::Manip? CAREFUL with timezones (see
1975 # mailing list archive)
1976 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
1977 (localtime($p->{ending}) )[0,1,2,3,4,5];
1978 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
1979 (localtime($p->{beginning}) )[0,1,2,3,4,5];
1981 if ( $freq =~ /^\d+$/ ) {
1983 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
1985 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
1986 } elsif ( $freq =~ /^(\d+)w$/ ) {
1988 $nmday += $weeks * 7;
1989 $pmday -= $weeks * 7;
1990 } elsif ( $freq =~ /^(\d+)d$/ ) {
1994 } elsif ( $freq =~ /^(\d+)h$/ ) {
1999 return { 'error' => "unparsable frequency: ". $freq };
2002 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2003 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2007 'svcnum' => $p->{svcnum},
2008 'beginning' => $p->{beginning},
2009 'ending' => $p->{ending},
2010 'previous' => ($previous > $start) ? $previous : $start,
2011 'next' => ($next < $end) ? $next : $end,
2012 'header' => $header,
2020 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2021 return { 'error' => $session } if $context eq 'error';
2023 my $search = { 'custnum' => $custnum };
2024 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2025 my $cust_main = qsearchs('cust_main', $search )
2026 or return { 'error' => "unknown custnum $custnum" };
2028 my $status = $cust_main->status;
2029 #false laziness w/ClientAPI/Signup.pm
2031 my $cust_pkg = new FS::cust_pkg ( {
2032 'custnum' => $custnum,
2033 'pkgpart' => $p->{'pkgpart'},
2035 my $error = $cust_pkg->check;
2036 return { 'error' => $error } if $error;
2039 unless ( $p->{'svcpart'} eq 'none' ) {
2043 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2045 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2046 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2047 $svcdb = $part_svc->svcdb;
2049 $svcdb = 'svc_acct';
2051 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2054 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2055 'svc_domain' => [ qw( domain ) ],
2056 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2057 'svc_external' => [ qw( id title ) ],
2058 'svc_pbx' => [ qw( id title ) ],
2061 my $svc_x = "FS::$svcdb"->new( {
2062 'svcpart' => $svcpart,
2063 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2066 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2069 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2070 my $acct_snarf = new FS::acct_snarf ( {
2071 'machine' => $p->{"snarf_machine$snarfnum"},
2072 'protocol' => $p->{"snarf_protocol$snarfnum"},
2073 'username' => $p->{"snarf_username$snarfnum"},
2074 '_password' => $p->{"snarf_password$snarfnum"},
2077 push @acct_snarf, $acct_snarf;
2079 $svc_x->child_objects( \@acct_snarf );
2082 my $y = $svc_x->setdefault; # arguably should be in new method
2083 return { 'error' => $y } if $y && !ref($y);
2085 $error = $svc_x->check;
2086 return { 'error' => $error } if $error;
2093 tie my %hash, 'Tie::RefHash';
2094 %hash = ( $cust_pkg => \@svc );
2096 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
2097 return { 'error' => $error } if $error;
2099 my $conf = new FS::Conf;
2100 if ( $conf->exists('signup_server-realtime') ) {
2102 my $bill_error = _do_bop_realtime( $cust_main, $status );
2105 $cust_pkg->cancel('quiet'=>1);
2108 $cust_pkg->reexport;
2112 $cust_pkg->reexport;
2115 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2117 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2124 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2125 return { 'error' => $session } if $context eq 'error';
2127 my $search = { 'custnum' => $custnum };
2128 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2129 my $cust_main = qsearchs('cust_main', $search )
2130 or return { 'error' => "unknown custnum $custnum" };
2132 my $status = $cust_main->status;
2133 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2134 or return { 'error' => "unknown package $p->{pkgnum}" };
2137 my $error = FS::cust_pkg::order( $custnum,
2143 my $conf = new FS::Conf;
2144 if ( $conf->exists('signup_server-realtime') ) {
2146 my $bill_error = _do_bop_realtime( $cust_main, $status );
2149 $newpkg[0]->suspend;
2152 $newpkg[0]->reexport;
2156 $newpkg[0]->reexport;
2159 return { error => '', pkgnum => $cust_pkg->pkgnum };
2163 sub order_recharge {
2166 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2167 return { 'error' => $session } if $context eq 'error';
2169 my $search = { 'custnum' => $custnum };
2170 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2171 my $cust_main = qsearchs('cust_main', $search )
2172 or return { 'error' => "unknown custnum $custnum" };
2174 my $status = $cust_main->status;
2175 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2176 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2178 my $svc_x = $cust_svc->svc_x;
2179 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2182 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2183 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2184 recharge_totalbytes );
2185 my $amount = $part_pkg->option('recharge_amount', 1);
2187 my ($l, $v, $d) = $cust_svc->label; # blah
2188 my $pkg = "Recharge $v";
2190 my $bill_error = $cust_main->charge($amount, $pkg,
2191 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2192 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2193 $part_pkg->taxclass); #meh
2195 my $conf = new FS::Conf;
2196 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2198 $bill_error = _do_bop_realtime( $cust_main, $status );
2203 my $error = $svc_x->recharge (\%vhash);
2204 return { 'error' => $error } if $error;
2208 my $error = $bill_error;
2209 $error ||= $svc_x->recharge (\%vhash);
2210 return { 'error' => $error } if $error;
2213 return { error => '', svc => $cust_svc->part_svc->svc };
2217 sub _do_bop_realtime {
2218 my ($cust_main, $status) = (shift, shift);
2220 my $old_balance = $cust_main->balance;
2222 my $bill_error = $cust_main->bill
2223 || $cust_main->apply_payments_and_credits
2224 || $cust_main->realtime_collect('selfservice' => 1);
2226 if ( $cust_main->balance > $old_balance
2227 && $cust_main->balance > 0
2228 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
2229 1 : $status eq 'suspended' ) ) {
2230 #this makes sense. credit is "un-doing" the invoice
2231 my $conf = new FS::Conf;
2232 $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
2233 'self-service decline',
2234 'reason_type' => $conf->config('signup_credit_type'),
2236 $cust_main->apply_credits( 'order' => 'newest' );
2238 return { 'error' => '_decline', 'bill_error' => $bill_error };
2247 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2248 return { 'error' => $session } if $context eq 'error';
2250 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2251 or return { 'error' => "unknown custnum $custnum" };
2253 my @cust_pkg = sort { $a->bill <=> $b->bill }
2254 grep { $_->part_pkg->freq ne '0' }
2255 $cust_main->ncancelled_pkgs;
2257 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2259 my $total = $cust_main->balance;
2262 my $bill = $_->bill;
2263 $total += $_->part_pkg->base_recur($_, \$bill);
2264 my $renew_date = $_->part_pkg->add_freq($_->bill);
2266 'pkgnum' => $_->pkgnum,
2267 'amount' => sprintf('%.2f', $total),
2268 'bill_date' => $_->bill,
2269 'bill_date_pretty' => time2str('%x', $_->bill),
2270 'renew_date' => $renew_date,
2271 'renew_date_pretty' => time2str('%x', $renew_date),
2272 'expire_date' => $_->expire,
2273 'expire_date_pretty' => time2str('%x', $_->expire),
2278 return { 'dates' => \@array };
2282 sub payment_info_renew_info {
2284 my $renew_info = renew_info($p);
2285 my $payment_info = payment_info($p);
2286 return { %$renew_info,
2294 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2295 return { 'error' => $session } if $context eq 'error';
2297 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2298 or return { 'error' => "unknown custnum $custnum" };
2300 my $date = $p->{'date'};
2304 #freeside-daily -n -d $date fs_daily $custnum
2305 $cust_main->bill_and_collect( 'time' => $date,
2306 'invoice_time' => $now,
2307 'actual_time' => $now,
2308 'check_freq' => '1d',
2311 return { 'error' => '' };
2317 my $session = _cache->get($p->{'session_id'})
2318 or return { 'error' => "Can't resume session" }; #better error message
2320 my $custnum = $session->{'custnum'};
2322 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2323 or return { 'error' => "unknown custnum $custnum" };
2325 my $conf = new FS::Conf;
2327 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2328 or return { 'error' => 'Permission denied' };
2330 my $pkgnum = $p->{'pkgnum'};
2332 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2333 'pkgnum' => $pkgnum, } )
2334 or return { 'error' => "unknown pkgnum $pkgnum" };
2336 my $error = $cust_pkg->suspend(reason => $reasonnum);
2337 return { 'error' => $error };
2343 my $session = _cache->get($p->{'session_id'})
2344 or return { 'error' => "Can't resume session" }; #better error message
2346 my $custnum = $session->{'custnum'};
2348 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2349 or return { 'error' => "unknown custnum $custnum" };
2351 my $pkgnum = $p->{'pkgnum'};
2353 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2354 'pkgnum' => $pkgnum, } )
2355 or return { 'error' => "unknown pkgnum $pkgnum" };
2357 my $error = $cust_pkg->cancel('quiet' => 1);
2358 return { 'error' => $error };
2362 sub provision_phone {
2365 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2367 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2368 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2369 return { 'error' => $session } if $context eq 'error';
2371 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2372 return { 'error' => 'service not found' } unless $svc_phone;
2373 return { 'error' => 'invalid svcnum' }
2374 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2376 $svc_phone->email($p->{'email'})
2377 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2378 $svc_phone->forwarddst($p->{'forwarddst'})
2379 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2380 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2381 return { 'error' => $svc_phone->replace };
2385 unless($p->{'lnp'}) {
2386 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2387 $p->{'lnp_status'} = "portingin";
2388 return _provision( 'FS::svc_phone',
2389 [qw(lnp_desired_due_date lnp_other_provider
2390 lnp_other_provider_account phonenum countrycode lnp_status)],
2391 [qw(phonenum countrycode)],
2398 unless (scalar(@bulkdid)) {
2399 return _provision( 'FS::svc_phone',
2400 [qw(phonenum countrycode)],
2401 [qw(phonenum countrycode)],
2407 # bulk DID order case
2409 foreach my $did ( @bulkdid ) {
2410 $did =~ s/[^0-9]//g;
2411 $error = _provision( 'FS::svc_phone',
2412 [qw(phonenum countrycode)],
2413 [qw(phonenum countrycode)],
2415 'pkgnum' => $p->{'pkgnum'},
2416 'svcpart' => $p->{'svcpart'},
2418 'countrycode' => $p->{'countrycode'},
2419 'session_id' => $p->{'session_id'},
2422 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2424 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2427 sub provision_acct {
2429 warn "provision_acct called\n"
2432 return { 'error' => gettext('passwords_dont_match') }
2433 if $p->{'_password'} ne $p->{'_password2'};
2434 return { 'error' => gettext('empty_password') }
2435 unless length($p->{'_password'});
2437 if ($p->{'domsvc'}) {
2438 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2439 qw ( svcpart pkgnum ) );
2440 return { 'error' => gettext('invalid_domain') }
2441 unless ($domains{$p->{'domsvc'}});
2444 warn "provision_acct calling _provision\n"
2446 _provision( 'FS::svc_acct',
2447 [qw(username _password domsvc)],
2448 [qw(username _password domsvc)],
2454 sub provision_external {
2456 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2457 _provision( 'FS::svc_external',
2466 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2467 warn "_provision called for $class\n"
2470 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2471 return { 'error' => $session } if $context eq 'error';
2473 my $search = { 'custnum' => $custnum };
2474 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2475 my $cust_main = qsearchs('cust_main', $search )
2476 or return { 'error' => "unknown custnum $custnum" };
2478 my $pkgnum = $p->{'pkgnum'};
2480 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2482 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2483 'pkgnum' => $pkgnum,
2485 or return { 'error' => "unknown pkgnum $pkgnum" };
2487 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2489 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2490 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2492 warn "creating $class record\n"
2494 my $svc_x = $class->new( {
2495 'pkgnum' => $p->{'pkgnum'},
2496 'svcpart' => $p->{'svcpart'},
2497 map { $_ => $p->{$_} } @$fields
2499 warn "inserting $class record\n"
2501 my $error = $svc_x->insert;
2504 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2506 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2509 my $return = { 'svc' => $part_svc->svc,
2511 map { $_ => $svc_x->get($_) } @$return_fields
2513 warn "_provision returning ". Dumper($return). "\n"
2522 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2523 return { 'error' => $session } if $context eq 'error';
2525 my $search = { 'custnum' => $custnum };
2526 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2527 my $cust_main = qsearchs('cust_main', $search )
2528 or return { 'error' => "unknown custnum $custnum" };
2530 my $pkgnum = $p->{'pkgnum'};
2532 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2533 'pkgnum' => $pkgnum,
2535 or return { 'error' => "unknown pkgnum $pkgnum" };
2537 my $svcpart = $p->{'svcpart'};
2539 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2540 'svcpart' => $svcpart, } )
2541 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2542 my $part_svc = $pkg_svc->part_svc;
2544 my $conf = new FS::Conf;
2547 'svc' => $part_svc->svc,
2548 'svcdb' => $part_svc->svcdb,
2549 'pkgnum' => $pkgnum,
2550 'svcpart' => $svcpart,
2551 'custnum' => $custnum,
2553 'security_phrase' => 0, #XXX !
2554 'svc_acct_pop' => [], #XXX !
2556 'init_popstate' => '',
2561 small_custview( $cust_main, $conf->config('countrydefault') ),
2565 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2566 && $ret->{'svcdb'} eq 'svc_phone') {
2567 $ret->{'svcnum'} = $p->{'svcnum'};
2568 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2569 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2570 $ret->{'email'} = $svc_phone->email;
2571 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2578 sub unprovision_svc {
2581 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2582 return { 'error' => $session } if $context eq 'error';
2584 my $search = { 'custnum' => $custnum };
2585 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2586 my $cust_main = qsearchs('cust_main', $search )
2587 or return { 'error' => "unknown custnum $custnum" };
2589 my $svcnum = $p->{'svcnum'};
2591 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2592 or return { 'error' => "unknown svcnum $svcnum" };
2594 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2595 unless $cust_svc->cust_pkg->custnum == $custnum;
2597 my $conf = new FS::Conf;
2599 return { 'svc' => $cust_svc->part_svc->svc,
2600 'error' => $cust_svc->cancel,
2602 small_custview( $cust_main, $conf->config('countrydefault') ),
2607 sub myaccount_passwd {
2609 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2610 return { 'error' => $session } if $context eq 'error';
2612 return { 'error' => "New passwords don't match." }
2613 if $p->{'new_password'} ne $p->{'new_password2'};
2615 return { 'error' => 'Enter new password' }
2616 unless length($p->{'new_password'});
2618 #my $search = { 'custnum' => $custnum };
2619 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2620 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2621 my $search = " AND custnum = $1";
2622 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2624 my $svc_acct = qsearchs( {
2625 'table' => 'svc_acct',
2626 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2627 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2628 'LEFT JOIN cust_main USING ( custnum ) ',
2629 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2630 'extra_sql' => $search, #important
2632 or return { 'error' => "Service not found" };
2634 if ( exists($p->{'old_password'}) ) {
2635 return { 'error' => "Incorrect password." }
2636 unless $svc_acct->check_password($p->{'old_password'});
2639 $svc_acct->set_password($p->{'new_password'});
2640 my $error = $svc_acct->replace();
2642 my($label, $value) = $svc_acct->cust_svc->label;
2644 return { 'error' => $error,
2654 my $conf = new FS::Conf;
2655 my $verification = $conf->config('selfservice-password_reset_verification')
2656 or return { 'error' => 'Password resets disabled' };
2658 my $username = $p->{'username'};
2660 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
2661 or return { 'error' => 'Account not found' };
2663 my $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2664 'domsvc' => $svc_domain->svcnum }
2666 or return { 'error' => 'Account not found' };
2668 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
2669 or return { 'error' => 'Account not found' };
2671 my $cust_main = $cust_pkg->cust_main;
2675 my( $p, $cust_main ) = @_;
2676 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
2677 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
2680 my( $p, $cust_main ) = @_;
2681 my $cust_pay = qsearchs({
2682 'table' => 'cust_pay',
2683 'hashref' => { 'custnum' => $cust_main->custnum },
2684 'order_by' => 'ORDER BY _date DESC LIMIT 1',
2688 $p->{'amount'} == $cust_pay->paid;
2691 my( $p, $cust_main ) = @_;
2692 $p->{'zip'} eq $cust_main->zip
2693 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
2697 foreach my $verify ( split(',', $verification) ) {
2699 &{ $verify{$verify} }( $p, $cust_main )
2700 or return { 'error' => 'Account not found' };
2704 #okay, we're verified, now create a unique session
2706 my $reset_session = {
2707 'svcnum' => $svc_acct->svcnum,
2710 my $timeout = '1 hour'; #?
2712 my $reset_session_id;
2714 $reset_session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
2715 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") ); #just in case
2717 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
2721 my $msgnum = $conf->config('selfservice-password_reset_msgnum', $cust_main->agentnum);
2722 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
2723 return { 'error' => "selfservice-password_reset_msgnum unset" } unless $msgnum;
2724 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
2725 my $error = $msg_template->send( 'cust_main' => $cust_main,
2726 'object' => $svc_acct,
2727 'substitutions' => {
2728 'session_id' => $reset_session_id,
2732 return { 'error' => $error }; #????
2735 return { 'error' => '' };
2738 sub check_reset_passwd {
2741 my $conf = new FS::Conf;
2742 my $verification = $conf->config('selfservice-password_reset_verification')
2743 or return { 'error' => 'Password resets disabled' };
2745 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
2746 or return { 'error' => "Can't resume session" }; #better error message
2748 my $svcnum = $reset_session->{'svcnum'};
2750 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
2751 or return { 'error' => "Service not found" };
2753 return { 'error' => '',
2754 'username' => $svc_acct->username,
2759 sub process_reset_passwd {
2762 my $conf = new FS::Conf;
2763 my $verification = $conf->config('selfservice-password_reset_verification')
2764 or return { 'error' => 'Password resets disabled' };
2766 return { 'error' => "New passwords don't match." }
2767 if $p->{'new_password'} ne $p->{'new_password2'};
2769 return { 'error' => 'Enter new password' }
2770 unless length($p->{'new_password'});
2772 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
2773 or return { 'error' => "Can't resume session" }; #better error message
2775 my $svcnum = $reset_session->{'svcnum'};
2777 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
2778 or return { 'error' => "Service not found" };
2780 $svc_acct->set_password($p->{'new_password'});
2781 my $error = $svc_acct->replace();
2783 my($label, $value) = $svc_acct->cust_svc->label;
2785 return { 'error' => $error,
2794 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2795 return { 'error' => $session } if $context eq 'error';
2797 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
2798 FS::TicketSystem->init();
2800 my $conf = new FS::Conf;
2801 my $queue = $p->{'queue'}
2802 || $conf->config('ticket_system-selfservice_queueid')
2803 || $conf->config('ticket_system-default_queueid');
2805 warn "$me create_ticket: creating ticket\n" if $DEBUG;
2806 my $err_or_ticket = FS::TicketSystem->create_ticket(
2807 '', #create RT session based on FS CurrentUser (fs_selfservice)
2809 'custnum' => $custnum,
2810 'svcnum' => $session->{'svcnum'},
2811 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
2814 if ( ref($err_or_ticket) ) {
2815 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
2817 return { 'error' => '',
2818 'ticket_id' => $err_or_ticket->id,
2821 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
2823 return { 'error' => $err_or_ticket };
2831 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2832 return { 'error' => $session } if $context eq 'error';
2834 return { error => 'requested format not implemented' }
2835 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
2837 my $conf = new FS::Conf;
2838 my $age_threshold = 0;
2839 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
2840 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
2842 my $search = { 'custnum' => $custnum };
2843 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2844 my $cust_main = qsearchs('cust_main', $search )
2845 or return { 'error' => "unknown custnum $custnum" };
2847 # does it make more sense to just run one sql query for this instead of all the
2848 # insanity below? would increase performance greately for large data sets?
2850 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
2851 my @part_svc = $cust_pkg->part_svc;
2852 foreach my $part_svc ( @part_svc ) {
2853 if($part_svc->svcdb eq 'svc_phone'){
2854 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
2855 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
2856 push @svc_phone, $cust_pkg_svc->svc_x
2857 if $cust_pkg_svc->date_inserted >= $age_threshold;
2865 my($xls_r,$xls_c) = (0,0);
2868 my @fields = qw( countrycode phonenum pin sip_password phone_name );
2869 if($p->{'format'} eq 'csv') {
2870 $csv = new Text::CSV_XS { 'always_quote' => 1,
2873 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2874 $content .= $csv->string;
2876 elsif($p->{'format'} eq 'xls') {
2877 my $XLS1 = new IO::Scalar \$content;
2878 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
2879 or return { 'error' => "Error opening .xls file: $!" };
2880 $xls = $xls_workbook->add_worksheet('DIDs');
2881 foreach ( @fields ) {
2882 $xls->write(0,$xls_c++,$_);
2887 foreach my $svc_phone ( @svc_phone ) {
2888 my @cols = map { $svc_phone->$_ } @fields;
2889 if($p->{'format'} eq 'csv') {
2890 return { 'error' => 'Unable to create CSV' }
2891 unless $csv->combine(@cols);
2892 $content .= $csv->string;
2894 elsif($p->{'format'} eq 'xls') {
2897 $xls->write($xls_r,$xls_c++,$_);
2903 $xls_workbook->close() if $p->{'format'} eq 'xls';
2905 { content => $content, format => $p->{'format'}, };
2910 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2911 return { 'error' => $session } if $context eq 'error';
2913 warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2914 FS::TicketSystem->init();
2915 return { 'error' => 'get_ticket configuration error' }
2916 if $FS::TicketSystem::system ne 'RT_Internal';
2918 # check existence and ownership as part of this
2919 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2920 my $rt_session = FS::TicketSystem->session('');
2921 my $Ticket = FS::TicketSystem->get_ticket_object(
2923 ticket_id => $p->{'ticket_id'},
2926 return { 'error' => 'ticket not found' } if !$Ticket;
2928 if ( length( $p->{'subject'} || '' ) ) {
2930 if ( $p->{'subject'} ne $Ticket->Subject ) {
2931 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
2932 return { 'error' => "unable to set subject: $msg" } if !$val;
2936 if(length($p->{'reply'})) {
2937 my @err_or_res = FS::TicketSystem->correspond_ticket(
2939 'ticket_id' => $p->{'ticket_id'},
2940 'content' => $p->{'reply'},
2943 return { 'error' => 'unable to reply to ticket' }
2944 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2947 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
2948 my $err_or_ticket = FS::TicketSystem->get_ticket(
2950 'ticket_id' => $p->{'ticket_id'},
2953 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
2954 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
2956 return { 'error' => $err_or_ticket };
2959 my @custs = @{$err_or_ticket->{'custs'}};
2960 my @txns = @{$err_or_ticket->{'txns'}};
2963 # superseded by check in get_ticket_object
2964 #return { 'error' => 'invalid ticket requested' }
2965 #unless grep($_ eq $custnum, @custs);
2967 foreach my $txn ( @txns ) {
2968 push @filtered_txns, $txn
2969 if ($txn->{'type'} eq 'EmailRecord'
2970 || $txn->{'type'} eq 'Correspond'
2971 || $txn->{'type'} eq 'Create');
2974 warn "$me get_ticket: successful: \n"
2976 return { 'error' => '',
2977 'transactions' => \@filtered_txns,
2978 'ticket_fields' => $err_or_ticket->{'fields'},
2979 'ticket_id' => $p->{'ticket_id'},
2983 sub adjust_ticket_priority {
2985 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2986 return { 'error' => $session } if $context eq 'error';
2988 warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
2989 FS::TicketSystem->init;
2990 my $ss_priority = FS::TicketSystem->selfservice_priority;
2992 return { 'error' => 'adjust_ticket_priority configuration error' }
2993 if $FS::TicketSystem::system ne 'RT_Internal'
2996 my $values = $p->{'values'}; #hashref, id => priority value
2999 foreach my $id (keys %$values) {
3000 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3001 my $Ticket = FS::TicketSystem->get_ticket_object('',
3003 'custnum' => $custnum,
3006 $ticket_error{$id} = 'ticket not found';
3010 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3011 # We're not going to implement it for RT_External.
3012 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3013 my $new_value = $values->{$id};
3014 next if $old_value eq $new_value;
3016 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3018 # AddCustomFieldValue works fine (replacing any existing value) if it's
3019 # a single-valued custom field, which it should be. If it's not, you're
3020 # doing something wrong.
3022 if ( length($new_value) ) {
3023 ($val, $msg) = $Ticket->AddCustomFieldValue(
3024 Field => $ss_priority,
3025 Value => $new_value,
3029 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3030 Field => $ss_priority,
3031 Value => $old_value,
3035 $ticket_error{$id} = $msg if !$val;
3036 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3038 return { 'error' => '',
3039 'ticket_error' => \%ticket_error,
3040 %{ customer_info($p) } # send updated customer info back
3046 sub _custoragent_session_custnum {
3049 my($context, $session, $custnum);
3050 if ( $p->{'session_id'} ) {
3052 $context = 'customer';
3053 $session = _cache->get($p->{'session_id'})
3054 or return ( 'error' => "Can't resume session" ); #better error message
3055 $custnum = $session->{'custnum'};
3057 } elsif ( $p->{'agent_session_id'} ) {
3060 my $agent_cache = new FS::ClientAPI_SessionCache( {
3061 'namespace' => 'FS::ClientAPI::Agent',
3063 $session = $agent_cache->get($p->{'agent_session_id'})
3064 or return ( 'error' => "Can't resume session" ); #better error message
3065 $custnum = $p->{'custnum'};
3069 return ( 'error' => "Can't resume session" ); #better error message
3072 ($context, $session, $custnum);