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;
44 use FS::acct_rt_transaction;
48 $me = '[FS::ClientAPI::MyAccount]';
50 use vars qw( @cust_main_editable_fields @location_editable_fields );
51 @cust_main_editable_fields = qw(
52 first last daytime night fax mobile
54 payby payinfo payname paystart_month paystart_year payissue payip
55 ss paytype paystate stateid stateid_state
57 @location_editable_fields = qw(
58 address1 address2 city county state zip country
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'});
199 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
200 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
202 my $svc_acct = qsearchs( 'svc_acct', { 'username' => $p->{'username'},
203 'domsvc' => $svc_domain->svcnum, }
205 return { error => 'User not found.' } unless $svc_acct;
207 if($conf->exists('selfservice_server-login_svcpart')) {
208 my @svcpart = $conf->config('selfservice_server-login_svcpart');
209 my $svcpart = $svc_acct->cust_svc->svcpart;
210 return { error => 'Invalid user.' }
211 unless grep($_ eq $svcpart, @svcpart);
214 return { error => 'Incorrect password.' }
215 unless $svc_acct->check_password($p->{'password'});
222 'svcnum' => $svc_x->svcnum,
225 my $cust_svc = $svc_x->cust_svc;
226 my $cust_pkg = $cust_svc->cust_pkg;
228 my $cust_main = $cust_pkg->cust_main;
229 $session->{'custnum'} = $cust_main->custnum;
230 if ( $conf->exists('pkg-balances') ) {
231 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
232 $cust_main->ncancelled_pkgs;
233 $session->{'pkgnum'} = $cust_pkg->pkgnum
234 if scalar(@cust_pkg) > 1;
238 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
239 #return { error => 'Only primary user may log in.' }
240 # if $conf->exists('selfservice_server-primary_only')
241 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
242 my $part_pkg = $cust_pkg->part_pkg;
243 return { error => 'Only primary user may log in.' }
244 if $conf->exists('selfservice_server-primary_only')
245 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
249 $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
250 } until ( ! defined _cache->get($session_id) ); #just in case
252 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
253 _cache->set( $session_id, $session, $timeout );
255 return { 'error' => '',
256 'session_id' => $session_id,
262 if ( $p->{'session_id'} ) {
263 _cache->remove($p->{'session_id'});
264 return { %{ skin_info($p) }, 'error' => '' };
266 return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
273 my($context, $session, $custnum) = _custoragent_session_custnum($p);
274 return { 'error' => $session } if $context eq 'error';
276 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
277 or return { 'error' => "Service not found" };
279 $session->{'svcnum'} = $svc_acct->svcnum;
281 my $conf = new FS::Conf;
282 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
283 _cache->set( $p->{'session_id'}, $session, $timeout );
285 return { 'error' => '' };
289 sub payment_gateway {
291 # takes a cust_main and a cust_payby entry, returns the payment_gateway
292 my $conf = new FS::Conf;
293 my $cust_main = shift;
294 my $cust_payby = shift;
295 my $gatewaynum = $conf->config('selfservice-payment_gateway');
297 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
298 die "configured gatewaynum $gatewaynum not found!" if !$pg;
302 return '' if ! FS::payby->realtime($cust_payby);
303 my $pg = $cust_main->agent->payment_gateway(
304 'method' => FS::payby->payby2bop($cust_payby),
314 my $conf = new FS::Conf;
316 my $info = skin_info($p);
318 use vars qw( $cust_paybys ); #cache for performance
319 unless ( $cust_paybys ) {
321 my %cust_paybys = map { $_ => 1 }
322 map { FS::payby->payby2payment($_) }
323 $conf->config('signup_server-payby');
325 $cust_paybys = [ keys %cust_paybys ];
328 $info->{'cust_paybys'} = $cust_paybys;
330 my($context, $session, $custnum) = _custoragent_session_custnum($p);
331 return { 'error' => $session } if $context eq 'error';
333 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
334 or return { 'error' => "unknown custnum $custnum" };
336 $info->{'hide_payment_fields'} = [
338 my $pg = payment_gateway($cust_main, $_);
339 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
340 } @{ $info->{cust_paybys} }
343 $info->{'self_suspend_reason'} =
344 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
346 $info->{'edit_ticket_subject'} =
347 $conf->exists('ticket_system-selfservice_edit_subject') &&
348 $cust_main->edit_subject;
351 'custnum' => $custnum,
352 'access_pkgnum' => $session->{'pkgnum'},
353 'access_svcnum' => $session->{'svcnum'},
360 my($context, $session, $custnum) = _custoragent_session_custnum($p);
361 return { 'error' => $session } if $context eq 'error';
365 my $conf = new FS::Conf;
366 if ($conf->exists('cust_main-require_address2')) {
367 $return{'require_address2'} = '1';
369 $return{'require_address2'} = '';
372 if ( $FS::TicketSystem::system ) {
373 warn "$me customer_info: initializing ticket system\n" if $DEBUG;
374 FS::TicketSystem->init();
377 if ( $custnum ) { #customer record
379 my $search = { 'custnum' => $custnum };
380 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
381 my $cust_main = qsearchs('cust_main', $search )
382 or return { 'error' => "unknown custnum $custnum" };
384 $return{display_custnum} = $cust_main->display_custnum;
386 if ( $session->{'pkgnum'} ) {
387 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
388 #next_bill_date from cust_pkg?
390 $return{balance} = $cust_main->balance;
391 $return{next_bill_date} = $cust_main->next_bill_date;
392 $return{next_bill_date_pretty} =
393 time2str('%m/%d/%Y', $return{next_bill_date} );
396 my @tickets = $cust_main->tickets;
397 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
398 if ( FS::TicketSystem->selfservice_priority ) {
399 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
403 ($a->{'_selfservice_priority'} eq '') <=>
404 ($b->{'_selfservice_priority'} eq '')
407 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
413 $return{tickets} = \@tickets;
416 unless ( $session->{'pkgnum'} ) {
419 invnum => $_->invnum,
420 date => time2str("%b %o, %Y", $_->_date),
423 } $cust_main->open_cust_bill;
424 $return{open_invoices} = \@open;
426 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
427 my $sth = dbh->prepare($sql) or die dbh->errstr;
428 $sth->execute($custnum) or die $sth->errstr;
429 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
430 $return{'last_invoice_date_pretty'} =
431 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
434 $return{countrydefault} = scalar($conf->config('countrydefault'));
436 $return{small_custview} =
437 small_custview( $cust_main,
438 $return{countrydefault},
439 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
442 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
444 $return{has_ship_address} = $cust_main->has_ship_address;
445 $return{status} = $cust_main->status;
446 $return{statuscolor} = $cust_main->statuscolor;
448 for (@cust_main_editable_fields) {
449 $return{$_} = $cust_main->get($_);
452 for (@location_editable_fields) {
453 $return{$_} = $cust_main->bill_location->get($_);
454 $return{'ship_'.$_} = $cust_main->ship_location->get($_);
456 $return{has_ship_address} = $cust_main->has_ship_address;
457 # compatibility: some places in selfservice use this to determine
458 # if there's a ship address
459 if ( $return{has_ship_address} ) {
460 $return{ship_last} = $cust_main->last;
461 $return{ship_first} = $cust_main->first;
464 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
465 $return{payinfo} = $cust_main->paymask;
466 @return{'month', 'year'} = $cust_main->paydate_monthyear;
469 $return{'invoicing_list'} =
470 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
471 $return{'postal_invoicing'} =
472 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
474 if (scalar($conf->config('support_packages'))) {
475 my @support_services = ();
476 foreach ($cust_main->support_services) {
477 my $seconds = $_->svc_x->seconds || 0;
478 my $time_remaining = (($seconds < 0) ? '-' : '' ).
479 int(abs($seconds)/3600)."h".
480 sprintf("%02d",(abs($seconds)%3600)/60)."m";
481 my $cust_pkg = $_->cust_pkg;
484 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
485 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
486 push @support_services, { svcnum => $_->svcnum,
487 time => $time_remaining,
492 $return{support_services} = \@support_services;
495 if ( $conf->config('prepayment_discounts-credit_type') ) {
497 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
500 if ( $session->{'svcnum'} ) {
501 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
502 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
503 $return{'svcnum'} = $session->{'svcnum'};
506 } elsif ( $session->{'svcnum'} ) { #no customer record
508 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
509 or die "unknown svcnum";
510 $return{name} = $svc_acct->email;
514 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
518 return { 'error' => '',
519 'custnum' => $custnum,
525 sub customer_info_short {
528 my($context, $session, $custnum) = _custoragent_session_custnum($p);
529 return { 'error' => $session } if $context eq 'error';
533 my $conf = new FS::Conf;
535 if ( $custnum ) { #customer record
537 my $search = { 'custnum' => $custnum };
538 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
539 my $cust_main = qsearchs('cust_main', $search )
540 or return { 'error' => "unknown custnum $custnum" };
542 $return{display_custnum} = $cust_main->display_custnum;
544 $return{countrydefault} = scalar($conf->config('countrydefault'));
546 $return{small_custview} =
547 small_custview( $cust_main,
548 $return{countrydefault},
552 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
554 $return{payby} = $cust_main->payby;
556 #none of these are terribly expensive if we want 'em...
557 for (@cust_main_editable_fields) {
558 $return{$_} = $cust_main->get($_);
560 #maybe a little more expensive, but it should be cached by now
561 for (@location_editable_fields) {
562 $return{$_} = $cust_main->bill_location->get($_);
563 $return{'ship_'.$_} = $cust_main->ship_location->get($_);
566 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
567 $return{payinfo} = $cust_main->paymask;
568 @return{'month', 'year'} = $cust_main->paydate_monthyear;
571 $return{'invoicing_list'} =
572 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
573 #$return{'postal_invoicing'} =
574 # 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
576 if ( $session->{'svcnum'} ) {
577 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
578 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
579 $return{'svcnum'} = $session->{'svcnum'};
582 } elsif ( $session->{'svcnum'} ) { #no customer record
584 #uuh, not supproted yet... die?
585 return { 'error' => 'customer_info_short not yet supported as agent' };
589 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
593 return { 'error' => '',
594 'custnum' => $custnum,
599 sub billing_history {
602 my($context, $session, $custnum) = _custoragent_session_custnum($p);
603 return { 'error' => $session } if $context eq 'error';
605 return { 'error' => 'No customer' } unless $custnum;
607 my $search = { 'custnum' => $custnum };
608 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
609 my $cust_main = qsearchs('cust_main', $search )
610 or return { 'error' => "unknown custnum $custnum" };
614 if ( $session->{'pkgnum'} ) {
615 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
616 #next_bill_date from cust_pkg?
617 return { 'error' => 'No history for package' };
620 $return{balance} = $cust_main->balance;
621 $return{next_bill_date} = $cust_main->next_bill_date;
622 $return{next_bill_date_pretty} =
623 time2str('%m/%d/%Y', $return{next_bill_date} );
627 my $conf = new FS::Conf;
629 if ( $conf->exists('selfservice-billing_history-line_items') ) {
631 foreach my $cust_bill ( $cust_main->cust_bill ) {
634 'type' => 'Line item',
635 'description' => $_->desc. ( $_->sdate && $_->edate
636 ? ' '. time2str('%d-%b-%Y', $_->sdate).
637 ' To '. time2str('%d-%b-%Y', $_->edate)
640 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
641 'date' => $cust_bill->_date,
642 'date_pretty' => time2str('%m/%d/%Y', $cust_bill->_date ),
644 foreach $cust_bill->cust_bill_pkg;
652 'description' => 'Invoice #'. $_->display_invnum,
653 'amount' => sprintf('%.2f', $_->charged ),
655 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
657 foreach $cust_main->cust_bill;
663 'description' => 'Payment', #XXX type
664 'amount' => sprintf('%.2f', 0 - $_->paid ),
666 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
668 foreach $cust_main->cust_pay;
672 'description' => 'Credit', #more info?
673 'amount' => sprintf('%.2f', 0 -$_->amount ),
675 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
677 foreach $cust_main->cust_credit;
681 'description' => 'Refund', #more info? type, like payment?
682 'amount' => $_->refund,
684 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
686 foreach $cust_main->cust_refund;
688 @history = sort { $b->{'date'} <=> $a->{'date'} } @history;
690 $return{'history'} = \@history;
698 my $session = _cache->get($p->{'session_id'})
699 or return { 'error' => "Can't resume session" }; #better error message
701 my $custnum = $session->{'custnum'}
702 or return { 'error' => "no customer record" };
704 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
705 or return { 'error' => "unknown custnum $custnum" };
707 my $new = new FS::cust_main { $cust_main->hash };
709 $new->set( $_ => $p->{$_} )
710 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
712 if ( exists($p->{address1}) ) {
713 my $bill_location = FS::cust_location->new({
714 map { $_ => $p->{$_} } @location_editable_fields
716 # if this is unchanged from before, cust_main::replace will ignore it
717 $new->set('bill_location' => $bill_location);
720 if ( exists($p->{ship_address1}) ) {
721 my $ship_location = FS::cust_location->new({
722 map { $_ => $p->{"ship_$_"} } @location_editable_fields
724 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
725 # Selfservice unfortunately tries to indicate "same as billing
726 # address" by sending all fields empty. Did this ever work?
727 $ship_location = $cust_main->bill_location;
729 $new->set('ship_location' => $ship_location);
731 # but if it hasn't been passed in at all, leave ship_location alone--
732 # DON'T change it to match bill_location.
735 if (exists($p->{'payby'})) {
736 $p->{'payby'} =~ /^([A-Z]{4})$/
737 or return { 'error' => "illegal_payby " . $p->{'payby'} };
741 if ( $payby =~ /^(CARD|DCRD)$/ ) {
743 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
745 if ( $new->payinfo eq $cust_main->paymask ) {
746 $new->payinfo($cust_main->payinfo);
748 $new->payinfo($p->{'payinfo'});
751 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
753 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
756 $p->{'payinfo1'} =~ /^([\dx]+)$/
757 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
759 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
760 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
762 $payinfo = $payinfo1. '@'. $payinfo2;
764 $new->payinfo( ($payinfo eq $cust_main->paymask)
765 ? $cust_main->payinfo
769 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
771 } elsif ( $payby =~ /^(BILL)$/ ) {
773 } elsif ( $payby ) { #notyet ready
774 return { 'error' => "unknown payby $payby" };
778 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
779 #false laziness with httemplate/edit/process/cust_main.cgi
780 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
781 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
783 @invoicing_list = $cust_main->invoicing_list;
786 my $error = $new->replace($cust_main, \@invoicing_list);
787 return { 'error' => $error } if $error;
790 return { 'error' => '' };
795 my $session = _cache->get($p->{'session_id'})
796 or return { 'error' => "Can't resume session" }; #better error message
802 my $conf = new FS::Conf;
803 use vars qw($payment_info); #cache for performance
804 unless ( $payment_info ) {
806 my %states = map { $_->state => 1 }
807 qsearch('cust_main_county', {
808 'country' => $conf->config('countrydefault') || 'US'
811 my %cust_paybys = map { $_ => 1 }
812 map { FS::payby->payby2payment($_) }
813 $conf->config('signup_server-payby');
815 my @cust_paybys = keys %cust_paybys;
819 #list all counties/states/countries
820 'cust_main_county' =>
821 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
823 #shortcut for one-country folks
825 [ sort { $a cmp $b } keys %states ],
827 'card_types' => card_types(),
829 'paytypes' => [ @FS::cust_main::paytypes ],
831 'paybys' => [ $conf->config('signup_server-payby') ],
832 'cust_paybys' => \@cust_paybys,
834 'stateid_label' => FS::Msgcat::_gettext('stateid'),
835 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
837 'show_ss' => $conf->exists('show_ss'),
838 'show_stateid' => $conf->exists('show_stateid'),
839 'show_paystate' => $conf->exists('show_bankstate'),
841 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
843 'credit_card_surcharge_percentage' => $conf->config('credit-card-surcharge-percentage'),
852 my %return = %$payment_info;
854 my $custnum = $session->{'custnum'};
856 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
857 or return { 'error' => "unknown custnum $custnum" };
859 $return{'hide_payment_fields'} = [
861 my $pg = payment_gateway($cust_main, $_);
862 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
863 } @{ $return{cust_paybys} }
866 $return{balance} = $cust_main->balance; #XXX pkg-balances?
868 $return{payname} = $cust_main->payname
869 || ( $cust_main->first. ' '. $cust_main->get('last') );
871 $return{$_} = $cust_main->bill_location->get($_)
872 for qw(address1 address2 city state zip);
874 $return{payby} = $cust_main->payby;
875 $return{stateid_state} = $cust_main->stateid_state;
877 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
878 $return{card_type} = cardtype($cust_main->payinfo);
879 $return{payinfo} = $cust_main->paymask;
881 @return{'month', 'year'} = $cust_main->paydate_monthyear;
885 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
886 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
887 $return{payinfo1} = $payinfo1;
888 $return{payinfo2} = $payinfo2;
889 $return{paytype} = $cust_main->paytype;
890 $return{paystate} = $cust_main->paystate;
891 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
894 if ( $conf->config('prepayment_discounts-credit_type') ) {
896 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
899 #doubleclick protection
901 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
903 return { 'error' => '',
909 #some false laziness with httemplate/process/payment.cgi - look there for
910 #ACH and CVV support stuff
912 sub validate_payment {
915 my $session = _cache->get($p->{'session_id'})
916 or return { 'error' => "Can't resume session" }; #better error message
918 my $custnum = $session->{'custnum'};
920 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
921 or return { 'error' => "unknown custnum $custnum" };
923 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
924 or return { 'error' => gettext('illegal_amount') };
926 return { error => 'Amount must be greater than 0' } unless $amount > 0;
928 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
929 #changing the hidden form values
930 my $conf = new FS::Conf;
931 my $fee_display = $conf->config('selfservice_process-display') || 'add';
932 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart');
933 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
934 if ( $fee_display eq 'add'
936 and ! $fee_skip_first || scalar($cust_main->cust_pay)
939 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
940 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
943 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
944 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
945 my $discount_term = $1;
947 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
948 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
951 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
952 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
955 $p->{'payby'} ||= 'CARD';
956 $p->{'payby'} =~ /^([A-Z]{4})$/
957 or return { 'error' => "illegal_payby " . $p->{'payby'} };
960 #false laziness w/process/payment.cgi
963 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
965 $p->{'payinfo1'} =~ /^([\dx]+)$/
966 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
968 $p->{'payinfo2'} =~ /^([\dx]+)$/
969 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
971 $payinfo = $payinfo1. '@'. $payinfo2;
973 $payinfo = $cust_main->payinfo
974 if $cust_main->paymask eq $payinfo;
976 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
978 $payinfo = $p->{'payinfo'};
980 #more intelligent matching will be needed here if you change
981 #card_masking_method and don't remove existing paymasks
982 $payinfo = $cust_main->payinfo
983 if $cust_main->paymask eq $payinfo;
986 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
987 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
991 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
992 return { 'error' => gettext('unknown_card_type') }
993 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
995 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
996 if ( cardtype($payinfo) eq 'American Express card' ) {
997 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
998 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1001 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1002 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1008 die "unknown payby $payby";
1011 my %payby2fields = (
1012 'CARD' => [ qw( paystart_month paystart_year payissue payip
1013 address1 address2 city state zip country ) ],
1014 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1018 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1021 'cust_main' => $cust_main, #XXX or just custnum??
1022 'amount' => $amount,
1024 'payinfo' => $payinfo,
1025 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1026 'card_type' => $card_type,
1027 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1028 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1029 'month' => $p->{'month'},
1030 'year' => $p->{'year'},
1031 'payname' => $payname,
1032 'paybatch' => $paybatch, #this doesn't actually do anything
1033 'paycvv' => $paycvv,
1034 'payname' => $payname,
1035 'discount_term' => $discount_term,
1036 'pkgnum' => $session->{'pkgnum'},
1037 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1047 my $validate = validate_payment($p);
1048 return $validate if $validate->{'error'};
1050 my $conf = new FS::Conf;
1051 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1052 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1054 +{ map { $_=>$validate->{$_} }
1055 qw( card_type paymask payname paydate_pretty month year amount
1056 address1 address2 city state zip country
1062 sub process_stored_payment {
1065 my $session_id = $p->{'session_id'};
1067 my $payment_info = _cache->get( "payment_$session_id" )
1068 or return { 'error' => "Can't resume session" }; #better error message
1070 do_process_payment($payment_info);
1074 sub process_payment {
1077 my $payment_info = validate_payment($p);
1078 return $payment_info if $payment_info->{'error'};
1080 do_process_payment($payment_info);
1084 sub do_process_payment {
1085 my $validate = shift;
1087 my $cust_main = $validate->{'cust_main'};
1089 my $amount = delete $validate->{'amount'};
1092 my $payby = delete $validate->{'payby'};
1094 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1097 'paynum_ref' => \$paynum,
1100 return { 'error' => $error } if $error;
1102 #no error, so order the fee package if applicable...
1103 my $conf = new FS::Conf;
1104 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart');
1105 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1107 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1109 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1111 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1112 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1115 #and generate an invoice for it now too
1116 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1117 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1122 $cust_main->apply_payments;
1124 if ( $validate->{'save'} ) {
1125 my $new = new FS::cust_main { $cust_main->hash };
1126 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1127 $new->set( $_ => $validate->{$_} )
1128 foreach qw( payname paystart_month paystart_year payissue payip );
1129 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1131 my $bill_location = FS::cust_location->new({
1132 map { $_ => $validate->{$_} }
1133 qw(address1 address2 city state country zip)
1135 $new->set('bill_location' => $bill_location);
1136 # but don't allow the service address to change this way.
1138 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1139 $new->set( $_ => $validate->{$_} )
1140 foreach qw( payname payip paytype paystate
1141 stateid stateid_state );
1142 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1144 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1145 $new->set( 'paydate' => $validate->{'paydate'} );
1146 my $error = $new->replace($cust_main);
1148 #no, this causes customers to process their payments again
1149 #return { 'error' => $error };
1150 #XXX just warn verosely for now so i can figure out how these happen in
1151 # the first place, eventually should redirect them to the "change
1152 #address" page but indicate the payment did process??
1153 delete($validate->{'payinfo'}); #don't want to log this!
1154 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1155 "NEW: ". Dumper($new)."\n".
1156 "OLD: ". Dumper($cust_main)."\n".
1157 "PACKET: ". Dumper($validate)."\n";
1165 my $receipt_html = '';
1167 # currently supported for realtime CC only; send receipt data to SS
1168 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1171 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1174 <TD ALIGN="right">Payment#</TD>
1175 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1179 <TD ALIGN="right">Date</TD>
1181 <TD BGCOLOR="#FFFFFF"><B>! .
1182 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1188 <TD ALIGN="right">Amount</TD>
1189 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1194 <TD ALIGN="right">Payment method</TD>
1195 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1206 my($gw, $auth, $order) = split(':', $cust_pay->paybatch);
1210 'amount' => sprintf('%.2f', $cust_pay->paid),
1211 'date' => $cust_pay->_date,
1212 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1213 'time_pretty' => time2str('%T', $cust_pay->_date),
1214 'auth_num' => $auth,
1215 'order_num' => $order,
1216 'receipt_html' => $receipt_html,
1223 'receipt_html' => '',
1230 sub realtime_collect {
1233 my $session = _cache->get($p->{'session_id'})
1234 or return { 'error' => "Can't resume session" }; #better error message
1236 my $custnum = $session->{'custnum'};
1238 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1239 or return { 'error' => "unknown custnum $custnum" };
1242 if ( $p->{'amount'} ) {
1243 $amount = $p->{'amount'};
1245 elsif ( $session->{'pkgnum'} ) {
1246 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1249 $amount = $cust_main->balance;
1252 my $error = $cust_main->realtime_collect(
1253 'method' => $p->{'method'},
1254 'amount' => $amount,
1255 'pkgnum' => $session->{'pkgnum'},
1256 'session_id' => $p->{'session_id'},
1260 return { 'error' => $error } unless ref( $error );
1262 return { 'error' => '', amount => $amount, %$error };
1265 sub process_payment_order_pkg {
1268 my $hr = process_payment($p);
1269 return $hr if $hr->{'error'};
1274 sub process_payment_order_renew {
1277 my $hr = process_payment($p);
1278 return $hr if $hr->{'error'};
1283 sub process_prepay {
1287 my $session = _cache->get($p->{'session_id'})
1288 or return { 'error' => "Can't resume session" }; #better error message
1292 my $custnum = $session->{'custnum'};
1294 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1295 or return { 'error' => "unknown custnum $custnum" };
1297 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1298 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1306 return { 'error' => $error } if $error;
1308 return { 'error' => '',
1309 'amount' => $amount,
1310 'seconds' => $seconds,
1311 'duration' => duration_exact($seconds),
1312 'upbytes' => $upbytes,
1313 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1314 'downbytes' => $downbytes,
1315 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1316 'totalbytes'=> $totalbytes,
1317 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1324 my $session = _cache->get($p->{'session_id'})
1325 or return { 'error' => "Can't resume session" }; #better error message
1327 my $custnum = $session->{'custnum'};
1329 my $invnum = $p->{'invnum'};
1331 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1332 'custnum' => $custnum } )
1333 or return { 'error' => "Can't find invnum" };
1337 return { 'error' => '',
1338 'invnum' => $invnum,
1339 'invoice_text' => join('', $cust_bill->print_text ),
1340 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1347 my $session = _cache->get($p->{'session_id'})
1348 or return { 'error' => "Can't resume session" }; #better error message
1350 my $custnum = $session->{'custnum'};
1352 my $invnum = $p->{'invnum'};
1354 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1355 'custnum' => $custnum } )
1356 or return { 'error' => "Can't find invnum" };
1360 return { 'error' => '',
1361 'invnum' => $invnum,
1362 'invoice_pdf' => $cust_bill->print_pdf({
1363 'unsquelch_cdr' => 1,
1364 'locale' => $p->{'locale'},
1370 sub legacy_invoice {
1372 my $session = _cache->get($p->{'session_id'})
1373 or return { 'error' => "Can't resume session" }; #better error message
1375 my $custnum = $session->{'custnum'};
1377 my $legacyinvnum = $p->{'legacyinvnum'};
1380 'legacyinvnum' => $legacyinvnum,
1381 'custnum' => $custnum,
1384 my $legacy_cust_bill =
1385 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1386 || qsearchs('legacy_cust_bill', \%hash )
1387 or return { 'error' => "Can't find legacyinvnum" };
1391 return { 'error' => '',
1392 'legacyinvnum' => $legacyinvnum,
1393 'legacyid' => $legacy_cust_bill->legacyid,
1394 'invoice_html' => $legacy_cust_bill->content_html,
1399 sub legacy_invoice_pdf {
1401 my $session = _cache->get($p->{'session_id'})
1402 or return { 'error' => "Can't resume session" }; #better error message
1404 my $custnum = $session->{'custnum'};
1406 my $legacyinvnum = $p->{'legacyinvnum'};
1408 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1409 'legacyinvnum' => $legacyinvnum,
1410 'custnum' => $custnum,
1411 }) or return { 'error' => "Can't find legacyinvnum" };
1415 return { 'error' => '',
1416 'legacyinvnum' => $legacyinvnum,
1417 'legacyid' => $legacy_cust_bill->legacyid,
1418 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1426 #sessioning for this? how do we get the session id to the backend invoice
1427 # template so it can add it to the link, blah
1430 if ( $p->{'invnum'} ) {
1431 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1432 or return { 'error' => 'unknown invnum' };
1433 $agentnum = $cust_bill->cust_main->agentnum;
1436 my $templatename = $p->{'template'} || $p->{'templatename'};
1438 #false laziness-ish w/view/cust_bill-logo.cgi
1440 my $conf = new FS::Conf;
1441 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1442 $templatename = "_$1";
1447 my $filename = "logo$templatename.png";
1449 return { 'error' => '',
1450 'logo' => $conf->config_binary($filename, $agentnum),
1451 'content_type' => 'image/png', #should allow gif, jpg too
1458 my $session = _cache->get($p->{'session_id'})
1459 or return { 'error' => "Can't resume session" }; #better error message
1461 my $custnum = $session->{'custnum'};
1463 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1464 or return { 'error' => "unknown custnum $custnum" };
1466 my $conf = new FS::Conf;
1468 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1470 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1474 return { 'error' => '',
1475 'balance' => $cust_main->balance,
1478 my $owed = $_->owed;
1480 +{ 'invnum' => $_->invnum,
1481 '_date' => $_->_date,
1482 'date' => time2str("%b %o, %Y", $_->_date),
1483 'date_short' => time2str("%m-%d-%Y", $_->_date),
1484 'previous' => sprintf('%.2f', ($_->previous)[0]),
1485 'charged' => sprintf('%.2f', $_->charged),
1486 'owed' => sprintf('%.2f', $owed),
1487 'balance' => sprintf('%.2f', $balance),
1492 'legacy_invoices' => [
1494 +{ 'legacyinvnum' => $_->legacyinvnum,
1495 'legacyid' => $_->legacyid,
1496 '_date' => $_->_date,
1497 'date' => time2str("%b %o, %Y", $_->_date),
1498 'date_short' => time2str("%m-%d-%Y", $_->_date),
1499 'charged' => sprintf('%.2f', $_->charged),
1500 'has_content' => ( length($_->content_pdf)
1501 || length($_->content_html) ),
1511 my $session = _cache->get($p->{'session_id'})
1512 or return { 'error' => "Can't resume session" }; #better error message
1514 my $custnum = $session->{'custnum'};
1516 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1517 or return { 'error' => "unknown custnum $custnum" };
1519 my @errors = $cust_main->cancel( 'quiet'=>1 );
1521 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1523 return { 'error' => $error };
1530 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1531 return { 'error' => $session } if $context eq 'error';
1533 my $search = { 'custnum' => $custnum };
1534 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1535 my $cust_main = qsearchs('cust_main', $search )
1536 or return { 'error' => "unknown custnum $custnum" };
1538 my $conf = new FS::Conf;
1540 # the duplication below is necessary:
1541 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1542 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1543 # non-backwards-compatible change breaking the software of anyone using the API
1544 # instead of the stock selfservice
1545 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1546 if( $conf->exists('selfservice_server-view-wholesale') ) {
1547 return { 'svcnum' => $session->{'svcnum'},
1548 'custnum' => $custnum,
1549 'cust_pkg' => [ map {
1551 part_pkg => [ map $_->hashref, $_->part_pkg ],
1553 [ map $_->hashref, $_->available_part_svc ],
1555 [ map { my $ref = { $_->hash,
1556 label => [ $_->label ],
1558 $ref->{_password} = $_->svc_x->_password
1559 if $context eq 'agent'
1560 && $conf->exists('agent-showpasswords')
1561 && $_->part_svc->svcdb eq 'svc_acct';
1566 } $cust_main->cust_pkg
1569 small_custview( $cust_main, $conf->config('countrydefault') ),
1570 'wholesale_view' => 1,
1571 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1572 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1573 'lnp' => $conf->exists('svc_phone-lnp'),
1577 { 'svcnum' => $session->{'svcnum'},
1578 'custnum' => $custnum,
1579 'cust_pkg' => [ map {
1580 my $primary_cust_svc = $_->primary_cust_svc;
1583 pkg_label => $_->pkg_label,
1584 status => $_->status,
1586 [ map $_->hashref, $_->available_part_svc ],
1588 [ map { my $ref = { $_->hash,
1589 label => [ $_->label ],
1591 $ref->{_password} = $_->svc_x->_password
1592 if $context eq 'agent'
1593 && $conf->exists('agent-showpasswords')
1594 && $_->part_svc->svcdb eq 'svc_acct';
1595 $ref->{svchash} = { $_->svc_x->hash } if
1596 $_->part_svc->svcdb eq 'svc_phone';
1597 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1598 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1604 ? { $primary_cust_svc->hash,
1605 label => [ $primary_cust_svc->label ],
1606 finger => $primary_cust_svc->svc_x->finger, #uuh
1607 $primary_cust_svc->part_svc->hash,
1611 } $cust_main->ncancelled_pkgs
1614 small_custview( $cust_main, $conf->config('countrydefault') ),
1622 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1623 return { 'error' => $session } if $context eq 'error';
1625 my $search = { 'custnum' => $custnum };
1626 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1627 my $cust_main = qsearchs('cust_main', $search )
1628 or return { 'error' => "unknown custnum $custnum" };
1630 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1631 if ( ! $pkgnum && $p->{'svcnum'} ) {
1632 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1633 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1637 #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1638 foreach my $cust_pkg ( $p->{'ncancelled'}
1639 ? $cust_main->ncancelled_pkgs
1640 : $cust_main->unsuspended_pkgs ) {
1641 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1642 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1645 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1647 if ( $p->{'svcdb'} ) {
1648 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1650 : ref($p->{'svcdb'}) eq 'ARRAY'
1651 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1652 : { $p->{'svcdb'} => 1 };
1653 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1656 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1659 my $conf = new FS::Conf;
1662 'svcnum' => $session->{'svcnum'},
1663 'custnum' => $custnum,
1664 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1665 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1668 my $svc_x = $_->svc_x;
1669 my($label, $value) = $_->label;
1670 my $part_svc = $_->part_svc;
1671 my $svcdb = $part_svc->svcdb;
1672 my $cust_pkg = $_->cust_pkg;
1673 my $part_pkg = $cust_pkg->part_pkg;
1676 'svcnum' => $_->svcnum,
1677 'display_svcnum' => $_->display_svcnum,
1681 'pkg_label' => $cust_pkg->pkg_label,
1682 'pkg_status' => $cust_pkg->status,
1683 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1686 if ( $svcdb eq 'svc_acct' ) {
1689 'username' => $svc_x->username,
1690 'email' => $svc_x->email,
1691 'finger' => $svc_x->finger,
1692 'seconds' => $svc_x->seconds,
1693 'upbytes' => display_bytecount($svc_x->upbytes),
1694 'downbytes' => display_bytecount($svc_x->downbytes),
1695 'totalbytes' => display_bytecount($svc_x->totalbytes),
1697 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1698 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1699 'recharge_upbytes' =>
1700 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1701 'recharge_downbytes' =>
1702 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1703 'recharge_totalbytes' =>
1704 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1708 } elsif ( $svcdb eq 'svc_dsl' ) {
1709 $hash{'phonenum'} = $svc_x->phonenum;
1710 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1711 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1712 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1715 $hash{'name'} = $cust_main->name;
1718 # elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1732 sub _customer_svc_x {
1733 my($custnum, $svcnum, $table) = (shift, shift, shift);
1734 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1736 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1737 my $search = " AND custnum = $1";
1738 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1741 'table' => ($table || 'svc_acct'),
1742 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1743 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1744 #'LEFT JOIN cust_main USING ( custnum ) ',
1745 'hashref' => $hashref,
1746 'extra_sql' => $search, #important
1751 sub svc_status_html {
1754 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1755 return { 'error' => $session } if $context eq 'error';
1757 #XXX only svc_dsl for now
1758 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1759 or return { 'error' => "Service not found" };
1761 my $html = $svc_x->getstatus_html;
1763 return { 'html' => $html };
1767 sub svc_status_hash {
1770 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1771 return { 'error' => $session } if $context eq 'error';
1773 #XXX only svc_acct for now
1774 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1775 or return { 'error' => "Service not found" };
1777 my ( $html, $hashref ) = $svc_x->export_getstatus;
1782 sub set_svc_status_hash {
1785 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1786 return { 'error' => $session } if $context eq 'error';
1788 #XXX only svc_acct for now
1789 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1790 or return { 'error' => "Service not found" };
1792 warn "set_svc_status_hash ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1794 my $error = $svc_x->export_setstatus($p); #$p? returns error?
1795 return { 'error' => $error } if $error;
1797 return {}; #? { 'error' => '' }
1802 sub acct_forward_info {
1805 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1806 return { 'error' => $session } if $context eq 'error';
1808 my $svc_forward = _customer_svc_x( $custnum,
1809 { 'srcsvc' => $p->{'svcnum'} },
1812 or return { 'error' => '',
1816 return { 'error' => '',
1817 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
1822 sub process_acct_forward {
1824 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1825 return { 'error' => $session } if $context eq 'error';
1827 my $old = _customer_svc_x( $custnum,
1828 { 'srcsvc' => $p->{'svcnum'} },
1832 if ( $p->{'dst'} eq '' ) {
1834 my $error = $old->delete;
1835 return { 'error' => $error };
1837 return { 'error' => '' };
1840 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
1841 'dst' => $p->{'dst'},
1846 $new->svcnum($old->svcnum);
1847 my $cust_svc = $old->cust_svc;
1848 $new->svcpart($old->svcpart);
1849 $new->pkgnuym($old->pkgnum);
1850 $error = $new->replace($old);
1852 my $conf = new FS::Conf;
1853 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
1855 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
1856 or return { 'error' => 'No service' }; #how would we even get here?
1858 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
1860 $error = $new->insert;
1863 return { 'error' => $error };
1867 sub list_dsl_devices {
1870 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1871 return { 'error' => $session } if $context eq 'error';
1873 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1874 or return { 'error' => "Service not found" };
1877 'devices' => [ map {
1878 +{ 'mac_addr' => $_->mac_addr };
1879 } $svc_dsl->dsl_device
1885 sub add_dsl_device {
1888 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1889 return { 'error' => $session } if $context eq 'error';
1891 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1892 or return { 'error' => "Service not found" };
1894 return { 'error' => 'No MAC address supplied' }
1895 unless length($p->{'mac_addr'});
1897 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
1898 'mac_addr' => scalar($p->{'mac_addr'}),
1900 my $error = $dsl_device->insert;
1901 return { 'error' => $error };
1905 sub delete_dsl_device {
1908 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1909 return { 'error' => $session } if $context eq 'error';
1911 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1912 or return { 'error' => "Service not found" };
1914 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
1915 'mac_addr' => scalar($p->{'mac_addr'}),
1918 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
1920 my $error = $dsl_device->delete;
1921 return { 'error' => $error };
1927 _usage_details( \&_port_graph, $p,
1928 'svcdb' => 'svc_port',
1933 my($svc_port, $begin, $end) = @_;
1935 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
1936 push @usage, { 'png' => $pngOrError };
1940 sub _list_svc_usage {
1941 my($svc_acct, $begin, $end) = @_;
1943 foreach my $part_export (
1944 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1945 qw( sqlradius sqlradius_withdomain )
1947 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1952 sub list_svc_usage {
1953 _usage_details(\&_list_svc_usage, @_);
1956 sub _list_support_usage {
1957 my($svc_acct, $begin, $end) = @_;
1959 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1960 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1962 push @usage, { 'seconds' => $_->seconds,
1963 'support' => $_->support,
1964 '_date' => $_->_date,
1965 'id' => $_->transaction_id,
1966 'creator' => $_->creator,
1967 'subject' => $_->subject,
1968 'status' => $_->status,
1969 'ticketid' => $_->ticketid,
1975 sub list_support_usage {
1976 _usage_details(\&_list_support_usage, @_);
1979 sub _list_cdr_usage {
1980 # XXX CDR type support...
1981 # XXX any way to do a paged search on this?
1982 # we have to return the results all at once...
1983 my($svc_phone, $begin, $end, %opt) = @_;
1984 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
1985 $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1988 sub list_cdr_usage {
1990 _usage_details( \&_list_cdr_usage, $p,
1991 'svcdb' => 'svc_phone',
1995 sub _usage_details {
1996 my($callback, $p, %opt) = @_;
1998 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1999 return { 'error' => $session } if $context eq 'error';
2001 my $search = { 'svcnum' => $p->{'svcnum'} };
2002 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2004 my $svcdb = $opt{'svcdb'} || 'svc_acct';
2006 my $svc_x = qsearchs( $svcdb, $search );
2007 return { 'error' => 'No service selected in list_svc_usage' }
2010 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
2011 my $freq = $cust_pkg->part_pkg->freq;
2014 if ( $svcdb eq 'svc_phone' ) {
2015 my $format = $cust_pkg->part_pkg->option('output_format') || '';
2016 $format = '' if $format =~ /^sum_/;
2017 # sensible default if there is no format or it's a summary format
2018 if ( $cust_pkg->part_pkg->plan eq 'voip_inbound' ) {
2019 $format ||= 'source_default';
2020 $callback_opt{inbound} = 1;
2023 $format ||= 'default';
2026 $callback_opt{format} = $format;
2027 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2030 my $start = $cust_pkg->setup;
2031 #my $end = $cust_pkg->bill; # or time?
2034 unless ( $p->{beginning} ) {
2035 $p->{beginning} = $cust_pkg->last_bill;
2036 $p->{ending} = $end;
2039 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2043 #kinda false laziness with FS::cust_main::bill, but perhaps
2044 #we should really change this bit to DateTime and DateTime::Duration
2046 #change this bit to use Date::Manip? CAREFUL with timezones (see
2047 # mailing list archive)
2048 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2049 (localtime($p->{ending}) )[0,1,2,3,4,5];
2050 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2051 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2053 if ( $freq =~ /^\d+$/ ) {
2055 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2057 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2058 } elsif ( $freq =~ /^(\d+)w$/ ) {
2060 $nmday += $weeks * 7;
2061 $pmday -= $weeks * 7;
2062 } elsif ( $freq =~ /^(\d+)d$/ ) {
2066 } elsif ( $freq =~ /^(\d+)h$/ ) {
2071 return { 'error' => "unparsable frequency: ". $freq };
2074 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2075 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2079 'svcnum' => $p->{svcnum},
2080 'beginning' => $p->{beginning},
2081 'ending' => $p->{ending},
2082 'previous' => ($previous > $start) ? $previous : $start,
2083 'next' => ($next < $end) ? $next : $end,
2084 'header' => $header,
2092 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2093 return { 'error' => $session } if $context eq 'error';
2095 my $search = { 'custnum' => $custnum };
2096 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2097 my $cust_main = qsearchs('cust_main', $search )
2098 or return { 'error' => "unknown custnum $custnum" };
2100 my $status = $cust_main->status;
2101 #false laziness w/ClientAPI/Signup.pm
2103 my $cust_pkg = new FS::cust_pkg ( {
2104 'custnum' => $custnum,
2105 'pkgpart' => $p->{'pkgpart'},
2107 my $error = $cust_pkg->check;
2108 return { 'error' => $error } if $error;
2111 unless ( $p->{'svcpart'} eq 'none' ) {
2115 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2117 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2118 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2119 $svcdb = $part_svc->svcdb;
2121 $svcdb = 'svc_acct';
2123 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2126 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2127 'svc_domain' => [ qw( domain ) ],
2128 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2129 'svc_external' => [ qw( id title ) ],
2130 'svc_pbx' => [ qw( id title ) ],
2133 my $svc_x = "FS::$svcdb"->new( {
2134 'svcpart' => $svcpart,
2135 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2138 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2141 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2142 my $acct_snarf = new FS::acct_snarf ( {
2143 'machine' => $p->{"snarf_machine$snarfnum"},
2144 'protocol' => $p->{"snarf_protocol$snarfnum"},
2145 'username' => $p->{"snarf_username$snarfnum"},
2146 '_password' => $p->{"snarf_password$snarfnum"},
2149 push @acct_snarf, $acct_snarf;
2151 $svc_x->child_objects( \@acct_snarf );
2154 my $y = $svc_x->setdefault; # arguably should be in new method
2155 return { 'error' => $y } if $y && !ref($y);
2157 $error = $svc_x->check;
2158 return { 'error' => $error } if $error;
2165 tie my %hash, 'Tie::RefHash';
2166 %hash = ( $cust_pkg => \@svc );
2168 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
2169 return { 'error' => $error } if $error;
2171 my $conf = new FS::Conf;
2172 if ( $conf->exists('signup_server-realtime') ) {
2174 my $bill_error = _do_bop_realtime( $cust_main, $status );
2177 $cust_pkg->cancel('quiet'=>1);
2180 $cust_pkg->reexport;
2184 $cust_pkg->reexport;
2187 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2189 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2196 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2197 return { 'error' => $session } if $context eq 'error';
2199 my $search = { 'custnum' => $custnum };
2200 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2201 my $cust_main = qsearchs('cust_main', $search )
2202 or return { 'error' => "unknown custnum $custnum" };
2204 my $status = $cust_main->status;
2205 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2206 or return { 'error' => "unknown package $p->{pkgnum}" };
2209 my $error = FS::cust_pkg::order( $custnum,
2215 my $conf = new FS::Conf;
2216 if ( $conf->exists('signup_server-realtime') ) {
2218 my $bill_error = _do_bop_realtime( $cust_main, $status );
2221 $newpkg[0]->suspend;
2224 $newpkg[0]->reexport;
2228 $newpkg[0]->reexport;
2231 return { error => '', pkgnum => $cust_pkg->pkgnum };
2235 sub order_recharge {
2238 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2239 return { 'error' => $session } if $context eq 'error';
2241 my $search = { 'custnum' => $custnum };
2242 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2243 my $cust_main = qsearchs('cust_main', $search )
2244 or return { 'error' => "unknown custnum $custnum" };
2246 my $status = $cust_main->status;
2247 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2248 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2250 my $svc_x = $cust_svc->svc_x;
2251 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2254 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2255 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2256 recharge_totalbytes );
2257 my $amount = $part_pkg->option('recharge_amount', 1);
2259 my ($l, $v, $d) = $cust_svc->label; # blah
2260 my $pkg = "Recharge $v";
2262 my $bill_error = $cust_main->charge($amount, $pkg,
2263 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2264 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2265 $part_pkg->taxclass); #meh
2267 my $conf = new FS::Conf;
2268 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2270 $bill_error = _do_bop_realtime( $cust_main, $status );
2275 my $error = $svc_x->recharge (\%vhash);
2276 return { 'error' => $error } if $error;
2280 my $error = $bill_error;
2281 $error ||= $svc_x->recharge (\%vhash);
2282 return { 'error' => $error } if $error;
2285 return { error => '', svc => $cust_svc->part_svc->svc };
2289 sub _do_bop_realtime {
2290 my ($cust_main, $status) = (shift, shift);
2292 my $old_balance = $cust_main->balance;
2294 my $bill_error = $cust_main->bill
2295 || $cust_main->apply_payments_and_credits
2296 || $cust_main->realtime_collect('selfservice' => 1);
2298 if ( $cust_main->balance > $old_balance
2299 && $cust_main->balance > 0
2300 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
2301 1 : $status eq 'suspended' ) ) {
2302 #this makes sense. credit is "un-doing" the invoice
2303 my $conf = new FS::Conf;
2304 $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
2305 'self-service decline',
2306 'reason_type' => $conf->config('signup_credit_type'),
2308 $cust_main->apply_credits( 'order' => 'newest' );
2310 return { 'error' => '_decline', 'bill_error' => $bill_error };
2319 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2320 return { 'error' => $session } if $context eq 'error';
2322 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2323 or return { 'error' => "unknown custnum $custnum" };
2325 my @cust_pkg = sort { $a->bill <=> $b->bill }
2326 grep { $_->part_pkg->freq ne '0' }
2327 $cust_main->ncancelled_pkgs;
2329 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2331 my $total = $cust_main->balance;
2334 my $bill = $_->bill;
2335 $total += $_->part_pkg->base_recur($_, \$bill);
2336 my $renew_date = $_->part_pkg->add_freq($_->bill);
2338 'pkgnum' => $_->pkgnum,
2339 'amount' => sprintf('%.2f', $total),
2340 'bill_date' => $_->bill,
2341 'bill_date_pretty' => time2str('%x', $_->bill),
2342 'renew_date' => $renew_date,
2343 'renew_date_pretty' => time2str('%x', $renew_date),
2344 'expire_date' => $_->expire,
2345 'expire_date_pretty' => time2str('%x', $_->expire),
2350 return { 'dates' => \@array };
2354 sub payment_info_renew_info {
2356 my $renew_info = renew_info($p);
2357 my $payment_info = payment_info($p);
2358 return { %$renew_info,
2366 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2367 return { 'error' => $session } if $context eq 'error';
2369 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2370 or return { 'error' => "unknown custnum $custnum" };
2372 my $date = $p->{'date'};
2376 #freeside-daily -n -d $date fs_daily $custnum
2377 $cust_main->bill_and_collect( 'time' => $date,
2378 'invoice_time' => $now,
2379 'actual_time' => $now,
2380 'check_freq' => '1d',
2383 return { 'error' => '' };
2389 my $session = _cache->get($p->{'session_id'})
2390 or return { 'error' => "Can't resume session" }; #better error message
2392 my $custnum = $session->{'custnum'};
2394 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2395 or return { 'error' => "unknown custnum $custnum" };
2397 my $conf = new FS::Conf;
2399 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2400 or return { 'error' => 'Permission denied' };
2402 my $pkgnum = $p->{'pkgnum'};
2404 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2405 'pkgnum' => $pkgnum, } )
2406 or return { 'error' => "unknown pkgnum $pkgnum" };
2408 my $error = $cust_pkg->suspend(reason => $reasonnum);
2409 return { 'error' => $error };
2415 my $session = _cache->get($p->{'session_id'})
2416 or return { 'error' => "Can't resume session" }; #better error message
2418 my $custnum = $session->{'custnum'};
2420 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2421 or return { 'error' => "unknown custnum $custnum" };
2423 my $pkgnum = $p->{'pkgnum'};
2425 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2426 'pkgnum' => $pkgnum, } )
2427 or return { 'error' => "unknown pkgnum $pkgnum" };
2429 my $error = $cust_pkg->cancel('quiet' => 1);
2430 return { 'error' => $error };
2434 sub provision_phone {
2437 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2439 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2440 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2441 return { 'error' => $session } if $context eq 'error';
2443 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2444 return { 'error' => 'service not found' } unless $svc_phone;
2445 return { 'error' => 'invalid svcnum' }
2446 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2448 $svc_phone->email($p->{'email'})
2449 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2450 $svc_phone->forwarddst($p->{'forwarddst'})
2451 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2452 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2453 return { 'error' => $svc_phone->replace };
2457 unless($p->{'lnp'}) {
2458 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2459 $p->{'lnp_status'} = "portingin";
2460 return _provision( 'FS::svc_phone',
2461 [qw(lnp_desired_due_date lnp_other_provider
2462 lnp_other_provider_account phonenum countrycode lnp_status)],
2463 [qw(phonenum countrycode)],
2470 unless (scalar(@bulkdid)) {
2471 return _provision( 'FS::svc_phone',
2472 [qw(phonenum countrycode)],
2473 [qw(phonenum countrycode)],
2479 # bulk DID order case
2481 foreach my $did ( @bulkdid ) {
2482 $did =~ s/[^0-9]//g;
2483 $error = _provision( 'FS::svc_phone',
2484 [qw(phonenum countrycode)],
2485 [qw(phonenum countrycode)],
2487 'pkgnum' => $p->{'pkgnum'},
2488 'svcpart' => $p->{'svcpart'},
2490 'countrycode' => $p->{'countrycode'},
2491 'session_id' => $p->{'session_id'},
2494 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2496 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2499 sub provision_acct {
2501 warn "provision_acct called\n"
2504 return { 'error' => gettext('passwords_dont_match') }
2505 if $p->{'_password'} ne $p->{'_password2'};
2506 return { 'error' => gettext('empty_password') }
2507 unless length($p->{'_password'});
2509 if ($p->{'domsvc'}) {
2510 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2511 qw ( svcpart pkgnum ) );
2512 return { 'error' => gettext('invalid_domain') }
2513 unless ($domains{$p->{'domsvc'}});
2516 warn "provision_acct calling _provision\n"
2518 _provision( 'FS::svc_acct',
2519 [qw(username _password domsvc)],
2520 [qw(username _password domsvc)],
2526 sub provision_external {
2528 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2529 _provision( 'FS::svc_external',
2538 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2539 warn "_provision called for $class\n"
2542 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2543 return { 'error' => $session } if $context eq 'error';
2545 my $search = { 'custnum' => $custnum };
2546 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2547 my $cust_main = qsearchs('cust_main', $search )
2548 or return { 'error' => "unknown custnum $custnum" };
2550 my $pkgnum = $p->{'pkgnum'};
2552 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2554 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2555 'pkgnum' => $pkgnum,
2557 or return { 'error' => "unknown pkgnum $pkgnum" };
2559 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2561 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2562 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2564 warn "creating $class record\n"
2566 my $svc_x = $class->new( {
2567 'pkgnum' => $p->{'pkgnum'},
2568 'svcpart' => $p->{'svcpart'},
2569 map { $_ => $p->{$_} } @$fields
2571 warn "inserting $class record\n"
2573 my $error = $svc_x->insert;
2576 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2578 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2581 my $return = { 'svc' => $part_svc->svc,
2583 map { $_ => $svc_x->get($_) } @$return_fields
2585 warn "_provision returning ". Dumper($return). "\n"
2594 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2595 return { 'error' => $session } if $context eq 'error';
2597 my $search = { 'custnum' => $custnum };
2598 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2599 my $cust_main = qsearchs('cust_main', $search )
2600 or return { 'error' => "unknown custnum $custnum" };
2602 my $pkgnum = $p->{'pkgnum'};
2604 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2605 'pkgnum' => $pkgnum,
2607 or return { 'error' => "unknown pkgnum $pkgnum" };
2609 my $svcpart = $p->{'svcpart'};
2611 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2612 'svcpart' => $svcpart, } )
2613 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2614 my $part_svc = $pkg_svc->part_svc;
2616 my $conf = new FS::Conf;
2619 'svc' => $part_svc->svc,
2620 'svcdb' => $part_svc->svcdb,
2621 'pkgnum' => $pkgnum,
2622 'svcpart' => $svcpart,
2623 'custnum' => $custnum,
2625 'security_phrase' => 0, #XXX !
2626 'svc_acct_pop' => [], #XXX !
2628 'init_popstate' => '',
2633 small_custview( $cust_main, $conf->config('countrydefault') ),
2637 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2638 && $ret->{'svcdb'} eq 'svc_phone') {
2639 $ret->{'svcnum'} = $p->{'svcnum'};
2640 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2641 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2642 $ret->{'email'} = $svc_phone->email;
2643 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2650 sub unprovision_svc {
2653 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2654 return { 'error' => $session } if $context eq 'error';
2656 my $search = { 'custnum' => $custnum };
2657 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2658 my $cust_main = qsearchs('cust_main', $search )
2659 or return { 'error' => "unknown custnum $custnum" };
2661 my $svcnum = $p->{'svcnum'};
2663 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2664 or return { 'error' => "unknown svcnum $svcnum" };
2666 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2667 unless $cust_svc->cust_pkg->custnum == $custnum;
2669 my $conf = new FS::Conf;
2671 return { 'svc' => $cust_svc->part_svc->svc,
2672 'error' => $cust_svc->cancel,
2674 small_custview( $cust_main, $conf->config('countrydefault') ),
2679 sub myaccount_passwd {
2681 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2682 return { 'error' => $session } if $context eq 'error';
2684 return { 'error' => "New passwords don't match." }
2685 if $p->{'new_password'} ne $p->{'new_password2'};
2687 return { 'error' => 'Enter new password' }
2688 unless length($p->{'new_password'});
2690 #my $search = { 'custnum' => $custnum };
2691 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2692 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2693 my $search = " AND custnum = $1";
2694 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2696 my $svc_acct = qsearchs( {
2697 'table' => 'svc_acct',
2698 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2699 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2700 'LEFT JOIN cust_main USING ( custnum ) ',
2701 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2702 'extra_sql' => $search, #important
2704 or return { 'error' => "Service not found" };
2706 if ( exists($p->{'old_password'}) ) {
2707 return { 'error' => "Incorrect password." }
2708 unless $svc_acct->check_password($p->{'old_password'});
2711 $svc_acct->set_password($p->{'new_password'});
2712 my $error = $svc_acct->replace();
2714 my($label, $value) = $svc_acct->cust_svc->label;
2716 return { 'error' => $error,
2726 my $conf = new FS::Conf;
2727 my $verification = $conf->config('selfservice-password_reset_verification')
2728 or return { 'error' => 'Password resets disabled' };
2730 my $username = $p->{'username'};
2732 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
2733 or return { 'error' => 'Account not found' };
2735 my $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2736 'domsvc' => $svc_domain->svcnum }
2738 or return { 'error' => 'Account not found' };
2740 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
2741 or return { 'error' => 'Account not found' };
2743 my $cust_main = $cust_pkg->cust_main;
2747 my( $p, $cust_main ) = @_;
2748 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
2749 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
2752 my( $p, $cust_main ) = @_;
2753 my $cust_pay = qsearchs({
2754 'table' => 'cust_pay',
2755 'hashref' => { 'custnum' => $cust_main->custnum },
2756 'order_by' => 'ORDER BY _date DESC LIMIT 1',
2760 $p->{'amount'} == $cust_pay->paid;
2763 my( $p, $cust_main ) = @_;
2764 $p->{'zip'} eq $cust_main->zip
2765 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
2769 foreach my $verify ( split(',', $verification) ) {
2771 &{ $verify{$verify} }( $p, $cust_main )
2772 or return { 'error' => 'Account not found' };
2776 #okay, we're verified, now create a unique session
2778 my $reset_session = {
2779 'svcnum' => $svc_acct->svcnum,
2782 my $timeout = '1 hour'; #?
2784 my $reset_session_id;
2786 $reset_session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
2787 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") ); #just in case
2789 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
2793 my $msgnum = $conf->config('selfservice-password_reset_msgnum', $cust_main->agentnum);
2794 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
2795 return { 'error' => "selfservice-password_reset_msgnum unset" } unless $msgnum;
2796 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
2797 my $error = $msg_template->send( 'cust_main' => $cust_main,
2798 'object' => $svc_acct,
2799 'substitutions' => {
2800 'session_id' => $reset_session_id,
2804 return { 'error' => $error }; #????
2807 return { 'error' => '' };
2810 sub check_reset_passwd {
2813 my $conf = new FS::Conf;
2814 my $verification = $conf->config('selfservice-password_reset_verification')
2815 or return { 'error' => 'Password resets disabled' };
2817 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
2818 or return { 'error' => "Can't resume session" }; #better error message
2820 my $svcnum = $reset_session->{'svcnum'};
2822 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
2823 or return { 'error' => "Service not found" };
2825 return { 'error' => '',
2826 'username' => $svc_acct->username,
2831 sub process_reset_passwd {
2834 my $conf = new FS::Conf;
2835 my $verification = $conf->config('selfservice-password_reset_verification')
2836 or return { 'error' => 'Password resets disabled' };
2838 return { 'error' => "New passwords don't match." }
2839 if $p->{'new_password'} ne $p->{'new_password2'};
2841 return { 'error' => 'Enter new password' }
2842 unless length($p->{'new_password'});
2844 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
2845 or return { 'error' => "Can't resume session" }; #better error message
2847 my $svcnum = $reset_session->{'svcnum'};
2849 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
2850 or return { 'error' => "Service not found" };
2852 $svc_acct->set_password($p->{'new_password'});
2853 my $error = $svc_acct->replace();
2855 my($label, $value) = $svc_acct->cust_svc->label;
2857 return { 'error' => $error,
2866 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2867 return { 'error' => $session } if $context eq 'error';
2869 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
2870 FS::TicketSystem->init();
2872 my $conf = new FS::Conf;
2873 my $queue = $p->{'queue'}
2874 || $conf->config('ticket_system-selfservice_queueid')
2875 || $conf->config('ticket_system-default_queueid');
2877 warn "$me create_ticket: creating ticket\n" if $DEBUG;
2878 my $err_or_ticket = FS::TicketSystem->create_ticket(
2879 '', #create RT session based on FS CurrentUser (fs_selfservice)
2881 'custnum' => $custnum,
2882 'svcnum' => $session->{'svcnum'},
2883 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
2886 if ( ref($err_or_ticket) ) {
2887 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
2889 return { 'error' => '',
2890 'ticket_id' => $err_or_ticket->id,
2893 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
2895 return { 'error' => $err_or_ticket };
2903 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2904 return { 'error' => $session } if $context eq 'error';
2906 return { error => 'requested format not implemented' }
2907 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
2909 my $conf = new FS::Conf;
2910 my $age_threshold = 0;
2911 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
2912 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
2914 my $search = { 'custnum' => $custnum };
2915 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2916 my $cust_main = qsearchs('cust_main', $search )
2917 or return { 'error' => "unknown custnum $custnum" };
2919 # does it make more sense to just run one sql query for this instead of all the
2920 # insanity below? would increase performance greately for large data sets?
2922 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
2923 my @part_svc = $cust_pkg->part_svc;
2924 foreach my $part_svc ( @part_svc ) {
2925 if($part_svc->svcdb eq 'svc_phone'){
2926 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
2927 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
2928 push @svc_phone, $cust_pkg_svc->svc_x
2929 if $cust_pkg_svc->date_inserted >= $age_threshold;
2937 my($xls_r,$xls_c) = (0,0);
2940 my @fields = qw( countrycode phonenum pin sip_password phone_name );
2941 if($p->{'format'} eq 'csv') {
2942 $csv = new Text::CSV_XS { 'always_quote' => 1,
2945 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2946 $content .= $csv->string;
2948 elsif($p->{'format'} eq 'xls') {
2949 my $XLS1 = new IO::Scalar \$content;
2950 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
2951 or return { 'error' => "Error opening .xls file: $!" };
2952 $xls = $xls_workbook->add_worksheet('DIDs');
2953 foreach ( @fields ) {
2954 $xls->write(0,$xls_c++,$_);
2959 foreach my $svc_phone ( @svc_phone ) {
2960 my @cols = map { $svc_phone->$_ } @fields;
2961 if($p->{'format'} eq 'csv') {
2962 return { 'error' => 'Unable to create CSV' }
2963 unless $csv->combine(@cols);
2964 $content .= $csv->string;
2966 elsif($p->{'format'} eq 'xls') {
2969 $xls->write($xls_r,$xls_c++,$_);
2975 $xls_workbook->close() if $p->{'format'} eq 'xls';
2977 { content => $content, format => $p->{'format'}, };
2982 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2983 return { 'error' => $session } if $context eq 'error';
2985 warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2986 FS::TicketSystem->init();
2987 return { 'error' => 'get_ticket configuration error' }
2988 if $FS::TicketSystem::system ne 'RT_Internal';
2990 # check existence and ownership as part of this
2991 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2992 my $rt_session = FS::TicketSystem->session('');
2993 my $Ticket = FS::TicketSystem->get_ticket_object(
2995 ticket_id => $p->{'ticket_id'},
2998 return { 'error' => 'ticket not found' } if !$Ticket;
3000 if ( length( $p->{'subject'} || '' ) ) {
3002 if ( $p->{'subject'} ne $Ticket->Subject ) {
3003 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3004 return { 'error' => "unable to set subject: $msg" } if !$val;
3008 if(length($p->{'reply'})) {
3009 my @err_or_res = FS::TicketSystem->correspond_ticket(
3011 'ticket_id' => $p->{'ticket_id'},
3012 'content' => $p->{'reply'},
3015 return { 'error' => 'unable to reply to ticket' }
3016 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3019 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3020 my $err_or_ticket = FS::TicketSystem->get_ticket(
3022 'ticket_id' => $p->{'ticket_id'},
3025 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3026 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3028 return { 'error' => $err_or_ticket };
3031 my @custs = @{$err_or_ticket->{'custs'}};
3032 my @txns = @{$err_or_ticket->{'txns'}};
3035 # superseded by check in get_ticket_object
3036 #return { 'error' => 'invalid ticket requested' }
3037 #unless grep($_ eq $custnum, @custs);
3039 foreach my $txn ( @txns ) {
3040 push @filtered_txns, $txn
3041 if ($txn->{'type'} eq 'EmailRecord'
3042 || $txn->{'type'} eq 'Correspond'
3043 || $txn->{'type'} eq 'Create');
3046 warn "$me get_ticket: successful: \n"
3048 return { 'error' => '',
3049 'transactions' => \@filtered_txns,
3050 'ticket_fields' => $err_or_ticket->{'fields'},
3051 'ticket_id' => $p->{'ticket_id'},
3055 sub adjust_ticket_priority {
3057 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3058 return { 'error' => $session } if $context eq 'error';
3060 warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3061 FS::TicketSystem->init;
3062 my $ss_priority = FS::TicketSystem->selfservice_priority;
3064 return { 'error' => 'adjust_ticket_priority configuration error' }
3065 if $FS::TicketSystem::system ne 'RT_Internal'
3068 my $values = $p->{'values'}; #hashref, id => priority value
3071 foreach my $id (keys %$values) {
3072 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3073 my $Ticket = FS::TicketSystem->get_ticket_object('',
3075 'custnum' => $custnum,
3078 $ticket_error{$id} = 'ticket not found';
3082 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3083 # We're not going to implement it for RT_External.
3084 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3085 my $new_value = $values->{$id};
3086 next if $old_value eq $new_value;
3088 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3090 # AddCustomFieldValue works fine (replacing any existing value) if it's
3091 # a single-valued custom field, which it should be. If it's not, you're
3092 # doing something wrong.
3094 if ( length($new_value) ) {
3095 ($val, $msg) = $Ticket->AddCustomFieldValue(
3096 Field => $ss_priority,
3097 Value => $new_value,
3101 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3102 Field => $ss_priority,
3103 Value => $old_value,
3107 $ticket_error{$id} = $msg if !$val;
3108 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3110 return { 'error' => '',
3111 'ticket_error' => \%ticket_error,
3112 %{ customer_info($p) } # send updated customer info back
3118 sub _custoragent_session_custnum {
3121 my($context, $session, $custnum);
3122 if ( $p->{'session_id'} ) {
3124 $context = 'customer';
3125 $session = _cache->get($p->{'session_id'})
3126 or return ( 'error' => "Can't resume session" ); #better error message
3127 $custnum = $session->{'custnum'};
3129 } elsif ( $p->{'agent_session_id'} ) {
3132 my $agent_cache = new FS::ClientAPI_SessionCache( {
3133 'namespace' => 'FS::ClientAPI::Agent',
3135 $session = $agent_cache->get($p->{'agent_session_id'})
3136 or return ( 'error' => "Can't resume session" ); #better error message
3137 $custnum = $p->{'custnum'};
3141 return ( 'error' => "Can't resume session" ); #better error message
3144 ($context, $session, $custnum);