1 package FS::ClientAPI::MyAccount;
3 use 5.008; #require 5.8+ for Time::Local 1.05+
5 use vars qw( $cache $DEBUG $me );
6 use subs qw( _cache _provision );
9 use Digest::MD5 qw(md5_hex);
10 use Digest::SHA qw(sha512_hex);
13 use Time::Local qw(timelocal_nocheck);
14 use Business::CreditCard 0.35;
17 use Spreadsheet::WriteExcel;
18 use OLE::Storage_Lite;
19 use FS::UI::Web::small_custview qw(small_custview); #less doh
21 use FS::UI::bytecount qw( display_bytecount );
24 use FS::Record qw(qsearch qsearchs dbh);
25 use FS::Msgcat qw(gettext);
26 use FS::Misc qw(card_types money_pretty);
27 use FS::Misc::DateTime qw(parse_datetime);
29 use FS::ClientAPI_SessionCache;
41 use FS::legacy_cust_bill;
42 use FS::cust_main_county;
46 use FS::acct_rt_transaction;
49 use FS::cust_location;
51 # for code organization
52 use FS::ClientAPI::MyAccount::contact;
53 use FS::ClientAPI::MyAccount::quotation;
56 $me = '[FS::ClientAPI::MyAccount]';
58 use vars qw( @cust_main_editable_fields @location_editable_fields );
59 @cust_main_editable_fields = qw(
60 first last company daytime night fax mobile
62 payby payinfo payname paystart_month paystart_year payissue payip
63 ss paytype paystate stateid stateid_state
65 @location_editable_fields = qw(
66 address1 address2 city county state zip country
70 BEGIN { #preload to reduce time customer_info takes
71 if ( $FS::TicketSystem::system ) {
72 warn "$me: initializing ticket system\n" if $DEBUG;
73 FS::TicketSystem->init();
78 $cache ||= new FS::ClientAPI_SessionCache( {
79 'namespace' => 'FS::ClientAPI::MyAccount',
86 my($context, $session, $custnum) = _custoragent_session_custnum($p);
87 #return { 'error' => $session } if $context eq 'error';
90 if ( $context eq 'customer' ) {
92 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
95 $sth->execute($custnum) or die $sth->errstr;
97 $agentnum = $sth->fetchrow_arrayref->[0]
98 or die "no agentnum for custnum $custnum";
100 #} elsif ( $context eq 'agent' ) {
101 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
104 $p->{'agentnum'} = $agentnum;
106 my $conf = new FS::Conf;
108 #false laziness w/Signup.pm
110 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
112 if ( $skin_info_cache_agent ) {
114 warn "$me loading cached skin info for agentnum $agentnum\n"
119 warn "$me populating skin info cache for agentnum $agentnum\n"
122 $skin_info_cache_agent = {
123 'agentnum' => $agentnum,
124 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
125 qw( company_name date_format ) ),
126 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
127 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
128 text_color link_color vlink_color hlink_color alink_color
129 font title_color title_align title_size menu_bgcolor menu_fontsize
132 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
133 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
134 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo enable_payment_without_balance )
136 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
137 qw( title_left_image title_right_image
138 menu_top_image menu_body_image menu_bottom_image
141 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
142 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
143 qw( head body_header body_footer company_address ) ),
144 'money_char' => $conf->config("money_char") || '$',
145 'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
148 services.php Services
149 services.php My Services
150 services_new.php Order a new service
153 personal.php Personal Information
154 password.php Change Password
157 payment_cc.php Credit Card Payment
158 payment_ach.php Electronic Check Payment
159 payment_paypal.php PayPal Payment
160 payment_webpay.php Webpay Payments
163 usage_data.php Data usage
164 usage_cdr.php Call usage
166 tickets.php Help Desk
167 tickets.php Open Tickets
168 tickets_resolved.php Resolved Tickets
169 ticket_create.php Create a new ticket
177 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
181 #{ %$skin_info_cache_agent };
182 $skin_info_cache_agent;
189 my $conf = new FS::Conf;
193 'phone_login' => $conf->exists('selfservice_server-phone_login'),
194 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
195 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
196 'banner_image_md5' =>
197 md5_hex($conf->config_binary('selfservice-login_banner_image')),
204 sub login_banner_image {
206 my $conf = new FS::Conf;
207 my $image = $conf->config_binary('selfservice-login_banner_image');
209 'md5' => md5_hex($image),
214 #false laziness w/FS::ClientAPI::passwd::passwd
218 my $conf = new FS::Conf;
222 if ( $p->{'domain'} eq 'svc_phone'
223 && $conf->exists('selfservice_server-phone_login') ) {
225 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
226 return { error => 'Number not found.' } unless $svc_phone;
229 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
230 #return { error => 'Only primary user may log in.' }
231 # if $conf->exists('selfservice_server-primary_only')
232 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
234 return { error => 'Incorrect PIN.' }
235 unless $svc_phone->check_pin($p->{'password'});
239 } elsif ( $p->{email}
240 && (my $contact = FS::contact->by_selfservice_email($p->{email}))
243 return { error => 'Incorrect contact password.' }
244 unless $contact->authenticate_password($p->{'password'});
246 $session->{'contactnum'} = $contact->contactnum;
248 $session->{'custnum'} = $contact->custnum;
252 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
254 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
255 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
257 my @svc_acct = qsearch( 'svc_acct', { 'username' => $p->{'username'},
258 'domsvc' => $svc_domain->svcnum, }
261 if ( $conf->exists('selfservice_server-login_svcpart') ) {
262 my @svcpart = $conf->config('selfservice_server-login_svcpart');
263 @svc_acct = grep { my $svcpart = $_->cust_svc->svcpart;
264 scalar( grep( $_ eq $svcpart, @svcpart ) );
269 if ( $conf->exists('selfservice_server-primary_only') ) {
272 my $cust_svc = $_->cust_svc;
273 $cust_svc->cust_pkg->part_pkg->svcpart([qw( svc_acct svc_phone )])
274 == $cust_svc->svcpart
279 return { error => 'User not found.' } unless @svc_acct;
281 #return { error => 'Multiple users.' } if scalar(@svc_acct) > 1;
283 my $svc_acct = $svc_acct[0];
285 if ( $conf->exists('selfservice_server-login_svcpart') ) {
286 my @svcpart = $conf->config('selfservice_server-login_svcpart');
287 my $svcpart = $svc_acct->cust_svc->svcpart;
288 return { error => 'Invalid user.' }
289 unless grep($_ eq $svcpart, @svcpart);
292 return { error => 'Incorrect password.' }
293 unless $svc_acct->check_password($p->{'password'});
301 $session->{'svcnum'} = $svc_x->svcnum;
303 my $cust_svc = $svc_x->cust_svc;
304 my $cust_pkg = $cust_svc->cust_pkg;
306 my $cust_main = $cust_pkg->cust_main;
307 $session->{'custnum'} = $cust_main->custnum;
308 if ( $conf->exists('pkg-balances') ) {
309 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
310 $cust_main->ncancelled_pkgs;
311 $session->{'pkgnum'} = $cust_pkg->pkgnum
312 if scalar(@cust_pkg) > 1;
316 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
317 #return { error => 'Only primary user may log in.' }
318 # if $conf->exists('selfservice_server-primary_only')
319 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
320 my $part_pkg = $cust_pkg->part_pkg;
321 return { error => 'Only primary user may log in.' }
322 if $conf->exists('selfservice_server-primary_only')
323 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
329 $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
330 } until ( ! defined _cache->get($session_id) ); #just in case
332 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
333 _cache->set( $session_id, $session, $timeout );
335 return { 'error' => '',
336 'session_id' => $session_id,
342 my $skin_info = skin_info($p);
343 if ( $p->{'session_id'} ) {
344 _cache->remove($p->{'session_id'});
345 return { %$skin_info, 'error' => '' };
347 return { %$skin_info, 'error' => "Can't resume session" }; #better error message
354 my($context, $session, $custnum) = _custoragent_session_custnum($p);
355 return { 'error' => $session } if $context eq 'error';
357 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
358 or return { 'error' => "Service not found" };
360 $session->{'svcnum'} = $svc_acct->svcnum;
362 my $conf = new FS::Conf;
363 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
364 _cache->set( $p->{'session_id'}, $session, $timeout );
366 return { 'error' => '' };
370 sub payment_gateway {
372 # takes a cust_main and a cust_payby entry, returns the payment_gateway
373 my $conf = new FS::Conf;
374 my $cust_main = shift;
375 my $cust_payby = shift;
376 my $gatewaynum = $conf->config('selfservice-payment_gateway');
378 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
379 die "configured gatewaynum $gatewaynum not found!" if !$pg;
383 return '' if ! FS::payby->realtime($cust_payby);
384 my $pg = $cust_main->agent->payment_gateway(
385 'method' => FS::payby->payby2bop($cust_payby),
395 my $conf = new FS::Conf;
397 my $info = skin_info($p);
399 use vars qw( $cust_paybys ); #cache for performance
400 unless ( $cust_paybys ) {
402 my %cust_paybys = map { $_ => 1 }
403 map { FS::payby->payby2payment($_) }
404 $conf->config('signup_server-payby');
406 $cust_paybys = [ keys %cust_paybys ];
409 $info->{'cust_paybys'} = $cust_paybys;
411 my($context, $session, $custnum) = _custoragent_session_custnum($p);
412 return { 'error' => $session } if $context eq 'error';
414 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
415 or return { 'error' => "unknown custnum $custnum" };
417 $info->{'hide_payment_fields'} = [
419 my $pg = payment_gateway($cust_main, $_);
420 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
421 } @{ $info->{cust_paybys} }
424 $info->{'self_suspend_reason'} =
425 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
427 $info->{'edit_ticket_subject'} =
428 $conf->exists('ticket_system-selfservice_edit_subject') &&
429 $cust_main->edit_subject;
431 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
433 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
436 'custnum' => $custnum,
437 'access_pkgnum' => $session->{'pkgnum'},
438 'access_svcnum' => $session->{'svcnum'},
445 my($context, $session, $custnum) = _custoragent_session_custnum($p);
446 return { 'error' => $session } if $context eq 'error';
450 my $conf = new FS::Conf;
451 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
453 # if ( $FS::TicketSystem::system ) {
454 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
455 # FS::TicketSystem->init();
458 if ( $custnum ) { #customer record
460 %return = ( %return, %{ customer_info_short($p) } );
462 #redundant with customer_info_short, but we need it for several things below
463 my $search = { 'custnum' => $custnum };
464 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
465 my $cust_main = qsearchs('cust_main', $search )
466 or return { 'error' => "unknown custnum $custnum" };
468 my $list_tickets = list_tickets($p);
469 $return{'tickets'} = $list_tickets->{'tickets'};
471 if ( $session->{'pkgnum'} ) {
472 #XXX open invoices in the pkg-balances case
474 $return{'money_char'} = $conf->config("money_char") || '$';
477 invnum => $_->invnum,
478 date => time2str("%b %o, %Y", $_->_date),
480 charged => $_->charged,
482 } $cust_main->open_cust_bill;
483 $return{open_invoices} = \@open;
485 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
486 my $sth = dbh->prepare($sql) or die dbh->errstr;
487 $sth->execute($custnum) or die $sth->errstr;
488 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
489 $return{'last_invoice_date_pretty'} =
490 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
493 #customer_info_short always has nobalance on..
494 $return{small_custview} =
495 small_custview( $cust_main,
496 $return{countrydefault},
497 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
500 $return{has_ship_address} = $cust_main->has_ship_address;
501 $return{status} = $cust_main->status;
502 $return{statuscolor} = $cust_main->statuscolor;
504 # compatibility: some places in selfservice use this to determine
505 # if there's a ship address
506 if ( $return{has_ship_address} ) {
507 $return{ship_last} = $cust_main->last;
508 $return{ship_first} = $cust_main->first;
511 if (scalar($conf->config('support_packages'))) {
512 my @support_services = ();
513 foreach ($cust_main->support_services) {
514 my $seconds = $_->svc_x->seconds || 0;
515 my $time_remaining = (($seconds < 0) ? '-' : '' ).
516 int(abs($seconds)/3600)."h".
517 sprintf("%02d",(abs($seconds)%3600)/60)."m";
518 my $cust_pkg = $_->cust_pkg;
521 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
522 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
523 push @support_services, { svcnum => $_->svcnum,
524 time => $time_remaining,
529 $return{support_services} = \@support_services;
532 if ( $conf->config('prepayment_discounts-credit_type') ) {
534 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
537 } elsif ( $session->{'svcnum'} ) { #no customer record
539 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
540 or die "unknown svcnum";
541 $return{name} = $svc_acct->email;
545 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
549 return { 'error' => '',
550 'custnum' => $custnum,
556 sub customer_info_short {
559 my($context, $session, $custnum) = _custoragent_session_custnum($p);
560 return { 'error' => $session } if $context eq 'error';
564 my $conf = new FS::Conf;
566 if ( $custnum ) { #customer record
568 my $search = { 'custnum' => $custnum };
569 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
570 my $cust_main = qsearchs('cust_main', $search )
571 or return { 'error' => "unknown custnum $custnum" };
573 $return{display_custnum} = $cust_main->display_custnum;
575 if ( $session->{'pkgnum'} ) {
576 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
577 #next_bill_date from cust_pkg?
579 $return{balance} = $cust_main->balance;
580 $return{next_bill_date} = $cust_main->next_bill_date;
581 $return{next_bill_date_pretty} =
582 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
585 $return{balance_pretty} = money_pretty($return{balance});
587 $return{countrydefault} = scalar($conf->config('countrydefault'));
589 $return{small_custview} =
590 small_custview( $cust_main,
591 $return{countrydefault},
595 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
597 $return{payby} = $cust_main->payby;
599 #none of these are terribly expensive if we want 'em...
600 for (@cust_main_editable_fields) {
601 $return{$_} = $cust_main->get($_);
603 #maybe a little more expensive, but it should be cached by now
604 for (@location_editable_fields) {
605 $return{$_} = $cust_main->bill_location->get($_);
606 $return{'ship_'.$_} = $cust_main->ship_location->get($_);
609 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
610 $return{payinfo} = $cust_main->paymask;
611 @return{'month', 'year'} = $cust_main->paydate_monthyear;
614 my @invoicing_list = $cust_main->invoicing_list;
615 $return{'invoicing_list'} =
616 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
617 $return{'postal_invoicing'} =
618 0 < ( grep { $_ eq 'POST' } @invoicing_list );
620 if ( $session->{'svcnum'} ) {
621 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
622 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
623 $return{'svcnum'} = $session->{'svcnum'};
626 } elsif ( $session->{'svcnum'} ) { #no customer record
628 #uuh, not supproted yet... die?
629 return { 'error' => 'customer_info_short not yet supported as agent' };
633 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
637 # this is here because this routine is called by both fs_ and ng_ main pages, where it appears
638 # it is not customer-specific, though it is only shown to authenticated customers
639 # it is not currently agent-specific, though at some point it might be
640 $return{'announcement'} = join(' ',$conf->config('selfservice-announcement')) || '';
642 return { 'error' => '',
643 'custnum' => $custnum,
648 sub customer_recurring {
651 my($context, $session, $custnum) = _custoragent_session_custnum($p);
652 return { 'error' => $session } if $context eq 'error';
656 my $conf = new FS::Conf;
658 my $search = { 'custnum' => $custnum };
659 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
660 my $cust_main = qsearchs('cust_main', $search )
661 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
663 $return{'display_recurring'} = [ $cust_main->display_recurring ];
665 return { 'error' => '',
666 'custnum' => $custnum,
671 sub billing_history {
674 my($context, $session, $custnum) = _custoragent_session_custnum($p);
675 return { 'error' => $session } if $context eq 'error';
677 return { 'error' => 'No customer' } unless $custnum;
679 my $search = { 'custnum' => $custnum };
680 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
681 my $cust_main = qsearchs('cust_main', $search )
682 or return { 'error' => "unknown custnum $custnum" };
686 if ( $session->{'pkgnum'} ) {
687 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
688 #next_bill_date from cust_pkg?
689 return { 'error' => 'No history for package' };
692 $return{balance} = $cust_main->balance;
693 $return{balance_pretty} = money_pretty($return{balance});
694 $return{next_bill_date} = $cust_main->next_bill_date;
695 $return{next_bill_date_pretty} =
696 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
699 my $conf = new FS::Conf;
701 $return{'history'} = [
702 $cust_main->payment_history(
703 'line_items' => $conf->exists('selfservice-billing_history-line_items'),
708 $return{'money_char'} = $conf->config("money_char") || '$',
716 my $session = _cache->get($p->{'session_id'})
717 or return { 'error' => "Can't resume session" }; #better error message
719 my $custnum = $session->{'custnum'}
720 or return { 'error' => "no customer record" };
722 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
723 or return { 'error' => "unknown custnum $custnum" };
725 my $conf = new FS::Conf;
726 if (($p->{payby} eq "CHEK" || $p->{payby} eq "DCHK") && $conf->exists('selfservice-ACH_info_readonly')) {
727 return { 'error' => "You do not have authority to add a bank account" };
730 my $new = new FS::cust_main { $cust_main->hash };
732 $new->set( $_ => $p->{$_} )
733 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
735 if ( exists($p->{address1}) ) {
736 my $bill_location = FS::cust_location->new({
737 map { $_ => $p->{$_} } @location_editable_fields
739 # if this is unchanged from before, cust_main::replace will ignore it
740 $new->set('bill_location' => $bill_location);
743 if ( exists($p->{ship_address1}) ) {
744 my $ship_location = FS::cust_location->new({
745 map { $_ => $p->{"ship_$_"} } @location_editable_fields
747 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
748 # Selfservice unfortunately tries to indicate "same as billing
749 # address" by sending all fields empty. Did this ever work?
750 $ship_location = $cust_main->bill_location;
752 $new->set('ship_location' => $ship_location);
754 # but if it hasn't been passed in at all, leave ship_location alone--
755 # DON'T change it to match bill_location.
758 if (exists($p->{'payby'})) {
759 $p->{'payby'} =~ /^([A-Z]{4})$/
760 or return { 'error' => "illegal_payby " . $p->{'payby'} };
764 if ( $payby =~ /^(CARD|DCRD)$/ ) {
766 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
768 if ( $new->payinfo eq $cust_main->paymask ) {
769 $new->payinfo($cust_main->payinfo);
770 $new->paycvv( $p->{'paycvv'} || $cust_main->paycvv );
772 $new->payinfo($p->{'payinfo'});
773 return { 'error' => 'CVV2 is required' }
774 if ! $p->{'paycvv'} && $conf->exists('selfservice-onfile_require_cvv');
775 $new->paycvv( $p->{'paycvv'} )
778 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
780 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
783 $p->{'payinfo1'} =~ /^([\dx]+)$/
784 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
786 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
787 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
789 $payinfo = $payinfo1. '@'. $payinfo2;
791 $new->payinfo( ($payinfo eq $cust_main->paymask)
792 ? $cust_main->payinfo
796 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
798 } elsif ( $payby =~ /^(BILL)$/ ) {
800 } elsif ( $payby ) { #notyet ready
801 return { 'error' => "unknown payby $payby" };
805 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
806 #false laziness with httemplate/edit/process/cust_main.cgi
807 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
808 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
810 @invoicing_list = $cust_main->invoicing_list;
813 my $error = $new->replace($cust_main, \@invoicing_list);
814 return { 'error' => $error } if $error;
817 return { 'error' => '' };
822 my $session = _cache->get($p->{'session_id'})
823 or return { 'error' => "Can't resume session" }; #better error message
829 my $conf = new FS::Conf;
830 use vars qw($payment_info); #cache for performance
831 unless ( $payment_info ) {
833 my %states = map { $_->state => 1 }
834 qsearch('cust_main_county', {
835 'country' => $conf->config('countrydefault') || 'US'
838 my %cust_paybys = map { $_ => 1 }
839 map { FS::payby->payby2payment($_) }
840 $conf->config('signup_server-payby');
842 my @cust_paybys = keys %cust_paybys;
846 #list all counties/states/countries
847 'cust_main_county' =>
848 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
850 #shortcut for one-country folks
852 [ sort { $a cmp $b } keys %states ],
854 'card_types' => card_types(),
856 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
857 'require_cvv' => $conf->exists('selfservice-require_cvv'),
858 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
860 'paytypes' => [ @FS::cust_main::paytypes ],
862 'paybys' => [ $conf->config('signup_server-payby') ],
863 'cust_paybys' => \@cust_paybys,
865 'stateid_label' => FS::Msgcat::_gettext('stateid'),
866 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
868 'show_ss' => $conf->exists('show_ss'),
869 'show_stateid' => $conf->exists('show_stateid'),
870 'show_paystate' => $conf->exists('show_bankstate'),
872 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
873 'ach_read_only' => $conf->exists('selfservice-ACH_info_readonly'),
883 my %return = %$payment_info;
885 delete $return{'cust_main_county'} if $p->{'omit_cust_main_county'};
887 my $custnum = $session->{'custnum'};
889 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
890 or return { 'error' => "unknown custnum $custnum" };
892 $return{'hide_payment_fields'} = [
894 my $pg = payment_gateway($cust_main, $_);
895 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
896 } @{ $return{cust_paybys} }
899 $return{balance} = $cust_main->balance; #XXX pkg-balances?
901 $return{payname} = $cust_main->payname
902 || ( $cust_main->first. ' '. $cust_main->get('last') );
904 $return{$_} = $cust_main->bill_location->get($_)
905 for qw(address1 address2 city state zip);
907 $return{payby} = $cust_main->payby;
908 $return{stateid_state} = $cust_main->stateid_state;
910 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
911 $return{card_type} = cardtype($cust_main->payinfo);
912 $return{payinfo} = $cust_main->paymask;
914 @return{'month', 'year'} = $cust_main->paydate_monthyear;
918 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
919 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
920 $return{payinfo1} = $payinfo1;
921 $return{payinfo2} = $payinfo2;
922 $return{paytype} = $cust_main->paytype;
923 $return{paystate} = $cust_main->paystate;
924 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
927 if ( $conf->config('prepayment_discounts-credit_type') ) {
929 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
932 #doubleclick protection
934 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
935 $return{paybatch} = $return{payunique}; #back compat
937 $return{credit_card_surcharge_percentage} = $conf->config('credit-card-surcharge-percentage', $cust_main->agentnum);
939 return { 'error' => '',
945 #some false laziness with httemplate/process/payment.cgi - look there for
946 #ACH and CVV support stuff
948 sub validate_payment {
951 my $session = _cache->get($p->{'session_id'})
952 or return { 'error' => "Can't resume session" }; #better error message
954 my $custnum = $session->{'custnum'};
956 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
957 or return { 'error' => "unknown custnum $custnum" };
959 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
960 or return { 'error' => gettext('illegal_amount') };
962 return { error => 'Amount must be greater than 0' } unless $amount > 0;
964 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
965 #changing the hidden form values
966 my $conf = new FS::Conf;
967 my $fee_display = $conf->config('selfservice_process-display') || 'add';
968 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
969 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
970 if ( $fee_display eq 'add'
972 and ! $fee_skip_first || scalar($cust_main->cust_pay)
975 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
976 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
979 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
980 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
981 my $discount_term = $1;
983 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
984 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
987 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
988 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
991 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
992 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
995 $payunique = $paybatch if ! length($payunique) && length($paybatch);
997 $p->{'payby'} ||= 'CARD';
998 $p->{'payby'} =~ /^([A-Z]{4})$/
999 or return { 'error' => "illegal_payby " . $p->{'payby'} };
1002 #false laziness w/process/payment.cgi
1005 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
1007 $p->{'payinfo1'} =~ /^([\dx]+)$/
1008 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1010 $p->{'payinfo2'} =~ /^([\dx]+)$/
1011 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1013 $payinfo = $payinfo1. '@'. $payinfo2;
1015 $payinfo = $cust_main->payinfo
1016 if $cust_main->paymask eq $payinfo;
1019 if ( $cust_main->paymask eq $payinfo ) {
1020 $payinfo = $cust_main->payinfo;
1024 if ($conf->exists('selfservice-ACH_info_readonly') && !$achonfile) {
1025 return { 'error' => "You are not allowed to change your payment information." };
1028 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1030 $payinfo = $p->{'payinfo'};
1034 #more intelligent matching will be needed here if you change
1035 #card_masking_method and don't remove existing paymasks
1036 if ( $cust_main->paymask eq $payinfo ) {
1037 $payinfo = $cust_main->payinfo;
1041 $payinfo =~ s/\D//g;
1042 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1043 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1047 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1048 return { 'error' => gettext('unknown_card_type') }
1049 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1051 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1052 if ( cardtype($payinfo) eq 'American Express card' ) {
1053 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1054 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1057 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1058 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1061 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1062 return { 'error' => 'CVV2 is required' };
1063 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1064 return { 'error' => 'CVV2 is required' };
1068 die "unknown payby $payby";
1071 my %payby2fields = (
1072 'CARD' => [ qw( paystart_month paystart_year payissue payip
1073 address1 address2 city state zip country ) ],
1074 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1078 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1081 'cust_main' => $cust_main, #XXX or just custnum??
1082 'amount' => sprintf('%.2f', $amount),
1084 'payinfo' => $payinfo,
1085 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1086 'card_type' => $card_type,
1087 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1088 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1089 'month' => $p->{'month'},
1090 'year' => $p->{'year'},
1091 'payname' => $payname,
1092 'payunique' => $payunique,
1093 'paybatch' => $paybatch,
1094 'paycvv' => $paycvv,
1095 'payname' => $payname,
1096 'discount_term' => $discount_term,
1097 'pkgnum' => $session->{'pkgnum'},
1098 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1108 my $validate = validate_payment($p);
1109 return $validate if $validate->{'error'};
1111 my $conf = new FS::Conf;
1112 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1113 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1115 +{ map { $_=>$validate->{$_} }
1116 qw( card_type paymask payname paydate_pretty month year amount
1117 address1 address2 city state zip country
1123 sub process_stored_payment {
1126 my $session_id = $p->{'session_id'};
1128 my $payment_info = _cache->get( "payment_$session_id" )
1129 or return { 'error' => "Can't resume session" }; #better error message
1131 do_process_payment($payment_info);
1135 sub process_payment {
1138 my $payment_info = validate_payment($p);
1139 return $payment_info if $payment_info->{'error'};
1141 do_process_payment($payment_info);
1145 sub do_process_payment {
1146 my $validate = shift;
1148 my $cust_main = $validate->{'cust_main'};
1150 my $amount = delete $validate->{'amount'};
1153 my $payby = delete $validate->{'payby'};
1155 if ( $validate->{'save'} ) {
1156 my $new = new FS::cust_main { $cust_main->hash };
1157 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1158 $new->set( $_ => $validate->{$_} )
1159 foreach qw( payname paystart_month paystart_year payissue payip );
1160 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1162 my $bill_location = FS::cust_location->new({
1163 map { $_ => $validate->{$_} }
1164 qw(address1 address2 city state country zip)
1166 $new->set('bill_location' => $bill_location);
1167 # but don't allow the service address to change this way.
1169 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1170 $new->set( $_ => $validate->{$_} )
1171 foreach qw( payname payip paytype paystate
1172 stateid stateid_state );
1173 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1175 $new->payinfo( $validate->{'payinfo'} ); #to properly set paymask
1176 $new->set( 'paydate' => $validate->{'paydate'} );
1177 my $error = $new->replace($cust_main);
1179 #no, this causes customers to process their payments again
1180 #return { 'error' => $error };
1181 #XXX just warn verosely for now so i can figure out how these happen in
1182 # the first place, eventually should redirect them to the "change
1183 #address" page but indicate if the payment processed?
1184 delete($validate->{'payinfo'}); #don't want to log this!
1185 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1186 "NEW: ". Dumper($new)."\n".
1187 "OLD: ". Dumper($cust_main)."\n".
1188 "PACKET: ". Dumper($validate)."\n";
1194 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1198 'paynum_ref' => \$paynum,
1201 return { 'error' => $error } if $error;
1203 #no error, so order the fee package if applicable...
1204 my $conf = new FS::Conf;
1205 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1206 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1208 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1210 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1212 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1213 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1216 #and generate an invoice for it now too
1217 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1218 return { 'error' => "payment processed and fee ordered successfully, but error billing fee: $error" }
1223 $cust_main->apply_payments;
1226 my $receipt_html = '';
1228 # currently supported for realtime CC only; send receipt data to SS
1229 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1232 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1235 <TD ALIGN="right">Payment#</TD>
1236 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1240 <TD ALIGN="right">Date</TD>
1242 <TD BGCOLOR="#FFFFFF"><B>! .
1243 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1249 <TD ALIGN="right">Amount</TD>
1250 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1255 <TD ALIGN="right">Payment method</TD>
1256 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1269 'amount' => sprintf('%.2f', $cust_pay->paid),
1270 'date' => $cust_pay->_date,
1271 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1272 'time_pretty' => time2str('%T', $cust_pay->_date),
1273 'auth_num' => $cust_pay->auth,
1274 'order_num' => $cust_pay->order_number,
1275 'receipt_html' => $receipt_html,
1282 'receipt_html' => '',
1289 sub realtime_collect {
1292 my $session = _cache->get($p->{'session_id'})
1293 or return { 'error' => "Can't resume session" }; #better error message
1295 my $custnum = $session->{'custnum'};
1297 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1298 or return { 'error' => "unknown custnum $custnum" };
1301 if ( $p->{'amount'} ) {
1302 $amount = $p->{'amount'};
1304 elsif ( $session->{'pkgnum'} ) {
1305 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1308 $amount = $cust_main->balance;
1311 my $error = $cust_main->realtime_collect(
1312 'method' => $p->{'method'},
1313 'amount' => $amount,
1314 'pkgnum' => $session->{'pkgnum'},
1315 'session_id' => $p->{'session_id'},
1319 return { 'error' => $error } unless ref( $error );
1321 return { 'error' => '', amount => $amount, %$error };
1324 sub start_thirdparty {
1326 my $session = _cache->get($p->{'session_id'})
1327 or return { 'error' => "Can't resume session" }; #better error message
1328 my $custnum = $session->{'custnum'};
1329 my $cust_main = FS::cust_main->by_key($custnum);
1331 my $amount = $p->{'amount'}
1332 or return { error => 'no amount' };
1334 my $result = $cust_main->create_payment(
1335 'method' => $p->{'method'},
1336 'amount' => $p->{'amount'},
1337 'pkgnum' => $session->{'pkgnum'},
1338 'session_id' => $p->{'session_id'},
1341 if ( ref($result) ) { # hashref or error
1344 return { error => $result };
1348 sub finish_thirdparty {
1350 my $session_id = delete $p->{'session_id'};
1351 my $session = _cache->get($session_id)
1352 or return { 'error' => "Can't resume session" };
1353 my $custnum = $session->{'custnum'};
1354 my $cust_main = FS::cust_main->by_key($custnum);
1356 if ( $p->{_cancel} ) {
1357 # customer backed out of making a payment
1358 return $cust_main->cancel_payment( $session_id );
1360 my $result = $cust_main->execute_payment( $session_id, %$p );
1361 if ( ref($result) ) {
1364 return { error => $result };
1368 sub process_payment_order_pkg {
1371 my $hr = process_payment($p);
1372 return $hr if $hr->{'error'};
1377 sub process_payment_order_renew {
1380 my $hr = process_payment($p);
1381 return $hr if $hr->{'error'};
1386 sub process_prepay {
1390 my $session = _cache->get($p->{'session_id'})
1391 or return { 'error' => "Can't resume session" }; #better error message
1395 my $custnum = $session->{'custnum'};
1397 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1398 or return { 'error' => "unknown custnum $custnum" };
1400 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1401 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1409 return { 'error' => $error } if $error;
1411 return { 'error' => '',
1412 'amount' => $amount,
1413 'seconds' => $seconds,
1414 'duration' => duration_exact($seconds),
1415 'upbytes' => $upbytes,
1416 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1417 'downbytes' => $downbytes,
1418 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1419 'totalbytes'=> $totalbytes,
1420 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1427 my $session = _cache->get($p->{'session_id'})
1428 or return { 'error' => "Can't resume session" }; #better error message
1430 my $custnum = $session->{'custnum'};
1432 my $invnum = $p->{'invnum'};
1434 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1435 'custnum' => $custnum } )
1436 or return { 'error' => "Can't find invnum" };
1440 return { 'error' => '',
1441 'invnum' => $invnum,
1442 'invoice_text' => join('', $cust_bill->print_text ),
1443 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1450 my $session = _cache->get($p->{'session_id'})
1451 or return { 'error' => "Can't resume session" }; #better error message
1453 my $custnum = $session->{'custnum'};
1455 my $invnum = $p->{'invnum'};
1457 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1458 'custnum' => $custnum } )
1459 or return { 'error' => "Can't find invnum" };
1463 return { 'error' => '',
1464 'invnum' => $invnum,
1465 'invoice_pdf' => $cust_bill->print_pdf({
1466 'unsquelch_cdr' => 1,
1467 'locale' => $p->{'locale'},
1473 sub legacy_invoice {
1475 my $session = _cache->get($p->{'session_id'})
1476 or return { 'error' => "Can't resume session" }; #better error message
1478 my $custnum = $session->{'custnum'};
1480 my $legacyinvnum = $p->{'legacyinvnum'};
1483 'legacyinvnum' => $legacyinvnum,
1484 'custnum' => $custnum,
1487 my $legacy_cust_bill =
1488 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1489 || qsearchs('legacy_cust_bill', \%hash )
1490 or return { 'error' => "Can't find legacyinvnum" };
1494 return { 'error' => '',
1495 'legacyinvnum' => $legacyinvnum,
1496 'legacyid' => $legacy_cust_bill->legacyid,
1497 'invoice_html' => $legacy_cust_bill->content_html,
1502 sub legacy_invoice_pdf {
1504 my $session = _cache->get($p->{'session_id'})
1505 or return { 'error' => "Can't resume session" }; #better error message
1507 my $custnum = $session->{'custnum'};
1509 my $legacyinvnum = $p->{'legacyinvnum'};
1511 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1512 'legacyinvnum' => $legacyinvnum,
1513 'custnum' => $custnum,
1514 }) or return { 'error' => "Can't find legacyinvnum" };
1518 return { 'error' => '',
1519 'legacyinvnum' => $legacyinvnum,
1520 'legacyid' => $legacy_cust_bill->legacyid,
1521 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1529 #sessioning for this? how do we get the session id to the backend invoice
1530 # template so it can add it to the link, blah
1533 if ( $p->{'invnum'} ) {
1534 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1535 or return { 'error' => 'unknown invnum' };
1536 $agentnum = $cust_bill->cust_main->agentnum;
1539 my $templatename = $p->{'template'} || $p->{'templatename'};
1541 #false laziness-ish w/view/cust_bill-logo.cgi
1543 my $conf = new FS::Conf;
1544 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1545 $templatename = "_$1";
1550 my $filename = "logo$templatename.png";
1552 return { 'error' => '',
1553 'logo' => $conf->config_binary($filename, $agentnum),
1554 'content_type' => 'image/png', #should allow gif, jpg too
1561 my $session = _cache->get($p->{'session_id'})
1562 or return { 'error' => "Can't resume session" }; #better error message
1564 my $custnum = $session->{'custnum'};
1566 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1567 or return { 'error' => "unknown custnum $custnum" };
1569 my $conf = new FS::Conf;
1571 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1573 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1578 #not super efficient, we also run cust_bill_pay/cust_credited inside owed
1579 my @payments_and_credits = sort {$b->_date <=> $a->_date} ($_->cust_bill_pay,$_->cust_credited);
1580 my $owed = $_->owed;
1582 +{ 'invnum' => $_->invnum,
1583 '_date' => $_->_date,
1584 'date' => time2str("%b %o, %Y", $_->_date),
1585 'date_short' => time2str("%m-%d-%Y", $_->_date),
1586 'previous' => sprintf('%.2f', ($_->previous)[0]),
1587 'charged' => sprintf('%.2f', $_->charged),
1588 'owed' => sprintf('%.2f', $owed),
1589 'balance' => sprintf('%.2f', $balance),
1590 'lastpay' => @payments_and_credits
1591 ? time2str("%b %o, %Y", $payments_and_credits[0]->_date)
1597 return { 'error' => '',
1598 'balance' => $cust_main->balance,
1599 'money_char' => $conf->config("money_char") || '$',
1600 'invoices' => $invoices,
1601 'legacy_invoices' => [
1603 +{ 'legacyinvnum' => $_->legacyinvnum,
1604 'legacyid' => $_->legacyid,
1605 '_date' => $_->_date,
1606 'date' => time2str("%b %o, %Y", $_->_date),
1607 'date_short' => time2str("%m-%d-%Y", $_->_date),
1608 'charged' => sprintf('%.2f', $_->charged),
1609 'has_content' => ( length($_->content_pdf)
1610 || length($_->content_html) ),
1620 my $session = _cache->get($p->{'session_id'})
1621 or return { 'error' => "Can't resume session" }; #better error message
1623 my $custnum = $session->{'custnum'};
1625 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1626 or return { 'error' => "unknown custnum $custnum" };
1628 return { 'error' => '',
1629 'balance' => $cust_main->balance,
1630 'money_char' => FS::Conf->new->config("money_char") || '$',
1631 'payments' => [ map $_->SSAPI_getinfo, $cust_main->cust_pay ],
1635 sub payment_receipt {
1637 my $session = _cache->get($p->{'session_id'})
1638 or return { 'error' => "Can't resume session" }; #better error message
1640 my $custnum = $session->{'custnum'};
1642 my $cust_pay = qsearchs('cust_pay', { 'custnum' => $custnum,
1643 'paynum' => $p->{'paynum'},
1646 or return { 'error' => "unknown payment ". $p->{'paynum'} };
1650 %{ $cust_pay->SSAPI_getinfo },
1657 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1658 return { 'error' => $session } if $context eq 'error';
1660 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1661 or return { 'error' => "unknown custnum $custnum" };
1665 my $cust_payby = $_;
1667 map { $_ => $cust_payby->$_ }
1668 qw( custpaybynum weight payby paymask paydate
1669 payname paystate paytype
1673 $cust_main->cust_payby
1681 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1682 return { 'error' => $session } if $context eq 'error';
1684 #XXX payinfo1 + payinfo2 for CHEK?
1685 #or take the opportunity to use separate, more well- named fields?
1687 # $p->{'payinfo1'} =~ /^([\dx]+)$/
1688 # or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1689 # my $payinfo1 = $1;
1690 # $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
1691 # or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1692 # my $payinfo2 = $1;
1693 # $payinfo = $payinfo1. '@'. $payinfo2;
1695 my $cust_payby = new FS::cust_payby {
1696 'custnum' => $custnum,
1697 map { $_ => $p->{$_} } qw( weight payby payinfo paycvv paydate payname
1698 paystate paytype payip
1702 my $error = $cust_payby->insert;
1704 return { 'error' => $error };
1706 return { 'custpaybynum' => $cust_payby->custpaybynum };
1714 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1715 return { 'error' => $session } if $context eq 'error';
1717 my $cust_payby = qsearchs('cust_payby', {
1718 'custnum' => $custnum,
1719 'custpaybynum' => $p->{'custpaybynum'},
1721 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1724 qw( weight payby payinfo paycvv paydate payname paystate paytype payip )
1726 next unless exists($p->{$field});
1727 $cust_payby->set($field,$p->{$field});
1730 my $error = $cust_payby->replace;
1732 return { 'error' => $error };
1734 return { 'custpaybynum' => $cust_payby->custpaybynum };
1742 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1743 return { 'error' => $session } if $context eq 'error';
1745 my $cust_payby = qsearchs('cust_payby', {
1746 'custnum' => $custnum,
1747 'custpaybynum' => $p->{'custpaybynum'},
1749 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1751 return { 'error' => $cust_payby->verify };
1758 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1759 return { 'error' => $session } if $context eq 'error';
1761 my $cust_payby = qsearchs('cust_payby', {
1762 'custnum' => $custnum,
1763 'custpaybynum' => $p->{'custpaybynum'},
1765 or return { 'error' => 'unknown custpaybynum '. $p->{'custpaybynum'} };
1767 my $conf = new FS::Conf;
1768 if (($cust_payby->payby eq "DCHK" || $cust_payby->payby eq "CHEK") && $conf->exists('selfservice-ACH_info_readonly')) {
1769 return { 'error' => "Sorry you do not have permission to delete bank information." };
1772 return { 'error' => $cust_payby->delete };
1778 my $session = _cache->get($p->{'session_id'})
1779 or return { 'error' => "Can't resume session" }; #better error message
1781 my $custnum = $session->{'custnum'};
1783 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1784 or return { 'error' => "unknown custnum $custnum" };
1786 my @errors = $cust_main->cancel( 'quiet'=>1 );
1788 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1790 return { 'error' => $error };
1797 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1798 return { 'error' => $session } if $context eq 'error';
1800 my $pkg = qsearchs({
1801 'table' => 'cust_pkg',
1802 'addl_from' => 'LEFT JOIN part_pkg USING ( pkgpart )',
1804 'custnum' => $custnum,
1805 'pkgnum' => $p->{'pkgnum'},
1808 or return {'error' => 'unknown pkg num $pkgnum'};
1811 pkg_label => $pkg->pkg,
1812 pkgpart => $pkg->pkgpart,
1813 classnum => $pkg->classnum,
1821 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1822 return { 'error' => $session } if $context eq 'error';
1824 my $search = { 'custnum' => $custnum };
1825 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1826 my $cust_main = qsearchs('cust_main', $search )
1827 or return { 'error' => "unknown custnum $custnum" };
1829 my $conf = new FS::Conf;
1830 my $immutable = $conf->exists('selfservice_immutable-package');
1832 # the duplication below is necessary:
1833 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1834 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1835 # non-backwards-compatible change breaking the software of anyone using the API
1836 # instead of the stock selfservice
1837 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1838 if( $conf->exists('selfservice_server-view-wholesale') ) {
1839 return { 'svcnum' => $session->{'svcnum'},
1840 'custnum' => $custnum,
1841 'cust_pkg' => [ map {
1843 immutable => $immutable,
1844 part_pkg => [ map $_->hashref, $_->part_pkg ],
1846 [ map $_->hashref, $_->available_part_svc ],
1848 [ map { my $ref = { $_->hash,
1849 label => [ $_->label ],
1851 $ref->{_password} = $_->svc_x->_password
1852 if $context eq 'agent'
1853 && $conf->exists('agent-showpasswords')
1854 && $_->part_svc->svcdb eq 'svc_acct';
1859 } $cust_main->cust_pkg
1862 small_custview( $cust_main, $conf->config('countrydefault') ),
1863 'wholesale_view' => 1,
1864 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1865 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1866 'lnp' => $conf->exists('svc_phone-lnp'),
1870 { 'svcnum' => $session->{'svcnum'},
1871 'custnum' => $custnum,
1872 'cust_pkg' => [ map {
1873 my $primary_cust_svc = $_->primary_cust_svc;
1876 immutable => $immutable,
1877 pkg_label => $_->pkg_locale,
1878 status => $_->status,
1879 statuscolor => $_->statuscolor,
1881 [ map { $_->hashref }
1882 grep { $_->selfservice_access ne 'hidden' }
1883 $_->available_part_svc
1886 [ map { my $ref = { $_->hash,
1887 label => [ $_->label ],
1889 $ref->{_password} = $_->svc_x->_password
1890 if $context eq 'agent'
1891 && $conf->exists('agent-showpasswords')
1892 && $_->part_svc->svcdb eq 'svc_acct';
1893 $ref->{svchash} = { $_->svc_x->hash } if
1894 $_->part_svc->svcdb eq 'svc_phone';
1895 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1896 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1899 grep { $_->part_svc->selfservice_access ne 'hidden' }
1904 ? { $primary_cust_svc->hash,
1905 label => [ $primary_cust_svc->label ],
1906 finger => $primary_cust_svc->svc_x->finger, #uuh
1907 $primary_cust_svc->part_svc->hash,
1911 } $cust_main->ncancelled_pkgs
1914 small_custview( $cust_main, $conf->config('countrydefault') ),
1915 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1923 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1924 return { 'error' => $session } if $context eq 'error';
1926 my $conf = new FS::Conf;
1928 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1929 my $search = { 'custnum' => $custnum };
1930 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1931 my $cust_main = qsearchs('cust_main', $search )
1932 or return { 'error' => "unknown custnum $custnum" };
1934 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1935 if ( ! $pkgnum && $p->{'svcnum'} ) {
1936 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1937 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1941 my @cust_pkg_usage = ();
1942 foreach my $cust_pkg ( $p->{'ncancelled'}
1943 ? $cust_main->ncancelled_pkgs
1944 : $cust_main->unsuspended_pkgs ) {
1945 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1946 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1947 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1950 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1953 foreach (@cust_pkg_usage) {
1954 my $part = $_->part_pkg_usage;
1955 my $tag = $part->description . ($part->shared ? 1 : 0);
1956 my $row = $usage_pools{$tag}
1957 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1958 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1959 $row->[2] += $part->minutes; # minutes total
1961 } # otherwise just leave them empty
1963 if ( $p->{'svcdb'} ) {
1964 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1966 : ref($p->{'svcdb'}) eq 'ARRAY'
1967 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1968 : { $p->{'svcdb'} => 1 };
1969 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1972 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1975 my @svcs; # stuff to return to the client
1976 my %bytes_used_total; # for _used columns only
1977 foreach my $cust_svc (@cust_svc) {
1978 my $svc_x = $cust_svc->svc_x;
1979 my($label, $value) = $cust_svc->label;
1980 my $part_svc = $cust_svc->part_svc;
1981 my $svcdb = $part_svc->svcdb;
1982 my $cust_pkg = $cust_svc->cust_pkg;
1983 my $part_pkg = $cust_pkg->part_pkg;
1986 'svcnum' => $cust_svc->svcnum,
1987 'display_svcnum' => $cust_svc->display_svcnum,
1991 'pkg_label' => $cust_pkg->pkg_locale,
1992 'pkg_status' => $cust_pkg->status,
1993 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1996 # would it make sense to put this in a svc_* method?
1998 if (!$hide_usage and grep(/^$svcdb$/, qw(svc_acct svc_broadband)) and $part_svc->part_export_usage) {
1999 my $last_bill = $cust_pkg->last_bill || 0;
2001 my $up_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctInputOctets');
2002 my $down_used = $cust_svc->attribute_since_sqlradacct($last_bill,$now,'AcctOutputOctets');
2005 'seconds_used' => $cust_svc->seconds_since_sqlradacct($last_bill,$now),
2006 'upbytes_used' => display_bytecount($up_used),
2007 'downbytes_used' => display_bytecount($down_used),
2008 'totalbytes_used' => display_bytecount($up_used + $down_used)
2010 $bytes_used_total{'seconds_used'} += $hash{'seconds_used'};
2011 $bytes_used_total{'upbytes_used'} += $up_used;
2012 $bytes_used_total{'downbytes_used'} += $down_used;
2013 $bytes_used_total{'totalbytes_used'} += $up_used + $down_used;
2016 if ( $svcdb eq 'svc_acct' ) {
2017 foreach (qw(username email finger seconds)) {
2018 $hash{$_} = $svc_x->$_;
2024 'upbytes' => display_bytecount($svc_x->upbytes),
2025 'downbytes' => display_bytecount($svc_x->downbytes),
2026 'totalbytes' => display_bytecount($svc_x->totalbytes),
2028 'recharge_amount' => $part_pkg->option('recharge_amount',1),
2029 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
2030 'recharge_upbytes' =>
2031 display_bytecount($part_pkg->option('recharge_upbytes',1)),
2032 'recharge_downbytes' =>
2033 display_bytecount($part_pkg->option('recharge_downbytes',1)),
2034 'recharge_totalbytes' =>
2035 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
2040 } elsif ( $svcdb eq 'svc_dsl' ) {
2042 $hash{'phonenum'} = $svc_x->phonenum;
2043 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
2044 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
2045 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
2048 $hash{'name'} = $cust_main->name;
2050 # no usage to hide here
2052 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2054 # could potentially show lots of things...
2055 $hash{'outbound'} = 1;
2056 $hash{'inbound'} = 0;
2057 if ( $svcdb eq 'svc_phone' ) {
2058 if ( $part_pkg->plan eq 'voip_inbound' ) {
2059 $hash{'outbound'} = 0;
2060 $hash{'inbound'} = 1;
2061 } elsif ( $part_pkg->option('selfservice_inbound_format')
2062 or $conf->config('selfservice-default_inbound_cdr_format')
2064 $hash{'inbound'} = 1;
2067 foreach (qw(inbound outbound)) {
2068 # hmm...we can't filter by status here, because there might
2069 # not be cdr_terminations at all. have to go by date.
2070 # find all since the last bill date.
2071 # XXX cdr types? we are going to need them.
2073 my $sum_cdr = $svc_x->sum_cdrs(
2074 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
2075 'begin' => ($cust_pkg->last_bill || 0),
2077 'disable_charged_party' => 1,
2079 $hash{$_} = $sum_cdr->hashref;
2082 } # not hiding usage
2086 } # foreach $cust_svc
2088 foreach my $field (keys %bytes_used_total) {
2089 if ($field =~ /bytes/) {
2090 $bytes_used_total{$field} = display_bytecount($bytes_used_total{$field});
2095 'svcnum' => $session->{'svcnum'},
2096 'custnum' => $custnum,
2097 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
2098 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
2100 'bytes_used_total' => \%bytes_used_total,
2102 map { $usage_pools{$_} }
2106 'hide_usage' => $hide_usage,
2111 sub _customer_svc_x {
2112 my($custnum, $svcnum, $table) = (shift, shift, shift);
2113 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
2115 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2116 my $search = " AND custnum = $1";
2117 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2120 'table' => ($table || 'svc_acct'),
2121 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2122 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
2123 #'LEFT JOIN cust_main USING ( custnum ) ',
2124 'hashref' => $hashref,
2125 'extra_sql' => $search, #important
2130 sub svc_status_html {
2133 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2134 return { 'error' => $session } if $context eq 'error';
2136 #XXX only svc_dsl for now
2137 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
2138 or return { 'error' => "Service not found" };
2140 my $html = $svc_x->getstatus_html;
2142 return { 'html' => $html };
2146 sub svc_status_hash {
2149 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2150 return { 'error' => $session } if $context eq 'error';
2152 #XXX only svc_acct for now
2153 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2154 or return { 'error' => "Service not found" };
2156 my ( $html, $hashref ) = $svc_x->export_getstatus;
2161 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
2162 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
2163 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
2164 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
2165 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
2168 my( $p, $method ) = @_;
2170 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2171 return { 'error' => $session } if $context eq 'error';
2173 #XXX only svc_acct for now
2174 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
2175 or return { 'error' => "Service not found" };
2177 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
2179 my $error = $svc_x->$method($p); #$p? returns error?
2180 return { 'error' => $error } if $error;
2182 return {}; #? { 'error' => '' }
2186 sub acct_forward_info {
2189 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2190 return { 'error' => $session } if $context eq 'error';
2192 my $svc_forward = _customer_svc_x( $custnum,
2193 { 'srcsvc' => $p->{'svcnum'} },
2196 or return { 'error' => '',
2200 return { 'error' => '',
2201 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2206 sub process_acct_forward {
2208 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2209 return { 'error' => $session } if $context eq 'error';
2211 my $old = _customer_svc_x( $custnum,
2212 { 'srcsvc' => $p->{'svcnum'} },
2216 if ( $p->{'dst'} eq '' ) {
2218 my $error = $old->delete;
2219 return { 'error' => $error };
2221 return { 'error' => '' };
2224 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2225 'dst' => $p->{'dst'},
2230 $new->svcnum($old->svcnum);
2231 my $cust_svc = $old->cust_svc;
2232 $new->svcpart($old->svcpart);
2233 $new->pkgnuym($old->pkgnum);
2234 $error = $new->replace($old);
2236 my $conf = new FS::Conf;
2237 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2239 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2240 or return { 'error' => 'No service' }; #how would we even get here?
2242 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2244 $error = $new->insert;
2247 return { 'error' => $error };
2251 sub list_dsl_devices {
2254 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2255 return { 'error' => $session } if $context eq 'error';
2257 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2258 or return { 'error' => "Service not found" };
2261 'devices' => [ map {
2262 +{ 'mac_addr' => $_->mac_addr };
2263 } $svc_dsl->dsl_device
2269 sub add_dsl_device {
2272 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2273 return { 'error' => $session } if $context eq 'error';
2275 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2276 or return { 'error' => "Service not found" };
2278 return { 'error' => 'No MAC address supplied' }
2279 unless length($p->{'mac_addr'});
2281 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2282 'mac_addr' => scalar($p->{'mac_addr'}),
2284 my $error = $dsl_device->insert;
2285 return { 'error' => $error };
2289 sub delete_dsl_device {
2292 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2293 return { 'error' => $session } if $context eq 'error';
2295 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2296 or return { 'error' => "Service not found" };
2298 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2299 'mac_addr' => scalar($p->{'mac_addr'}),
2302 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2304 my $error = $dsl_device->delete;
2305 return { 'error' => $error };
2311 _usage_details( \&_port_graph, $p,
2312 'svcdb' => 'svc_port',
2317 my($svc_port, $begin, $end) = @_;
2319 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2320 push @usage, { 'png' => $pngOrError };
2324 sub _list_svc_usage {
2325 my($svc_acct, $begin, $end) = @_;
2327 foreach my $part_export (
2328 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2329 qw( sqlradius sqlradius_withdomain )
2331 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2336 sub list_svc_usage {
2337 _usage_details(\&_list_svc_usage, @_);
2340 sub _list_support_usage {
2341 my($svc_acct, $begin, $end) = @_;
2343 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2344 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2346 push @usage, { 'seconds' => $_->seconds,
2347 'support' => $_->support,
2348 '_date' => $_->_date,
2349 'id' => $_->transaction_id,
2350 'creator' => $_->creator,
2351 'subject' => $_->subject,
2352 'status' => $_->status,
2353 'ticketid' => $_->ticketid,
2359 sub list_support_usage {
2360 _usage_details(\&_list_support_usage, @_);
2363 sub _list_cdr_usage {
2364 # XXX CDR type support...
2365 # XXX any way to do a paged search on this?
2366 # we have to return the results all at once...
2367 my($svc_x, $begin, $end, %opt) = @_;
2368 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2372 'disable_charged_party' => 1,
2377 sub list_cdr_usage {
2379 _usage_details( \&_list_cdr_usage, $p );
2382 sub _usage_details {
2383 my($callback, $p, %opt) = @_;
2384 my $conf = FS::Conf->new;
2386 if ( $conf->exists('selfservice_hide-usage') ) {
2387 return { 'error' => 'Viewing usage is not allowed.' };
2390 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2391 return { 'error' => $session } if $context eq 'error';
2393 my $search = { 'svcnum' => $p->{'svcnum'} };
2394 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2396 my $cust_svc = qsearchs( 'cust_svc', $search );
2397 return { 'error' => 'No service selected in list_svc_usage' }
2400 my $svc_x = $cust_svc->svc_x;
2401 my $svcdb = $svc_x->table;
2402 my $cust_pkg = $cust_svc->cust_pkg;
2403 my $freq = $cust_pkg->part_pkg->freq;
2406 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2408 if ( $p->{inbound} ) {
2409 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2410 || $conf->config('selfservice-default_inbound_cdr_format')
2411 || 'source_default';
2412 $callback_opt{inbound} = 1;
2414 $format = $cust_pkg->part_pkg->option('selfservice_format')
2415 || $conf->config('selfservice-default_cdr_format')
2419 $callback_opt{format} = $format;
2420 $callback_opt{use_clid} = 1;
2421 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2424 my $start = $cust_pkg->setup;
2425 #my $end = $cust_pkg->bill; # or time?
2428 unless ( $p->{beginning} ) {
2429 $p->{beginning} = $cust_pkg->last_bill;
2430 $p->{ending} = $end;
2433 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2434 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2436 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2440 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2441 # ugly kludge, I know
2442 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2443 if (defined $delete_col) {
2444 delete($_->[$delete_col]) foreach ($header, @usage);
2448 #kinda false laziness with FS::cust_main::bill, but perhaps
2449 #we should really change this bit to DateTime and DateTime::Duration
2451 #change this bit to use Date::Manip? CAREFUL with timezones (see
2452 # mailing list archive)
2453 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2454 (localtime($p->{ending}) )[0,1,2,3,4,5];
2455 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2456 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2458 if ( $freq =~ /^\d+$/ ) {
2460 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2462 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2463 } elsif ( $freq =~ /^(\d+)w$/ ) {
2465 $nmday += $weeks * 7;
2466 $pmday -= $weeks * 7;
2467 } elsif ( $freq =~ /^(\d+)d$/ ) {
2471 } elsif ( $freq =~ /^(\d+)h$/ ) {
2476 return { 'error' => "unparsable frequency: ". $freq };
2479 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2480 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2484 'svcnum' => $p->{svcnum},
2485 'beginning' => $p->{beginning},
2486 'ending' => $p->{ending},
2487 'inbound' => $p->{inbound},
2488 'previous' => ($previous > $start) ? $previous : $start,
2489 'next' => ($next < $end) ? $next : $end,
2490 'header' => $header,
2498 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2499 return { 'error' => $session } if $context eq 'error';
2501 my $search = { 'custnum' => $custnum };
2502 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2503 my $cust_main = qsearchs('cust_main', $search )
2504 or return { 'error' => "unknown custnum $custnum" };
2506 my $status = $cust_main->status;
2508 my %order_pkg_options = ();
2509 if ( $p->{locationnum} > 0 ) {
2510 $order_pkg_options{locationnum} = delete($p->{locationnum});
2511 } elsif ( $p->{address1} ) {
2512 $order_pkg_options{'cust_location'} = new FS::cust_location {
2513 map { $_ => $p->{$_} }
2514 qw( address1 address2 city county state zip country )
2518 #false laziness w/ClientAPI/Signup.pm
2520 my $cust_pkg = new FS::cust_pkg ( {
2521 'custnum' => $custnum,
2522 'pkgpart' => $p->{'pkgpart'},
2523 'quantity' => $p->{'quantity'} || 1,
2525 my $error = $cust_pkg->check;
2526 return { 'error' => $error } if $error;
2529 unless ( $p->{'svcpart'} eq 'none' ) {
2533 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2535 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2536 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2537 $svcdb = $part_svc->svcdb;
2539 $svcdb = 'svc_acct';
2541 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2544 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2545 'svc_domain' => [ qw( domain ) ],
2546 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2547 'svc_external' => [ qw( id title ) ],
2548 'svc_pbx' => [ qw( id title ) ],
2551 my $svc_x = "FS::$svcdb"->new( {
2552 'svcpart' => $svcpart,
2553 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2556 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2559 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2560 my $acct_snarf = new FS::acct_snarf ( {
2561 'machine' => $p->{"snarf_machine$snarfnum"},
2562 'protocol' => $p->{"snarf_protocol$snarfnum"},
2563 'username' => $p->{"snarf_username$snarfnum"},
2564 '_password' => $p->{"snarf_password$snarfnum"},
2567 push @acct_snarf, $acct_snarf;
2569 $svc_x->child_objects( \@acct_snarf );
2572 my $y = $svc_x->setdefault; # arguably should be in new method
2573 return { 'error' => $y } if $y && !ref($y);
2575 $error = $svc_x->check;
2576 return { 'error' => $error } if $error;
2582 $error = $cust_main->order_pkg(
2583 'cust_pkg' => $cust_pkg,
2588 return { 'error' => $error } if $error;
2590 my $conf = new FS::Conf;
2591 if ( $conf->exists('signup_server-realtime') ) {
2593 my $bill_error = _do_bop_realtime( $cust_main, $status, 'collect'=>$p->{run_bill_events} );
2596 $cust_pkg->cancel('quiet'=>1);
2599 $cust_pkg->reexport;
2603 $cust_pkg->reexport;
2606 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2608 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2615 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2616 return { 'error' => $session } if $context eq 'error';
2618 my $conf = new FS::Conf;
2619 my $immutable = $conf->exists('selfservice_immutable-package');
2620 return { 'error' => "Package modification disabled" } if $immutable;
2622 my $search = { 'custnum' => $custnum };
2623 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2624 my $cust_main = qsearchs('cust_main', $search )
2625 or return { 'error' => "unknown custnum $custnum" };
2627 my $status = $cust_main->status;
2628 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2629 or return { 'error' => "unknown package $p->{pkgnum}" };
2631 #if someone does need self-service package change of suspended packages,
2632 # figure out how to be more discriminating
2633 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2634 if $cust_pkg->status eq 'suspended';
2636 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2637 'quantity' => $p->{'quantity'} || 1,
2640 my $new_pkg = qsearchs('part_pkg', { 'pkgpart' => $p->{pkgpart} } )
2641 or return { 'error' => "unknown package $p->{pkgpart}" };
2643 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2644 unless ref($err_or_cust_pkg);
2647 if ( $conf->exists('signup_server-realtime') ) {
2649 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_invoice_void'=>1 );
2652 $err_or_cust_pkg->suspend;
2655 $err_or_cust_pkg->reexport;
2659 $err_or_cust_pkg->reexport;
2662 return { error => '', pkg => $new_pkg->pkg, pkgnum => $err_or_cust_pkg->pkgnum };
2666 sub order_recharge {
2669 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2670 return { 'error' => $session } if $context eq 'error';
2672 my $search = { 'custnum' => $custnum };
2673 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2674 my $cust_main = qsearchs('cust_main', $search )
2675 or return { 'error' => "unknown custnum $custnum" };
2677 my $status = $cust_main->status;
2678 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2679 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2681 my $svc_x = $cust_svc->svc_x;
2682 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2685 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2686 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2687 recharge_totalbytes );
2688 my $amount = $part_pkg->option('recharge_amount', 1);
2690 my ($l, $v, $d) = $cust_svc->label; # blah
2691 my $pkg = "Recharge $v";
2693 my $bill_error = $cust_main->charge($amount, $pkg,
2694 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2695 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2696 $part_pkg->taxclass); #meh
2698 my $conf = new FS::Conf;
2699 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2701 $bill_error = _do_bop_realtime( $cust_main, $status );
2706 my $error = $svc_x->recharge (\%vhash);
2707 return { 'error' => $error } if $error;
2711 my $error = $bill_error;
2712 $error ||= $svc_x->recharge (\%vhash);
2713 return { 'error' => $error } if $error;
2716 return { error => '', svc => $cust_svc->part_svc->svc };
2720 sub _do_bop_realtime {
2721 my ($cust_main, $status, %opt) = @_;
2723 my $old_balance = $cust_main->balance;
2726 my $bill_error = $cust_main->bill(
2727 'return_bill' => \@cust_bill,
2730 $bill_error ||= $cust_main->apply_payments_and_credits;
2732 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2733 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2735 if ( $cust_main->balance > $old_balance
2736 && $cust_main->balance > 0
2737 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2738 || $status eq 'suspended'
2742 unless ( $opt{'no_invoice_void'} ) {
2744 #this used to apply a credit, but now we can void invoices...
2745 foreach my $cust_bill (@cust_bill) {
2746 my $voiderror = $cust_bill->void('automatic payment failed');
2747 warn "Error voiding cust bill after decline: $voiderror" if $voiderror;
2752 return { 'error' => '_decline', 'bill_error' => $bill_error };
2755 if ( $opt{'collect'} ) {
2756 my $collect_error = $cust_main->collect();
2757 return { 'error' => '_decline', 'bill_error' => $collect_error }
2758 if $collect_error; #?
2767 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2768 return { 'error' => $session } if $context eq 'error';
2770 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2771 or return { 'error' => "unknown custnum $custnum" };
2773 my @cust_pkg = sort { $a->bill <=> $b->bill }
2774 grep { $_->part_pkg->freq ne '0' }
2775 $cust_main->ncancelled_pkgs;
2777 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2779 my $total = $cust_main->balance;
2782 my $bill = $_->bill;
2783 $total += $_->part_pkg->base_recur($_, \$bill);
2784 my $renew_date = $_->part_pkg->add_freq($_->bill);
2786 'pkgnum' => $_->pkgnum,
2787 'amount' => sprintf('%.2f', $total),
2788 'bill_date' => $_->bill,
2789 'bill_date_pretty' => time2str('%x', $_->bill),
2790 'renew_date' => $renew_date,
2791 'renew_date_pretty' => time2str('%x', $renew_date),
2792 'expire_date' => $_->expire,
2793 'expire_date_pretty' => time2str('%x', $_->expire),
2798 return { 'dates' => \@array };
2802 sub payment_info_renew_info {
2804 my $renew_info = renew_info($p);
2805 my $payment_info = payment_info($p);
2806 return { %$renew_info,
2814 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2815 return { 'error' => $session } if $context eq 'error';
2817 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2818 or return { 'error' => "unknown custnum $custnum" };
2820 my $date = $p->{'date'};
2824 #freeside-daily -n -d $date fs_daily $custnum
2825 $cust_main->bill_and_collect( 'time' => $date,
2826 'invoice_time' => $now,
2827 'actual_time' => $now,
2828 'check_freq' => '1d',
2831 return { 'error' => '' };
2837 my $session = _cache->get($p->{'session_id'})
2838 or return { 'error' => "Can't resume session" }; #better error message
2840 my $custnum = $session->{'custnum'};
2842 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2843 or return { 'error' => "unknown custnum $custnum" };
2845 my $conf = new FS::Conf;
2847 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2848 or return { 'error' => 'Permission denied' };
2850 my $pkgnum = $p->{'pkgnum'};
2852 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2853 'pkgnum' => $pkgnum, } )
2854 or return { 'error' => "unknown pkgnum $pkgnum" };
2856 my $error = $cust_pkg->suspend(reason => $reasonnum);
2857 return { 'error' => $error };
2863 my $session = _cache->get($p->{'session_id'})
2864 or return { 'error' => "Can't resume session" }; #better error message
2866 my $custnum = $session->{'custnum'};
2867 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2868 or return { 'error' => "unknown custnum $custnum" };
2870 my $pkgnum = $p->{'pkgnum'};
2871 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2872 'pkgnum' => $pkgnum, } )
2873 or return { 'error' => "unknown pkgnum $pkgnum" };
2875 my $error = $cust_pkg->cancel( 'quiet' => 1,
2876 'date' => $p->{'date'},
2878 return { 'error' => $error };
2881 sub provision_phone {
2884 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2886 #editing an existing phone number
2887 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2888 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2889 return { 'error' => $session } if $context eq 'error';
2891 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2892 return { 'error' => 'service not found' } unless $svc_phone;
2893 return { 'error' => 'invalid svcnum' }
2894 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2896 $svc_phone->email($p->{'email'})
2897 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2898 $svc_phone->forwarddst($p->{'forwarddst'})
2899 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2900 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2901 return { 'error' => $svc_phone->replace };
2905 unless ( $p->{'lnp'} ) {
2906 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2907 $p->{'lnp_status'} = "portingin";
2908 return _provision( 'FS::svc_phone',
2909 [qw(lnp_desired_due_date lnp_other_provider
2910 lnp_other_provider_account phonenum countrycode lnp_status)],
2911 [qw(phonenum countrycode)],
2917 # single DID order (the usual case)
2918 unless (scalar(@bulkdid)) {
2919 return _provision( 'FS::svc_phone',
2920 [qw(phonenum countrycode)],
2921 [qw(phonenum countrycode)],
2927 # bulk DID order case
2929 foreach my $did ( @bulkdid ) {
2930 $did =~ s/[^0-9]//g;
2931 $error = _provision( 'FS::svc_phone',
2932 [qw(phonenum countrycode)],
2933 [qw(phonenum countrycode)],
2935 'pkgnum' => $p->{'pkgnum'},
2936 'svcpart' => $p->{'svcpart'},
2938 'countrycode' => $p->{'countrycode'},
2939 'session_id' => $p->{'session_id'},
2942 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2944 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2949 warn "provision_pbx called\n"
2952 warn "provision_pbx calling _provision\n"
2954 _provision( 'FS::svc_pbx',
2955 [qw(id title max_extensions max_simultaneous ip_addr)],
2956 [qw(id title max_extensions max_simultaneous ip_addr)],
2962 sub provision_acct {
2964 warn "provision_acct called\n"
2967 return { 'error' => gettext('passwords_dont_match') }
2968 if $p->{'_password'} ne $p->{'_password2'};
2969 return { 'error' => gettext('empty_password') }
2970 unless length($p->{'_password'});
2972 if ($p->{'domsvc'}) {
2973 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2974 qw ( svcpart pkgnum ) );
2975 return { 'error' => gettext('invalid_domain') }
2976 unless ($domains{$p->{'domsvc'}});
2979 warn "provision_acct calling _provision\n"
2981 _provision( 'FS::svc_acct',
2982 [qw(username _password domsvc)],
2983 [qw(username _password domsvc)],
2989 sub provision_external {
2991 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2992 _provision( 'FS::svc_external',
3000 sub provision_forward {
3002 _provision( 'FS::svc_forward',
3003 ['srcsvc','src','dstsvc','dst'],
3010 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
3011 warn "_provision called for $class\n"
3014 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3015 return { 'error' => $session } if $context eq 'error';
3017 my $search = { 'custnum' => $custnum };
3018 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3019 my $cust_main = qsearchs('cust_main', $search )
3020 or return { 'error' => "unknown custnum $custnum" };
3022 my $pkgnum = $p->{'pkgnum'};
3024 warn "searching for custnum $custnum pkgnum $pkgnum\n"
3026 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3027 'pkgnum' => $pkgnum,
3029 or return { 'error' => "unknown pkgnum $pkgnum" };
3031 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
3033 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
3034 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
3036 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
3037 if $class ne 'FS::'. $part_svc->svcdb;
3039 warn "creating $class record\n"
3041 my $svc_x = $class->new( {
3042 'pkgnum' => $p->{'pkgnum'},
3043 'svcpart' => $p->{'svcpart'},
3044 map { $_ => $p->{$_} } @$fields
3047 my %insert_args = ();
3048 #i shouldn't be a special case here (pass an option or something)
3049 if ( $class eq 'FS::svc_phone'
3050 && grep length($p->{$_}), @location_editable_fields
3053 $insert_args{'cust_location'} = new FS::cust_location {
3054 map { $_ => $p->{$_} } @location_editable_fields
3058 warn "inserting $class record\n"
3060 my $error = $svc_x->insert(%insert_args);
3063 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
3065 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
3068 my $return = { 'svc' => $part_svc->svc,
3070 map { $_ => $svc_x->get($_) } @$return_fields
3072 warn "_provision returning ". Dumper($return). "\n"
3081 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3082 return { 'error' => $session } if $context eq 'error';
3084 my $search = { 'custnum' => $custnum };
3085 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3086 my $cust_main = qsearchs('cust_main', $search )
3087 or return { 'error' => "unknown custnum $custnum" };
3089 my $pkgnum = $p->{'pkgnum'};
3091 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3092 'pkgnum' => $pkgnum,
3094 or return { 'error' => "unknown pkgnum $pkgnum" };
3096 my $svcpart = $p->{'svcpart'};
3098 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
3099 'svcpart' => $svcpart, } )
3100 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
3101 my $part_svc = $pkg_svc->part_svc;
3103 my $conf = new FS::Conf;
3106 'svc' => $part_svc->svc,
3107 'svcdb' => $part_svc->svcdb,
3108 'pkgnum' => $pkgnum,
3109 'svcpart' => $svcpart,
3110 'custnum' => $custnum,
3112 'security_phrase' => 0, #XXX !
3113 'svc_acct_pop' => [], #XXX !
3115 'init_popstate' => '',
3120 small_custview( $cust_main, $conf->config('countrydefault') ),
3124 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
3125 && $ret->{'svcdb'} eq 'svc_phone') {
3126 $ret->{'svcnum'} = $p->{'svcnum'};
3127 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
3128 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
3129 $ret->{'email'} = $svc_phone->email;
3130 $ret->{'forwarddst'} = $svc_phone->forwarddst;
3134 if ($ret->{'svcdb'} eq 'svc_forward') {
3135 $ret->{'forward_emails'} = {$cust_pkg->forward_emails()};
3141 sub unprovision_svc {
3144 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3145 return { 'error' => $session } if $context eq 'error';
3147 my $search = { 'custnum' => $custnum };
3148 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3149 my $cust_main = qsearchs('cust_main', $search )
3150 or return { 'error' => "unknown custnum $custnum" };
3152 my $svcnum = $p->{'svcnum'};
3154 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
3155 or return { 'error' => "unknown svcnum $svcnum" };
3157 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
3158 unless $cust_svc->cust_pkg->custnum == $custnum;
3160 my $conf = new FS::Conf;
3162 return { 'svc' => $cust_svc->part_svc->svc,
3163 'error' => $cust_svc->cancel,
3165 small_custview( $cust_main, $conf->config('countrydefault') ),
3170 sub myaccount_passwd {
3172 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3173 return { 'error' => $session } if $context eq 'error';
3175 return { 'error' => "New passwords don't match." }
3176 if $p->{'new_password'} ne $p->{'new_password2'};
3178 return { 'error' => 'Enter new password' }
3179 unless length($p->{'new_password'});
3181 #my $search = { 'custnum' => $custnum };
3182 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3183 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3184 my $search = " AND custnum = $1";
3185 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3187 my $svc_acct = qsearchs( {
3188 'table' => 'svc_acct',
3189 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3190 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3191 'LEFT JOIN cust_main USING ( custnum ) ',
3192 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3193 'extra_sql' => $search, #important
3195 or return { 'error' => "Service not found" };
3199 my $conf = new FS::Conf;
3201 return { 'error' => 'Incorrect current password.' }
3202 if ( exists($p->{'old_password'})
3203 || $conf->exists('selfservice-password_change_oldpass')
3205 && ! $svc_acct->check_password($p->{'old_password'});
3207 $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3208 || $svc_acct->set_password($p->{'new_password'})
3209 || $svc_acct->replace();
3211 #regular pw change in self-service should change contact pw too, otherwise its
3212 #way too confusing. hell its confusing they're separate at all, but alas.
3213 #need to support the "ISP provides email that's used as a contact email" case
3215 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
3216 if ( $contact && $contact->custnum == $custnum ) {
3217 #svc_acct was successful but this one returns an error? "shouldn't happen"
3218 #don't recheck is_password_allowed here; if the svc_acct password was
3219 #legal, that's good enough
3220 $error ||= $contact->change_password($p->{'new_password'});
3223 my($label, $value) = $svc_acct->cust_svc->label;
3225 return { 'error' => $error,
3235 my $info = skin_info($p);
3237 my $conf = new FS::Conf;
3238 my $verification = $conf->config('selfservice-password_reset_verification')
3239 or return { %$info, 'error' => 'Password resets disabled' };
3244 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3246 $contact = FS::contact->by_selfservice_email($p->{'email'});
3248 $cust_main = $contact->cust_main if $contact;
3250 #also look for an svc_acct, otherwise it would be super confusing
3252 my($username, $domain) = split('@', $p->{'email'});
3253 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3254 if ( $svc_domain ) {
3255 $svc_acct = qsearchs('svc_acct', { 'username' => $username,
3256 'domsvc' => $svc_domain->svcnum }
3259 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3260 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3262 #precaution: don't change svc_acct password not part of the same
3263 # customer as contact
3264 $svc_acct = '' if ! $cust_pkg
3265 || $cust_pkg->custnum != $cust_main->custnum;
3270 return { %$info, 'error' => 'Email address not found' }
3271 unless $contact || $svc_acct;
3273 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3275 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3276 or return { %$info, 'error' => 'Account not found' };
3278 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3279 'domsvc' => $svc_domain->svcnum }
3281 or return { %$info, 'error' => 'Account not found' };
3283 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3284 or return { %$info, 'error' => 'Account not found' };
3286 $cust_main = $cust_pkg->cust_main;
3291 'email' => sub { 1; },
3293 my( $p, $cust_main ) = @_;
3294 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3295 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3298 my( $p, $cust_main ) = @_;
3299 my $cust_pay = qsearchs({
3300 'table' => 'cust_pay',
3301 'hashref' => { 'custnum' => $cust_main->custnum },
3302 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3306 $p->{'amount'} == $cust_pay->paid;
3309 my( $p, $cust_main ) = @_;
3310 $p->{'zip'} eq $cust_main->zip
3311 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3315 foreach my $verify ( split(',', $verification) ) {
3317 &{ $verify{$verify} }( $p, $cust_main )
3318 or return { %$info, 'error' => 'Account not found' };
3322 #okay, we're verified
3326 my $error = $contact->send_reset_email(
3327 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3331 return { %$info, 'error' => $error }; #????
3334 } elsif ( $svc_acct ) {
3336 #create a unique session
3338 my $reset_session = {
3339 'svcnum' => $svc_acct->svcnum,
3340 'agentnum' => $svc_acct->cust_main->agentnum,
3343 my $timeout = '1 hour'; #?
3345 my $reset_session_id;
3347 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3348 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3351 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3355 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3356 $cust_main->agentnum);
3357 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3358 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3360 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3361 my $error = $msg_template->send( 'cust_main' => $cust_main,
3362 'object' => $svc_acct,
3363 'substitutions' => {
3364 'session_id' => $reset_session_id,
3368 return { %$info, 'error' => $error }; #????
3373 return { %$info, 'error' => '' };
3376 sub check_reset_passwd {
3379 my $conf = new FS::Conf;
3380 my $verification = $conf->config('selfservice-password_reset_verification')
3381 or return { 'error' => 'Password resets disabled' };
3383 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3384 or return { 'error' => "Can't resume session" }; #better error message
3386 if ( $reset_session->{'svcnum'} ) {
3388 my $svcnum = $reset_session->{'svcnum'};
3390 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3391 or return { 'error' => "Service not found" };
3393 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3394 my $info = skin_info($p);
3398 'session_id' => $p->{'session_id'},
3399 'username' => $svc_acct->username,
3402 } elsif ( $reset_session->{'contactnum'} ) {
3404 my $contactnum = $reset_session->{'contactnum'};
3406 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3407 or return { 'error' => "Contact not found" };
3409 my @contact_email = $contact->contact_email;
3410 return { 'error' => 'No contact email' } unless @contact_email;
3412 $p->{'agentnum'} = $contact->cust_main->agentnum;
3413 my $info = skin_info($p);
3417 'session_id' => $p->{'session_id'},
3418 'email' => $contact_email[0]->email, #the first?
3423 return { 'error' => 'No svcnum or contactnum in session' }; #??
3429 sub process_reset_passwd {
3432 my $conf = new FS::Conf;
3433 my $verification = $conf->config('selfservice-password_reset_verification')
3434 or return { 'error' => 'Password resets disabled' };
3436 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3437 or return { 'error' => "Can't resume session" }; #better error message
3442 if ( $reset_session->{'svcnum'} ) {
3444 my $svcnum = $reset_session->{'svcnum'};
3446 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3447 or return { 'error' => "Service not found" };
3449 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3450 $info ||= skin_info($p);
3455 if ( $reset_session->{'contactnum'} ) {
3457 my $contactnum = $reset_session->{'contactnum'};
3459 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3460 or return { 'error' => "Contact not found" };
3462 $p->{'agentnum'} ||= $contact->cust_main->agentnum;
3463 $info ||= skin_info($p);
3467 return { %$info, 'error' => "New passwords don't match." }
3468 if $p->{'new_password'} ne $p->{'new_password2'};
3470 return { %$info, 'error' => 'Enter new password' }
3471 unless length($p->{'new_password'});
3475 my $error ||= $svc_acct->is_password_allowed($p->{'new_password'})
3476 || $svc_acct->set_password($p->{'new_password'})
3477 || $svc_acct->replace();
3479 return { %$info, 'error' => $error } if $error;
3481 #my($label, $value) = $svc_acct->cust_svc->label;
3482 #return { 'error' => $error,
3483 # #'label' => $label,
3484 # #'value' => $value,
3491 my $error = $contact->is_password_allowed($p->{'new_password'})
3492 || $contact->change_password($p->{'new_password'});
3494 return { %$info, 'error' => $error }; # if $error;
3498 #password changed ,so remove session, don't want it reused
3499 _cache->remove($p->{'session_id'});
3501 return { %$info, 'error' => '' };
3505 sub validate_passwd {
3509 %result = ( 'fieldid' => $p->{'fieldid'} )
3510 if $p->{'fieldid'} =~ /^\w+$/;
3512 return { %result, 'password_invalid' => 'Enter new password' }
3513 unless length($p->{'check_password'});
3516 if ($p->{'svcnum'}) {
3517 # false laziness with myaccount_passwd
3518 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3519 return { %result, 'error' => $session } if $context eq 'error';
3521 $custnum =~ /^(\d+)$/ or die "illegal custnum";
3522 my $search = " AND custnum = $1";
3523 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3525 $svc_acct = qsearchs( {
3526 'table' => 'svc_acct',
3527 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
3528 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
3529 'LEFT JOIN cust_main USING ( custnum ) ',
3530 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
3531 'extra_sql' => $search, #important
3533 or return { %result, 'error' => "Service not found" };
3534 # end false laziness
3537 unless ($svc_acct) {
3538 my $conf = new FS::Conf;
3539 my $agentnum = $p->{'agentnum'};
3540 return { %result, 'password_valid' => 1 }
3541 if $conf->config_bool('password-insecure', $p->{'agentnum'});
3544 $svc_acct ||= new FS::svc_acct {};
3546 my $error = $svc_acct->is_password_allowed($p->{'check_password'});
3547 return { %result, 'password_invalid' => $error } if $error;
3548 return { %result, 'password_valid' => 1 };
3553 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3554 return { 'error' => $session } if $context eq 'error';
3557 if ( $session->{'pkgnum'} ) {
3559 #tickets for specific service with pkg-balances on
3560 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3561 'pkgnum' => $session->{'pkgnum'} })
3562 or return { 'error' => 'unknown package' };
3563 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3564 push @tickets, $cust_svc->tickets( $p->{status} );
3569 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3570 or return { 'error' => "unknown custnum $custnum" };
3572 @tickets = $cust_main->tickets( $p->{status} );
3575 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3576 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3577 my $conf = new FS::Conf;
3578 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3582 ($a->{'_selfservice_priority'} eq '') <=>
3583 ($b->{'_selfservice_priority'} eq '')
3586 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3592 +{ tickets => \@tickets };
3599 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3600 return { 'error' => $session } if $context eq 'error';
3602 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3603 FS::TicketSystem->init();
3605 my $conf = new FS::Conf;
3606 my $queue = $p->{'queue'}
3607 || $conf->config('ticket_system-selfservice_queueid')
3608 || $conf->config('ticket_system-default_queueid');
3610 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3611 my $err_or_ticket = FS::TicketSystem->create_ticket(
3612 '', #create RT session based on FS CurrentUser (fs_selfservice)
3614 'custnum' => $custnum,
3615 'svcnum' => $session->{'svcnum'},
3616 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3619 if ( ref($err_or_ticket) ) {
3620 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3622 return { 'error' => '',
3623 'ticket_id' => $err_or_ticket->id,
3626 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3628 return { 'error' => $err_or_ticket };
3636 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3637 return { 'error' => $session } if $context eq 'error';
3639 return { error => 'requested format not implemented' }
3640 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3642 my $conf = new FS::Conf;
3643 my $age_threshold = 0;
3644 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3645 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3647 my $search = { 'custnum' => $custnum };
3648 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3649 my $cust_main = qsearchs('cust_main', $search )
3650 or return { 'error' => "unknown custnum $custnum" };
3652 # does it make more sense to just run one sql query for this instead of all the
3653 # insanity below? would increase performance greately for large data sets?
3655 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3656 my @part_svc = $cust_pkg->part_svc;
3657 foreach my $part_svc ( @part_svc ) {
3658 if($part_svc->svcdb eq 'svc_phone'){
3659 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3660 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3661 push @svc_phone, $cust_pkg_svc->svc_x
3662 if $cust_pkg_svc->date_inserted >= $age_threshold;
3670 my($xls_r,$xls_c) = (0,0);
3673 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3674 if($p->{'format'} eq 'csv') {
3675 $csv = new Text::CSV_XS { 'always_quote' => 1,
3678 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3679 $content .= $csv->string;
3681 elsif($p->{'format'} eq 'xls') {
3682 my $XLS1 = new IO::Scalar \$content;
3683 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3684 or return { 'error' => "Error opening .xls file: $!" };
3685 $xls = $xls_workbook->add_worksheet('DIDs');
3686 foreach ( @fields ) {
3687 $xls->write(0,$xls_c++,$_);
3692 foreach my $svc_phone ( @svc_phone ) {
3693 my @cols = map { $svc_phone->$_ } @fields;
3694 if($p->{'format'} eq 'csv') {
3695 return { 'error' => 'Unable to create CSV' }
3696 unless $csv->combine(@cols);
3697 $content .= $csv->string;
3699 elsif($p->{'format'} eq 'xls') {
3702 $xls->write($xls_r,$xls_c++,$_);
3708 $xls_workbook->close() if $p->{'format'} eq 'xls';
3710 { content => $content, format => $p->{'format'}, };
3715 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3716 return { 'error' => $session } if $context eq 'error';
3718 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3719 # FS::TicketSystem->init();
3720 # return { 'error' => 'get_ticket configuration error' }
3721 # if $FS::TicketSystem::system ne 'RT_Internal';
3723 # check existence and ownership as part of this
3724 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3725 my $rt_session = FS::TicketSystem->session('');
3726 my $Ticket = FS::TicketSystem->get_ticket_object(
3728 ticket_id => $p->{'ticket_id'},
3731 return { 'error' => 'ticket not found' } if !$Ticket;
3733 if ( length( $p->{'subject'} || '' ) ) {
3735 if ( $p->{'subject'} ne $Ticket->Subject ) {
3736 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3737 return { 'error' => "unable to set subject: $msg" } if !$val;
3741 if(length($p->{'reply'})) {
3742 my @err_or_res = FS::TicketSystem->correspond_ticket(
3744 'ticket_id' => $p->{'ticket_id'},
3745 'content' => $p->{'reply'},
3748 return { 'error' => 'unable to reply to ticket' }
3749 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3752 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3753 my $err_or_ticket = FS::TicketSystem->get_ticket(
3755 'ticket_id' => $p->{'ticket_id'},
3758 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3759 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3761 return { 'error' => $err_or_ticket };
3764 my @custs = @{$err_or_ticket->{'custs'}};
3765 my @txns = @{$err_or_ticket->{'txns'}};
3768 # superseded by check in get_ticket_object
3769 #return { 'error' => 'invalid ticket requested' }
3770 #unless grep($_ eq $custnum, @custs);
3772 foreach my $txn ( @txns ) {
3773 push @filtered_txns, $txn
3774 if ($txn->{'type'} eq 'EmailRecord'
3775 || $txn->{'type'} eq 'Correspond'
3776 || $txn->{'type'} eq 'Create');
3779 warn "$me get_ticket: successful: \n"
3781 return { 'error' => '',
3782 'transactions' => \@filtered_txns,
3783 'ticket_fields' => $err_or_ticket->{'fields'},
3784 'ticket_id' => $p->{'ticket_id'},
3788 sub adjust_ticket_priority {
3790 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3791 return { 'error' => $session } if $context eq 'error';
3793 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3794 # FS::TicketSystem->init;
3795 my $ss_priority = FS::TicketSystem->selfservice_priority;
3797 return { 'error' => 'adjust_ticket_priority configuration error' }
3798 if $FS::TicketSystem::system ne 'RT_Internal'
3801 my $values = $p->{'values'}; #hashref, id => priority value
3804 foreach my $id (keys %$values) {
3805 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3806 my $Ticket = FS::TicketSystem->get_ticket_object('',
3808 'custnum' => $custnum,
3811 $ticket_error{$id} = 'ticket not found';
3815 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3816 # We're not going to implement it for RT_External.
3817 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3818 my $new_value = $values->{$id};
3819 next if $old_value eq $new_value;
3821 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3823 # AddCustomFieldValue works fine (replacing any existing value) if it's
3824 # a single-valued custom field, which it should be. If it's not, you're
3825 # doing something wrong.
3827 if ( length($new_value) ) {
3828 ($val, $msg) = $Ticket->AddCustomFieldValue(
3829 Field => $ss_priority,
3830 Value => $new_value,
3834 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3835 Field => $ss_priority,
3836 Value => $old_value,
3840 $ticket_error{$id} = $msg if !$val;
3841 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3843 return { 'error' => '',
3844 'ticket_error' => \%ticket_error,
3845 %{ customer_info($p) } # send updated customer info back
3851 sub _custoragent_session_custnum {
3854 my($context, $session, $custnum);
3855 if ( $p->{'session_id'} ) {
3857 $context = 'customer';
3858 $session = _cache->get($p->{'session_id'})
3859 or return ( 'error' => "Can't resume session" ); #better error message
3860 $custnum = $session->{'custnum'};
3862 } elsif ( $p->{'agent_session_id'} ) {
3865 my $agent_cache = new FS::ClientAPI_SessionCache( {
3866 'namespace' => 'FS::ClientAPI::Agent',
3868 $session = $agent_cache->get($p->{'agent_session_id'})
3869 or return ( 'error' => "Can't resume session" ); #better error message
3870 $custnum = $p->{'custnum'};
3874 return ( 'error' => "Can't resume session" ); #better error message
3877 ($context, $session, $custnum);