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;
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);
27 use FS::Misc::DateTime qw(parse_datetime);
29 use FS::ClientAPI_SessionCache;
41 use FS::legacy_cust_bill;
42 use FS::cust_main_county;
46 use FS::acct_rt_transaction;
50 use FS::cust_location;
52 use FS::ClientAPI::MyAccount::quotation; # just for code organization
55 $me = '[FS::ClientAPI::MyAccount]';
57 use vars qw( @cust_main_editable_fields @location_editable_fields );
58 @cust_main_editable_fields = qw(
59 first last company daytime night fax mobile
61 payby payinfo payname paystart_month paystart_year payissue payip
62 ss paytype paystate stateid stateid_state
64 @location_editable_fields = qw(
65 address1 address2 city county state zip country
69 BEGIN { #preload to reduce time customer_info takes
70 if ( $FS::TicketSystem::system ) {
71 warn "$me: initializing ticket system\n" if $DEBUG;
72 FS::TicketSystem->init();
77 $cache ||= new FS::ClientAPI_SessionCache( {
78 'namespace' => 'FS::ClientAPI::MyAccount',
85 my($context, $session, $custnum) = _custoragent_session_custnum($p);
86 #return { 'error' => $session } if $context eq 'error';
89 if ( $context eq 'customer' && $custnum ) {
91 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
94 $sth->execute($custnum) or die $sth->errstr;
96 $agentnum = $sth->fetchrow_arrayref->[0]
97 or die "no agentnum for custnum $custnum";
99 #} elsif ( $context eq 'agent' ) {
100 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
103 $p->{'agentnum'} = $agentnum;
105 my $conf = new FS::Conf;
107 #false laziness w/Signup.pm
109 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
111 if ( $skin_info_cache_agent ) {
113 warn "$me loading cached skin info for agentnum $agentnum\n"
118 warn "$me populating skin info cache for agentnum $agentnum\n"
121 $skin_info_cache_agent = {
122 'agentnum' => $agentnum,
123 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
124 qw( company_name date_format ) ),
125 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
126 qw( body_bgcolor box_bgcolor stripe1_bgcolor stripe2_bgcolor
127 text_color link_color vlink_color hlink_color alink_color
128 font title_color title_align title_size menu_bgcolor menu_fontsize
131 'menu_disable' => [ $conf->config('selfservice-menu_disable',$agentnum) ],
132 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
133 qw( menu_skipblanks menu_skipheadings menu_nounderline no_logo )
135 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
136 qw( title_left_image title_right_image
137 menu_top_image menu_body_image menu_bottom_image
140 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
141 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
142 qw( head body_header body_footer company_address ) ),
143 'money_char' => $conf->config("money_char") || '$',
144 'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
147 services.php Services
148 services.php My Services
149 services_new.php Order a new service
152 personal.php Personal Information
153 password.php Change Password
156 payment_cc.php Credit Card Payment
157 payment_ach.php Electronic Check Payment
158 payment_paypal.php PayPal Payment
159 payment_webpay.php Webpay Payments
162 usage_data.php Data usage
163 usage_cdr.php Call usage
165 tickets.php Help Desk
166 tickets.php Open Tickets
167 tickets_resolved.php Resolved Tickets
168 ticket_create.php Create a new ticket
176 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
180 #{ %$skin_info_cache_agent };
181 $skin_info_cache_agent;
188 my $conf = new FS::Conf;
192 'phone_login' => $conf->exists('selfservice_server-phone_login'),
193 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
194 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
195 'banner_image_md5' =>
196 md5_hex($conf->config_binary('selfservice-login_banner_image')),
203 sub login_banner_image {
205 my $conf = new FS::Conf;
206 my $image = $conf->config_binary('selfservice-login_banner_image');
208 'md5' => md5_hex($image),
213 #false laziness w/FS::ClientAPI::passwd::passwd
217 my $conf = new FS::Conf;
221 if ( $p->{'domain'} eq 'svc_phone'
222 && $conf->exists('selfservice_server-phone_login') ) {
224 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
225 return { error => 'Number not found.' } unless $svc_phone;
228 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
229 #return { error => 'Only primary user may log in.' }
230 # if $conf->exists('selfservice_server-primary_only')
231 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
233 return { error => 'Incorrect PIN.' }
234 unless $svc_phone->check_pin($p->{'password'});
238 } elsif ( $p->{email}
239 && (my $contact = FS::contact->by_selfservice_email($p->{email}))
242 return { error => 'Incorrect contact password.' }
243 unless $contact->authenticate_password($p->{'password'});
245 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
246 if ( scalar(@cust_contact) == 1 ) {
247 $session->{'custnum'} = $cust_contact[0]->custnum;
248 } elsif ( scalar(@cust_contact) ) {
249 $session->{'customers'} = { map { $_->custnum => $_->cust_main->name }
253 return { error => 'No customer self-service access for contact' }; #??
258 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
260 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
261 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
263 my $svc_acct = qsearchs( 'svc_acct', { 'username' => $p->{'username'},
264 'domsvc' => $svc_domain->svcnum, }
266 return { error => 'User not found.' } unless $svc_acct;
268 if($conf->exists('selfservice_server-login_svcpart')) {
269 my @svcpart = $conf->config('selfservice_server-login_svcpart');
270 my $svcpart = $svc_acct->cust_svc->svcpart;
271 return { error => 'Invalid user.' }
272 unless grep($_ eq $svcpart, @svcpart);
275 return { error => 'Incorrect password.' }
276 unless $svc_acct->check_password($p->{'password'});
284 $session->{'svcnum'} = $svc_x->svcnum;
286 my $cust_svc = $svc_x->cust_svc;
287 my $cust_pkg = $cust_svc->cust_pkg;
289 my $cust_main = $cust_pkg->cust_main;
290 $session->{'custnum'} = $cust_main->custnum;
291 if ( $conf->exists('pkg-balances') ) {
292 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
293 $cust_main->ncancelled_pkgs;
294 $session->{'pkgnum'} = $cust_pkg->pkgnum
295 if scalar(@cust_pkg) > 1;
299 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
300 #return { error => 'Only primary user may log in.' }
301 # if $conf->exists('selfservice_server-primary_only')
302 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
303 my $part_pkg = $cust_pkg->part_pkg;
304 return { error => 'Only primary user may log in.' }
305 if $conf->exists('selfservice_server-primary_only')
306 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
312 $session_id = sha512_hex(time(). {}. rand(). $$)
313 } until ( ! defined _cache->get($session_id) ); #just in case
315 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
316 _cache->set( $session_id, $session, $timeout );
318 return { 'error' => '',
319 'session_id' => $session_id,
326 my $skin_info = skin_info($p);
327 if ( $p->{'session_id'} ) {
328 _cache->remove($p->{'session_id'});
329 return { %$skin_info, 'error' => '' };
331 return { %$skin_info, 'error' => "Can't resume session" }; #better error message
338 my($context, $session, $custnum) = _custoragent_session_custnum($p);
339 return { 'error' => $session } if $context eq 'error';
341 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
342 or return { 'error' => "Service not found" };
344 $session->{'svcnum'} = $svc_acct->svcnum;
346 my $conf = new FS::Conf;
347 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
348 _cache->set( $p->{'session_id'}, $session, $timeout );
350 return { 'error' => '' };
356 my($context, $session, $custnum) = _custoragent_session_custnum($p);
357 return { 'error' => $session } if $context eq 'error';
359 $session->{'custnum'} = $p->{'custnum'}
360 if exists $session->{'customers'}{ $p->{'custnum'} };
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' => '',
367 %{ customer_info( { session_id=>$p->{'session_id'} } ) },
371 sub payment_gateway {
373 # takes a cust_main and a cust_payby entry, returns the payment_gateway
374 my $conf = new FS::Conf;
375 my $cust_main = shift;
376 my $cust_payby = shift;
377 my $gatewaynum = $conf->config('selfservice-payment_gateway');
379 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
380 die "configured gatewaynum $gatewaynum not found!" if !$pg;
384 return '' if ! FS::payby->realtime($cust_payby);
385 my $pg = $cust_main->agent->payment_gateway(
386 'method' => FS::payby->payby2bop($cust_payby),
396 my $conf = new FS::Conf;
398 my $info = skin_info($p);
400 use vars qw( $cust_paybys ); #cache for performance
401 unless ( $cust_paybys ) {
403 my %cust_paybys = map { $_ => 1 }
404 map { FS::payby->payby2payment($_) }
405 $conf->config('signup_server-payby');
407 $cust_paybys = [ keys %cust_paybys ];
410 $info->{'cust_paybys'} = $cust_paybys;
412 my($context, $session, $custnum) = _custoragent_session_custnum($p);
413 return { 'error' => $session } if $context eq 'error';
415 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } );
417 $info->{'hide_payment_fields'} = [
419 my $pg = $cust_main && 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',
426 $cust_main ? $cust_main->agentnum : ''
429 $info->{'edit_ticket_subject'} =
430 $conf->exists('ticket_system-selfservice_edit_subject') &&
431 $cust_main && $cust_main->edit_subject;
433 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
435 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
438 'custnum' => $custnum,
439 'access_pkgnum' => $session->{'pkgnum'},
440 'access_svcnum' => $session->{'svcnum'},
447 my($context, $session, $custnum) = _custoragent_session_custnum($p);
448 return { 'error' => $session } if $context eq 'error';
452 my $conf = new FS::Conf;
453 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
455 # if ( $FS::TicketSystem::system ) {
456 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
457 # FS::TicketSystem->init();
460 if ( $custnum ) { #customer record
462 %return = ( %return, %{ customer_info_short($p) } );
464 #redundant with customer_info_short, but we need it for several things below
465 my $search = { 'custnum' => $custnum };
466 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
467 my $cust_main = qsearchs('cust_main', $search )
468 or return { 'error' => "customer_info: unknown custnum $custnum" };
470 my $list_tickets = list_tickets($p);
471 $return{'tickets'} = $list_tickets->{'tickets'};
473 if ( $session->{'pkgnum'} ) {
474 #XXX open invoices in the pkg-balances case
478 invnum => $_->invnum,
479 date => time2str("%b %o, %Y", $_->_date),
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_label; #$cust_main->status; #better to break anyone obscurely testing for strings in self-service than to have to upgrade every front-end to get the new status to display
502 $return{statuscolor} = $cust_main->statuscolor;
503 $return{status_label} = $cust_main->status_label;
505 # compatibility: some places in selfservice use this to determine
506 # if there's a ship address
507 if ( $return{has_ship_address} ) {
508 $return{ship_last} = $cust_main->last;
509 $return{ship_first} = $cust_main->first;
512 if (scalar($conf->config('support_packages'))) {
513 my @support_services = ();
514 foreach ($cust_main->support_services) {
515 my $seconds = $_->svc_x->seconds || 0;
516 my $time_remaining = (($seconds < 0) ? '-' : '' ).
517 int(abs($seconds)/3600)."h".
518 sprintf("%02d",(abs($seconds)%3600)/60)."m";
519 my $cust_pkg = $_->cust_pkg;
522 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
523 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
524 push @support_services, { svcnum => $_->svcnum,
525 time => $time_remaining,
530 $return{support_services} = \@support_services;
533 if ( $conf->config('prepayment_discounts-credit_type') ) {
535 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
538 } elsif ( $session->{'svcnum'} ) { #no customer record
540 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
541 or die "unknown svcnum";
542 $return{name} = $svc_acct->email;
546 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
550 return { 'error' => '',
551 'custnum' => $custnum,
557 sub customer_info_short {
560 my($context, $session, $custnum) = _custoragent_session_custnum($p);
561 return { 'error' => $session } if $context eq 'error';
565 my $conf = new FS::Conf;
567 if ( $custnum ) { #customer record
569 my $search = { 'custnum' => $custnum };
570 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
571 my $cust_main = qsearchs('cust_main', $search )
572 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
574 $return{display_custnum} = $cust_main->display_custnum;
576 if ( $session->{'pkgnum'} ) {
577 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
578 #next_bill_date from cust_pkg?
580 $return{balance} = $cust_main->balance;
581 $return{next_bill_date} = $cust_main->next_bill_date;
582 $return{next_bill_date_pretty} =
583 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
587 $return{countrydefault} = scalar($conf->config('countrydefault'));
589 $return{small_custview} =
590 small_custview( $cust_main,
591 $return{countrydefault},
595 $return{first} = $cust_main->first;
596 $return{'last'} = $cust_main->get('last');
597 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
599 $return{payby} = $cust_main->payby;
601 #none of these are terribly expensive if we want 'em...
602 for (@cust_main_editable_fields) {
603 $return{$_} = $cust_main->get($_);
605 #maybe a little more expensive, but it should be cached by now
606 for (@location_editable_fields) {
607 $return{$_} = $cust_main->bill_location->get($_)
608 if $cust_main->bill_locationnum;
609 $return{'ship_'.$_} = $cust_main->ship_location->get($_)
610 if $cust_main->ship_locationnum;
613 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
614 $return{payinfo} = $cust_main->paymask;
615 @return{'month', 'year'} = $cust_main->paydate_monthyear;
618 my @invoicing_list = $cust_main->invoicing_list;
619 $return{'invoicing_list'} =
620 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
621 $return{'postal_invoicing'} =
622 0 < ( grep { $_ eq 'POST' } @invoicing_list );
624 if ( $session->{'svcnum'} ) {
625 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
626 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
627 $return{'svcnum'} = $session->{'svcnum'};
630 } elsif ( $session->{'svcnum'} ) { #no customer record
632 #uuh, not supproted yet... die?
633 return { 'error' => 'customer_info_short not yet supported as agent' };
637 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
641 return { 'error' => '',
642 'custnum' => $custnum,
647 sub billing_history {
650 my($context, $session, $custnum) = _custoragent_session_custnum($p);
651 return { 'error' => $session } if $context eq 'error';
653 return { 'error' => 'No customer' } unless $custnum;
655 my $search = { 'custnum' => $custnum };
656 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
657 my $cust_main = qsearchs('cust_main', $search )
658 or return { 'error' => "unknown custnum $custnum" };
662 if ( $session->{'pkgnum'} ) {
663 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
664 #next_bill_date from cust_pkg?
665 return { 'error' => 'No history for package' };
668 $return{balance} = $cust_main->balance;
669 $return{next_bill_date} = $cust_main->next_bill_date;
670 $return{next_bill_date_pretty} =
671 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
676 my $conf = new FS::Conf;
678 if ( $conf->exists('selfservice-billing_history-line_items') ) {
680 foreach my $cust_bill ( $cust_main->cust_bill ) {
683 'type' => 'Line item',
684 'description' => $_->desc( $cust_main->locale ).
685 ( $_->sdate && $_->edate
686 ? ' '. time2str('%d-%b-%Y', $_->sdate).
687 ' To '. time2str('%d-%b-%Y', $_->edate)
690 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
691 'date' => $cust_bill->_date,
692 'date_pretty' => time2str('%m/%d/%Y', $cust_bill->_date ),
694 foreach $cust_bill->cust_bill_pkg;
702 'description' => 'Invoice #'. $_->display_invnum,
703 'amount' => sprintf('%.2f', $_->charged ),
705 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
707 foreach $cust_main->cust_bill;
713 'description' => 'Payment', #XXX type
714 'amount' => sprintf('%.2f', 0 - $_->paid ),
716 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
718 foreach $cust_main->cust_pay;
722 'description' => 'Credit', #more info?
723 'amount' => sprintf('%.2f', 0 -$_->amount ),
725 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
727 foreach $cust_main->cust_credit;
731 'description' => 'Refund', #more info? type, like payment?
732 'amount' => $_->refund,
734 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
736 foreach $cust_main->cust_refund;
738 @history = sort { $b->{'date'} <=> $a->{'date'} } @history;
740 $return{'history'} = \@history;
748 my $session = _cache->get($p->{'session_id'})
749 or return { 'error' => "Can't resume session" }; #better error message
751 my $custnum = $session->{'custnum'}
752 or return { 'error' => "no customer record" };
754 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
755 or return { 'error' => "unknown custnum $custnum" };
757 my $new = new FS::cust_main { $cust_main->hash };
759 $new->set( $_ => $p->{$_} )
760 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
762 if ( exists($p->{address1}) ) {
763 my $bill_location = FS::cust_location->new({
764 map { $_ => $p->{$_} } @location_editable_fields
766 # if this is unchanged from before, cust_main::replace will ignore it
767 $new->set('bill_location' => $bill_location);
770 if ( exists($p->{ship_address1}) ) {
771 my $ship_location = FS::cust_location->new({
772 map { $_ => $p->{"ship_$_"} } @location_editable_fields
774 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
775 # Selfservice unfortunately tries to indicate "same as billing
776 # address" by sending all fields empty. Did this ever work?
777 $ship_location = $cust_main->bill_location;
779 $new->set('ship_location' => $ship_location);
781 # but if it hasn't been passed in at all, leave ship_location alone--
782 # DON'T change it to match bill_location.
785 if (exists($p->{'payby'})) {
786 $p->{'payby'} =~ /^([A-Z]{4})$/
787 or return { 'error' => "illegal_payby " . $p->{'payby'} };
791 my $conf = new FS::Conf;
793 if ( $payby =~ /^(CARD|DCRD)$/ ) {
795 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
797 if ( $new->payinfo eq $cust_main->paymask ) {
798 $new->payinfo($cust_main->payinfo);
800 $new->payinfo($p->{'payinfo'});
803 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
805 if ( $conf->exists('selfservice-onfile_require_cvv') ){
806 return { 'error' => 'CVV2 is required' } unless $p->{'paycvv'};
809 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
812 $p->{'payinfo1'} =~ /^([\dx]+)$/
813 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
815 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
816 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
818 $payinfo = $payinfo1. '@'. $payinfo2;
820 $new->payinfo( ($payinfo eq $cust_main->paymask)
821 ? $cust_main->payinfo
825 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
827 } elsif ( $payby =~ /^(BILL)$/ ) {
829 } elsif ( $payby ) { #notyet ready
830 return { 'error' => "unknown payby $payby" };
834 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
835 #false laziness with httemplate/edit/process/cust_main.cgi
836 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
837 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
839 @invoicing_list = $cust_main->invoicing_list;
842 my $error = $new->replace($cust_main, \@invoicing_list);
843 return { 'error' => $error } if $error;
846 return { 'error' => '' };
851 my $session = _cache->get($p->{'session_id'})
852 or return { 'error' => "Can't resume session" }; #better error message
858 my $conf = new FS::Conf;
859 use vars qw($payment_info); #cache for performance
860 unless ( $payment_info ) {
862 my %states = map { $_->state => 1 }
863 qsearch('cust_main_county', {
864 'country' => $conf->config('countrydefault') || 'US'
867 my %cust_paybys = map { $_ => 1 }
868 map { FS::payby->payby2payment($_) }
869 $conf->config('signup_server-payby');
871 my @cust_paybys = keys %cust_paybys;
875 #list all counties/states/countries
876 'cust_main_county' =>
877 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
879 #shortcut for one-country folks
881 [ sort { $a cmp $b } keys %states ],
883 'card_types' => card_types(),
885 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
886 'require_cvv' => $conf->exists('selfservice-require_cvv'),
887 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
889 'paytypes' => [ @FS::cust_main::paytypes ],
891 'paybys' => [ $conf->config('signup_server-payby') ],
892 'cust_paybys' => \@cust_paybys,
894 'stateid_label' => FS::Msgcat::_gettext('stateid'),
895 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
897 'show_ss' => $conf->exists('show_ss'),
898 'show_stateid' => $conf->exists('show_stateid'),
899 'show_paystate' => $conf->exists('show_bankstate'),
901 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
903 'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
912 my %return = %$payment_info;
914 my $custnum = $session->{'custnum'};
916 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
917 or return { 'error' => "unknown custnum $custnum" };
919 $return{'hide_payment_fields'} = [
921 my $pg = payment_gateway($cust_main, $_);
922 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
923 } @{ $return{cust_paybys} }
926 $return{balance} = $cust_main->balance; #XXX pkg-balances?
928 $return{payname} = $cust_main->payname
929 || ( $cust_main->first. ' '. $cust_main->get('last') );
931 $return{$_} = $cust_main->bill_location->get($_)
932 for qw(address1 address2 city state zip);
934 $return{payby} = $cust_main->payby;
935 $return{stateid_state} = $cust_main->stateid_state;
937 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
938 $return{card_type} = cardtype($cust_main->payinfo);
939 $return{payinfo} = $cust_main->paymask;
941 @return{'month', 'year'} = $cust_main->paydate_monthyear;
945 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
946 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
947 $return{payinfo1} = $payinfo1;
948 $return{payinfo2} = $payinfo2;
949 $return{paytype} = $cust_main->paytype;
950 $return{paystate} = $cust_main->paystate;
951 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
954 if ( $conf->config('prepayment_discounts-credit_type') ) {
956 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
959 #doubleclick protection
961 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
962 $return{paybatch} = $return{payunique}; #back compat
964 return { 'error' => '',
970 #some false laziness with httemplate/process/payment.cgi - look there for
971 #ACH and CVV support stuff
973 sub validate_payment {
976 my $session = _cache->get($p->{'session_id'})
977 or return { 'error' => "Can't resume session" }; #better error message
979 my $custnum = $session->{'custnum'};
981 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
982 or return { 'error' => "unknown custnum $custnum" };
984 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
985 or return { 'error' => gettext('illegal_amount') };
987 return { error => 'Amount must be greater than 0' } unless $amount > 0;
989 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
990 #changing the hidden form values
991 my $conf = new FS::Conf;
992 my $fee_display = $conf->config('selfservice_process-display') || 'add';
993 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
994 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
995 if ( $fee_display eq 'add'
997 and ! $fee_skip_first || scalar($cust_main->cust_pay)
1000 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
1001 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
1004 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
1005 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
1006 my $discount_term = $1;
1008 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
1009 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
1012 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1013 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
1016 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1017 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
1020 $payunique = $paybatch if ! length($payunique) && length($paybatch);
1022 $p->{'payby'} ||= 'CARD';
1023 $p->{'payby'} =~ /^([A-Z]{4})$/
1024 or return { 'error' => "illegal_payby " . $p->{'payby'} };
1027 #false laziness w/process/payment.cgi
1030 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
1032 $p->{'payinfo1'} =~ /^([\dx]+)$/
1033 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1035 $p->{'payinfo2'} =~ /^([\dx]+)$/
1036 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1038 $payinfo = $payinfo1. '@'. $payinfo2;
1040 $payinfo = $cust_main->payinfo
1041 if $cust_main->paymask eq $payinfo;
1043 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1045 $payinfo = $p->{'payinfo'};
1049 #more intelligent matching will be needed here if you change
1050 #card_masking_method and don't remove existing paymasks
1051 if ( $cust_main->paymask eq $payinfo ) {
1052 $payinfo = $cust_main->payinfo;
1056 $payinfo =~ s/\D//g;
1057 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1058 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1062 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1063 return { 'error' => gettext('unknown_card_type') }
1064 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1066 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1067 if ( cardtype($payinfo) eq 'American Express card' ) {
1068 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1069 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1072 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1073 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1076 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1077 return { 'error' => 'CVV2 is required' };
1078 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1079 return { 'error' => 'CVV2 is required' };
1083 die "unknown payby $payby";
1086 my %payby2fields = (
1087 'CARD' => [ qw( paystart_month paystart_year payissue payip
1088 address1 address2 city state zip country ) ],
1089 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1093 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1096 'cust_main' => $cust_main, #XXX or just custnum??
1097 'amount' => sprintf('%.2f', $amount),
1099 'payinfo' => $payinfo,
1100 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1101 'card_type' => $card_type,
1102 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1103 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1104 'month' => $p->{'month'},
1105 'year' => $p->{'year'},
1106 'payname' => $payname,
1107 'payunique' => $payunique,
1108 'paybatch' => $paybatch,
1109 'paycvv' => $paycvv,
1110 'payname' => $payname,
1111 'discount_term' => $discount_term,
1112 'pkgnum' => $session->{'pkgnum'},
1113 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1123 my $validate = validate_payment($p);
1124 return $validate if $validate->{'error'};
1126 my $conf = new FS::Conf;
1127 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1128 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1130 +{ map { $_=>$validate->{$_} }
1131 qw( card_type paymask payname paydate_pretty month year amount
1132 address1 address2 city state zip country
1138 sub process_stored_payment {
1141 my $session_id = $p->{'session_id'};
1143 my $payment_info = _cache->get( "payment_$session_id" )
1144 or return { 'error' => "Can't resume session" }; #better error message
1146 do_process_payment($payment_info);
1150 sub process_payment {
1153 my $payment_info = validate_payment($p);
1154 return $payment_info if $payment_info->{'error'};
1156 do_process_payment($payment_info);
1160 sub do_process_payment {
1161 my $validate = shift;
1163 my $cust_main = $validate->{'cust_main'};
1165 my $amount = delete $validate->{'amount'};
1168 my $payby = delete $validate->{'payby'};
1170 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1174 'paynum_ref' => \$paynum,
1177 return { 'error' => $error } if $error;
1179 #no error, so order the fee package if applicable...
1180 my $conf = new FS::Conf;
1181 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1182 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1184 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1186 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1188 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1189 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1192 #and generate an invoice for it now too
1193 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1194 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1199 $cust_main->apply_payments;
1201 if ( $validate->{'save'} ) {
1202 my $new = new FS::cust_main { $cust_main->hash };
1203 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1204 $new->set( $_ => $validate->{$_} )
1205 foreach qw( payname paystart_month paystart_year payissue payip );
1206 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1208 my $bill_location = FS::cust_location->new({
1209 map { $_ => $validate->{$_} }
1210 qw(address1 address2 city state country zip)
1212 $new->set('bill_location' => $bill_location);
1213 # but don't allow the service address to change this way.
1215 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1216 $new->set( $_ => $validate->{$_} )
1217 foreach qw( payname payip paytype paystate
1218 stateid stateid_state );
1219 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1221 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1222 $new->set( 'paydate' => $validate->{'paydate'} );
1223 my $error = $new->replace($cust_main);
1225 #no, this causes customers to process their payments again
1226 #return { 'error' => $error };
1227 #XXX just warn verosely for now so i can figure out how these happen in
1228 # the first place, eventually should redirect them to the "change
1229 #address" page but indicate the payment did process??
1230 delete($validate->{'payinfo'}); #don't want to log this!
1231 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1232 "NEW: ". Dumper($new)."\n".
1233 "OLD: ". Dumper($cust_main)."\n".
1234 "PACKET: ". Dumper($validate)."\n";
1242 my $receipt_html = '';
1244 # currently supported for realtime CC only; send receipt data to SS
1245 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1248 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1251 <TD ALIGN="right">Payment#</TD>
1252 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1256 <TD ALIGN="right">Date</TD>
1258 <TD BGCOLOR="#FFFFFF"><B>! .
1259 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1265 <TD ALIGN="right">Amount</TD>
1266 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1271 <TD ALIGN="right">Payment method</TD>
1272 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1285 'amount' => sprintf('%.2f', $cust_pay->paid),
1286 'date' => $cust_pay->_date,
1287 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1288 'time_pretty' => time2str('%T', $cust_pay->_date),
1289 'auth_num' => $cust_pay->auth,
1290 'order_num' => $cust_pay->order_number,
1291 'receipt_html' => $receipt_html,
1298 'receipt_html' => '',
1305 sub realtime_collect {
1308 my $session = _cache->get($p->{'session_id'})
1309 or return { 'error' => "Can't resume session" }; #better error message
1311 my $custnum = $session->{'custnum'};
1313 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1314 or return { 'error' => "unknown custnum $custnum" };
1317 if ( $p->{'amount'} ) {
1318 $amount = $p->{'amount'};
1320 elsif ( $session->{'pkgnum'} ) {
1321 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1324 $amount = $cust_main->balance;
1327 my $error = $cust_main->realtime_collect(
1328 'method' => $p->{'method'},
1329 'amount' => $amount,
1330 'pkgnum' => $session->{'pkgnum'},
1331 'session_id' => $p->{'session_id'},
1335 return { 'error' => $error } unless ref( $error );
1337 return { 'error' => '', amount => $amount, %$error };
1340 sub start_thirdparty {
1342 my $session = _cache->get($p->{'session_id'})
1343 or return { 'error' => "Can't resume session" }; #better error message
1344 my $custnum = $session->{'custnum'};
1345 my $cust_main = FS::cust_main->by_key($custnum);
1347 my $amount = $p->{'amount'}
1348 or return { error => 'no amount' };
1350 my $result = $cust_main->create_payment(
1351 'method' => $p->{'method'},
1352 'amount' => $p->{'amount'},
1353 'pkgnum' => $session->{'pkgnum'},
1354 'session_id' => $p->{'session_id'},
1357 if ( ref($result) ) { # hashref or error
1360 return { error => $result };
1364 sub finish_thirdparty {
1366 my $session_id = delete $p->{'session_id'};
1367 my $session = _cache->get($session_id)
1368 or return { 'error' => "Can't resume session" };
1369 my $custnum = $session->{'custnum'};
1370 my $cust_main = FS::cust_main->by_key($custnum);
1372 if ( $p->{_cancel} ) {
1373 # customer backed out of making a payment
1374 return $cust_main->cancel_payment( $session_id );
1376 my $result = $cust_main->execute_payment( $session_id, %$p );
1377 if ( ref($result) ) {
1380 return { error => $result };
1384 sub process_payment_order_pkg {
1387 my $hr = process_payment($p);
1388 return $hr if $hr->{'error'};
1393 sub process_payment_order_renew {
1396 my $hr = process_payment($p);
1397 return $hr if $hr->{'error'};
1402 sub process_prepay {
1406 my $session = _cache->get($p->{'session_id'})
1407 or return { 'error' => "Can't resume session" }; #better error message
1411 my $custnum = $session->{'custnum'};
1413 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1414 or return { 'error' => "unknown custnum $custnum" };
1416 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1417 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1425 return { 'error' => $error } if $error;
1427 return { 'error' => '',
1428 'amount' => $amount,
1429 'seconds' => $seconds,
1430 'duration' => duration_exact($seconds),
1431 'upbytes' => $upbytes,
1432 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1433 'downbytes' => $downbytes,
1434 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1435 'totalbytes'=> $totalbytes,
1436 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1443 my $session = _cache->get($p->{'session_id'})
1444 or return { 'error' => "Can't resume session" }; #better error message
1446 my $custnum = $session->{'custnum'};
1448 my $invnum = $p->{'invnum'};
1450 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1451 'custnum' => $custnum } )
1452 or return { 'error' => "Can't find invnum" };
1456 return { 'error' => '',
1457 'invnum' => $invnum,
1458 'invoice_text' => join('', $cust_bill->print_text ),
1459 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1466 my $session = _cache->get($p->{'session_id'})
1467 or return { 'error' => "Can't resume session" }; #better error message
1469 my $custnum = $session->{'custnum'};
1471 my $invnum = $p->{'invnum'};
1473 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1474 'custnum' => $custnum } )
1475 or return { 'error' => "Can't find invnum" };
1479 return { 'error' => '',
1480 'invnum' => $invnum,
1481 'invoice_pdf' => $cust_bill->print_pdf({
1482 'unsquelch_cdr' => 1,
1483 'locale' => $p->{'locale'},
1489 sub legacy_invoice {
1491 my $session = _cache->get($p->{'session_id'})
1492 or return { 'error' => "Can't resume session" }; #better error message
1494 my $custnum = $session->{'custnum'};
1496 my $legacyinvnum = $p->{'legacyinvnum'};
1499 'legacyinvnum' => $legacyinvnum,
1500 'custnum' => $custnum,
1503 my $legacy_cust_bill =
1504 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1505 || qsearchs('legacy_cust_bill', \%hash )
1506 or return { 'error' => "Can't find legacyinvnum" };
1510 return { 'error' => '',
1511 'legacyinvnum' => $legacyinvnum,
1512 'legacyid' => $legacy_cust_bill->legacyid,
1513 'invoice_html' => $legacy_cust_bill->content_html,
1518 sub legacy_invoice_pdf {
1520 my $session = _cache->get($p->{'session_id'})
1521 or return { 'error' => "Can't resume session" }; #better error message
1523 my $custnum = $session->{'custnum'};
1525 my $legacyinvnum = $p->{'legacyinvnum'};
1527 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1528 'legacyinvnum' => $legacyinvnum,
1529 'custnum' => $custnum,
1530 }) or return { 'error' => "Can't find legacyinvnum" };
1534 return { 'error' => '',
1535 'legacyinvnum' => $legacyinvnum,
1536 'legacyid' => $legacy_cust_bill->legacyid,
1537 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1545 #sessioning for this? how do we get the session id to the backend invoice
1546 # template so it can add it to the link, blah
1549 if ( $p->{'invnum'} ) {
1550 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1551 or return { 'error' => 'unknown invnum' };
1552 $agentnum = $cust_bill->cust_main->agentnum;
1555 my $templatename = $p->{'template'} || $p->{'templatename'};
1557 #false laziness-ish w/view/cust_bill-logo.cgi
1559 my $conf = new FS::Conf;
1560 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1561 $templatename = "_$1";
1566 my $filename = "logo$templatename.png";
1568 return { 'error' => '',
1569 'logo' => $conf->config_binary($filename, $agentnum),
1570 'content_type' => 'image/png', #should allow gif, jpg too
1577 my $session = _cache->get($p->{'session_id'})
1578 or return { 'error' => "Can't resume session" }; #better error message
1580 my $custnum = $session->{'custnum'};
1582 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1583 or return { 'error' => "unknown custnum $custnum" };
1585 my $conf = new FS::Conf;
1587 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1589 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1593 return { 'error' => '',
1594 'balance' => $cust_main->balance,
1597 my $owed = $_->owed;
1599 +{ 'invnum' => $_->invnum,
1600 '_date' => $_->_date,
1601 'date' => time2str("%b %o, %Y", $_->_date),
1602 'date_short' => time2str("%m-%d-%Y", $_->_date),
1603 'previous' => sprintf('%.2f', ($_->previous)[0]),
1604 'charged' => sprintf('%.2f', $_->charged),
1605 'owed' => sprintf('%.2f', $owed),
1606 'balance' => sprintf('%.2f', $balance),
1611 'legacy_invoices' => [
1613 +{ 'legacyinvnum' => $_->legacyinvnum,
1614 'legacyid' => $_->legacyid,
1615 '_date' => $_->_date,
1616 'date' => time2str("%b %o, %Y", $_->_date),
1617 'date_short' => time2str("%m-%d-%Y", $_->_date),
1618 'charged' => sprintf('%.2f', $_->charged),
1619 'has_content' => ( length($_->content_pdf)
1620 || length($_->content_html) ),
1630 my $session = _cache->get($p->{'session_id'})
1631 or return { 'error' => "Can't resume session" }; #better error message
1633 my $custnum = $session->{'custnum'};
1635 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1636 or return { 'error' => "unknown custnum $custnum" };
1638 my @errors = $cust_main->cancel( 'quiet'=>1 );
1640 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1642 return { 'error' => $error };
1649 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1650 return { 'error' => $session } if $context eq 'error';
1652 my $search = { 'custnum' => $custnum };
1653 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1654 my $cust_main = qsearchs('cust_main', $search )
1655 or return { 'error' => "unknown custnum $custnum" };
1657 my $conf = new FS::Conf;
1658 my $immutable = $conf->exists('selfservice_immutable-package');
1660 # the duplication below is necessary:
1661 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1662 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1663 # non-backwards-compatible change breaking the software of anyone using the API
1664 # instead of the stock selfservice
1665 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1666 if( $conf->exists('selfservice_server-view-wholesale') ) {
1667 return { 'svcnum' => $session->{'svcnum'},
1668 'custnum' => $custnum,
1669 'cust_pkg' => [ map {
1671 immutable => $immutable,
1672 part_pkg => [ map $_->hashref, $_->part_pkg ],
1674 [ map $_->hashref, $_->available_part_svc ],
1676 [ map { my $ref = { $_->hash,
1677 label => [ $_->label ],
1679 $ref->{_password} = $_->svc_x->_password
1680 if $context eq 'agent'
1681 && $conf->exists('agent-showpasswords')
1682 && $_->part_svc->svcdb eq 'svc_acct';
1687 } $cust_main->cust_pkg
1690 small_custview( $cust_main, $conf->config('countrydefault') ),
1691 'wholesale_view' => 1,
1692 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1693 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1694 'lnp' => $conf->exists('svc_phone-lnp'),
1698 { 'svcnum' => $session->{'svcnum'},
1699 'custnum' => $custnum,
1700 'cust_pkg' => [ map {
1701 my $primary_cust_svc = $_->primary_cust_svc;
1704 immutable => $immutable,
1705 pkg_label => $_->pkg_locale,
1706 status => $_->status,
1707 statuscolor => $_->statuscolor,
1709 [ map { $_->hashref }
1710 grep { $_->selfservice_access ne 'hidden' }
1711 $_->available_part_svc
1714 [ map { my $ref = { $_->hash,
1715 label => [ $_->label ],
1717 $ref->{_password} = $_->svc_x->_password
1718 if $context eq 'agent'
1719 && $conf->exists('agent-showpasswords')
1720 && $_->part_svc->svcdb eq 'svc_acct';
1721 $ref->{svchash} = { $_->svc_x->hash } if
1722 $_->part_svc->svcdb eq 'svc_phone';
1723 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1724 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1727 grep { $_->part_svc->selfservice_access ne 'hidden' }
1732 ? { $primary_cust_svc->hash,
1733 label => [ $primary_cust_svc->label ],
1734 finger => $primary_cust_svc->svc_x->finger, #uuh
1735 $primary_cust_svc->part_svc->hash,
1739 } $cust_main->ncancelled_pkgs
1742 small_custview( $cust_main, $conf->config('countrydefault') ),
1743 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1751 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1752 return { 'error' => $session } if $context eq 'error';
1754 my $conf = new FS::Conf;
1756 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1757 my $search = { 'custnum' => $custnum };
1758 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1759 my $cust_main = qsearchs('cust_main', $search )
1760 or return { 'error' => "unknown custnum $custnum" };
1762 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1763 if ( ! $pkgnum && $p->{'svcnum'} ) {
1764 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1765 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1769 my @cust_pkg_usage = ();
1770 foreach my $cust_pkg ( $p->{'ncancelled'}
1771 ? $cust_main->ncancelled_pkgs
1772 : $cust_main->unsuspended_pkgs ) {
1773 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1774 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1775 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1778 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1781 foreach (@cust_pkg_usage) {
1782 my $part = $_->part_pkg_usage;
1783 my $tag = $part->description . ($part->shared ? 1 : 0);
1784 my $row = $usage_pools{$tag}
1785 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1786 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1787 $row->[2] += $part->minutes; # minutes total
1789 } # otherwise just leave them empty
1791 if ( $p->{'svcdb'} ) {
1792 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1794 : ref($p->{'svcdb'}) eq 'ARRAY'
1795 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1796 : { $p->{'svcdb'} => 1 };
1797 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1800 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1803 my @svcs; # stuff to return to the client
1804 foreach my $cust_svc (@cust_svc) {
1805 my $svc_x = $cust_svc->svc_x;
1806 my($label, $value) = $cust_svc->label;
1807 my $part_svc = $cust_svc->part_svc;
1808 my $svcdb = $part_svc->svcdb;
1809 my $cust_pkg = $cust_svc->cust_pkg;
1810 my $part_pkg = $cust_pkg->part_pkg;
1813 'svcnum' => $cust_svc->svcnum,
1814 'display_svcnum' => $cust_svc->display_svcnum,
1818 'pkg_label' => $cust_pkg->pkg_locale,
1819 'pkg_status' => $cust_pkg->status,
1820 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1823 # would it make sense to put this in a svc_* method?
1825 if ( $svcdb eq 'svc_acct' ) {
1826 foreach (qw(username email finger seconds)) {
1827 $hash{$_} = $svc_x->$_;
1833 'upbytes' => display_bytecount($svc_x->upbytes),
1834 'downbytes' => display_bytecount($svc_x->downbytes),
1835 'totalbytes' => display_bytecount($svc_x->totalbytes),
1837 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1838 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1839 'recharge_upbytes' =>
1840 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1841 'recharge_downbytes' =>
1842 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1843 'recharge_totalbytes' =>
1844 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1849 } elsif ( $svcdb eq 'svc_dsl' ) {
1851 $hash{'phonenum'} = $svc_x->phonenum;
1852 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1853 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1854 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1857 $hash{'name'} = $cust_main->name;
1859 # no usage to hide here
1861 } elsif ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
1863 # could potentially show lots of things...
1864 $hash{'outbound'} = 1;
1865 $hash{'inbound'} = 0;
1866 if ( $svcdb eq 'svc_phone' ) {
1867 if ( $part_pkg->plan eq 'voip_inbound' ) {
1868 $hash{'outbound'} = 0;
1869 $hash{'inbound'} = 1;
1870 } elsif ( $part_pkg->option('selfservice_inbound_format')
1871 or $conf->config('selfservice-default_inbound_cdr_format')
1873 $hash{'inbound'} = 1;
1876 foreach (qw(inbound outbound)) {
1877 # hmm...we can't filter by status here, because there might
1878 # not be cdr_terminations at all. have to go by date.
1879 # find all since the last bill date.
1880 # XXX cdr types? we are going to need them.
1882 my $sum_cdr = $svc_x->sum_cdrs(
1883 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1884 'begin' => ($cust_pkg->last_bill || 0),
1886 'disable_charged_party' => 1,
1888 $hash{$_} = $sum_cdr->hashref;
1891 } # not hiding usage
1895 } # foreach $cust_svc
1898 'svcnum' => $session->{'svcnum'},
1899 'custnum' => $custnum,
1900 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1901 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1904 map { $usage_pools{$_} }
1908 'hide_usage' => $hide_usage,
1913 sub _customer_svc_x {
1914 my($custnum, $svcnum, $table) = (shift, shift, shift);
1915 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1917 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1918 my $search = " AND custnum = $1";
1919 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1922 'table' => ($table || 'svc_acct'),
1923 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1924 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1925 #'LEFT JOIN cust_main USING ( custnum ) ',
1926 'hashref' => $hashref,
1927 'extra_sql' => $search, #important
1932 sub svc_status_html {
1935 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1936 return { 'error' => $session } if $context eq 'error';
1938 #XXX only svc_dsl for now
1939 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1940 or return { 'error' => "Service not found" };
1942 my $html = $svc_x->getstatus_html;
1944 return { 'html' => $html };
1948 sub svc_status_hash {
1951 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1952 return { 'error' => $session } if $context eq 'error';
1954 #XXX only svc_acct for now
1955 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1956 or return { 'error' => "Service not found" };
1958 my ( $html, $hashref ) = $svc_x->export_getstatus;
1963 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1964 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1965 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1966 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1967 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1970 my( $p, $method ) = @_;
1972 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1973 return { 'error' => $session } if $context eq 'error';
1975 #XXX only svc_acct for now
1976 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1977 or return { 'error' => "Service not found" };
1979 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1981 my $error = $svc_x->$method($p); #$p? returns error?
1982 return { 'error' => $error } if $error;
1984 return {}; #? { 'error' => '' }
1988 sub acct_forward_info {
1991 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1992 return { 'error' => $session } if $context eq 'error';
1994 my $svc_forward = _customer_svc_x( $custnum,
1995 { 'srcsvc' => $p->{'svcnum'} },
1998 or return { 'error' => '',
2002 return { 'error' => '',
2003 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2008 sub process_acct_forward {
2010 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2011 return { 'error' => $session } if $context eq 'error';
2013 my $old = _customer_svc_x( $custnum,
2014 { 'srcsvc' => $p->{'svcnum'} },
2018 if ( $p->{'dst'} eq '' ) {
2020 my $error = $old->delete;
2021 return { 'error' => $error };
2023 return { 'error' => '' };
2026 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2027 'dst' => $p->{'dst'},
2032 $new->svcnum($old->svcnum);
2033 my $cust_svc = $old->cust_svc;
2034 $new->svcpart($old->svcpart);
2035 $new->pkgnuym($old->pkgnum);
2036 $error = $new->replace($old);
2038 my $conf = new FS::Conf;
2039 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2041 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2042 or return { 'error' => 'No service' }; #how would we even get here?
2044 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2046 $error = $new->insert;
2049 return { 'error' => $error };
2053 sub list_dsl_devices {
2056 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2057 return { 'error' => $session } if $context eq 'error';
2059 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2060 or return { 'error' => "Service not found" };
2063 'devices' => [ map {
2064 +{ 'mac_addr' => $_->mac_addr };
2065 } $svc_dsl->dsl_device
2071 sub add_dsl_device {
2074 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2075 return { 'error' => $session } if $context eq 'error';
2077 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2078 or return { 'error' => "Service not found" };
2080 return { 'error' => 'No MAC address supplied' }
2081 unless length($p->{'mac_addr'});
2083 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2084 'mac_addr' => scalar($p->{'mac_addr'}),
2086 my $error = $dsl_device->insert;
2087 return { 'error' => $error };
2091 sub delete_dsl_device {
2094 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2095 return { 'error' => $session } if $context eq 'error';
2097 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2098 or return { 'error' => "Service not found" };
2100 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2101 'mac_addr' => scalar($p->{'mac_addr'}),
2104 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2106 my $error = $dsl_device->delete;
2107 return { 'error' => $error };
2113 _usage_details( \&_port_graph, $p,
2114 'svcdb' => 'svc_port',
2119 my($svc_port, $begin, $end) = @_;
2121 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2122 push @usage, { 'png' => $pngOrError };
2126 sub _list_svc_usage {
2127 my($svc_acct, $begin, $end) = @_;
2129 foreach my $part_export (
2130 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2131 qw( sqlradius sqlradius_withdomain )
2133 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2138 sub list_svc_usage {
2139 _usage_details(\&_list_svc_usage, @_);
2142 sub _list_support_usage {
2143 my($svc_acct, $begin, $end) = @_;
2145 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2146 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2148 push @usage, { 'seconds' => $_->seconds,
2149 'support' => $_->support,
2150 '_date' => $_->_date,
2151 'id' => $_->transaction_id,
2152 'creator' => $_->creator,
2153 'subject' => $_->subject,
2154 'status' => $_->status,
2155 'ticketid' => $_->ticketid,
2161 sub list_support_usage {
2162 _usage_details(\&_list_support_usage, @_);
2165 sub _list_cdr_usage {
2166 # XXX CDR type support...
2167 # XXX any way to do a paged search on this?
2168 # we have to return the results all at once...
2169 my($svc_x, $begin, $end, %opt) = @_;
2170 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2174 'disable_charged_party' => 1,
2179 sub list_cdr_usage {
2181 _usage_details( \&_list_cdr_usage, $p );
2184 sub _usage_details {
2185 my($callback, $p, %opt) = @_;
2186 my $conf = FS::Conf->new;
2188 if ( $conf->exists('selfservice_hide-usage') ) {
2189 return { 'error' => 'Viewing usage is not allowed.' };
2192 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2193 return { 'error' => $session } if $context eq 'error';
2195 my $search = { 'svcnum' => $p->{'svcnum'} };
2196 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2198 my $cust_svc = qsearchs( 'cust_svc', $search );
2199 return { 'error' => 'No service selected in list_svc_usage' }
2202 my $svc_x = $cust_svc->svc_x;
2203 my $svcdb = $svc_x->table;
2204 my $cust_pkg = $cust_svc->cust_pkg;
2205 my $freq = $cust_pkg->part_pkg->freq;
2208 if ( $svcdb eq 'svc_phone' or $svcdb eq 'svc_pbx' ) {
2210 if ( $p->{inbound} ) {
2211 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2212 || $conf->config('selfservice-default_inbound_cdr_format')
2213 || 'source_default';
2214 $callback_opt{inbound} = 1;
2216 $format = $cust_pkg->part_pkg->option('selfservice_format')
2217 || $conf->config('selfservice-default_cdr_format')
2221 $callback_opt{format} = $format;
2222 $callback_opt{use_clid} = 1;
2223 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2226 my $start = $cust_pkg->setup;
2227 #my $end = $cust_pkg->bill; # or time?
2230 unless ( $p->{beginning} ) {
2231 $p->{beginning} = $cust_pkg->last_bill;
2232 $p->{ending} = $end;
2235 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2236 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2238 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2242 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2243 # ugly kludge, I know
2244 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2245 if (defined $delete_col) {
2246 delete($_->[$delete_col]) foreach ($header, @usage);
2250 #kinda false laziness with FS::cust_main::bill, but perhaps
2251 #we should really change this bit to DateTime and DateTime::Duration
2253 #change this bit to use Date::Manip? CAREFUL with timezones (see
2254 # mailing list archive)
2255 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2256 (localtime($p->{ending}) )[0,1,2,3,4,5];
2257 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2258 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2260 if ( $freq =~ /^\d+$/ ) {
2262 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2264 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2265 } elsif ( $freq =~ /^(\d+)w$/ ) {
2267 $nmday += $weeks * 7;
2268 $pmday -= $weeks * 7;
2269 } elsif ( $freq =~ /^(\d+)d$/ ) {
2273 } elsif ( $freq =~ /^(\d+)h$/ ) {
2278 return { 'error' => "unparsable frequency: ". $freq };
2281 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2282 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2286 'svcnum' => $p->{svcnum},
2287 'beginning' => $p->{beginning},
2288 'ending' => $p->{ending},
2289 'inbound' => $p->{inbound},
2290 'previous' => ($previous > $start) ? $previous : $start,
2291 'next' => ($next < $end) ? $next : $end,
2292 'header' => $header,
2300 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2301 return { 'error' => $session } if $context eq 'error';
2303 my $search = { 'custnum' => $custnum };
2304 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2305 my $cust_main = qsearchs('cust_main', $search )
2306 or return { 'error' => "unknown custnum $custnum" };
2308 my $status = $cust_main->status;
2310 my %order_pkg_options = ();
2311 if ( $p->{locationnum} > 0 ) {
2312 $order_pkg_options{locationnum} = delete($p->{locationnum});
2313 } elsif ( $p->{address1} ) {
2314 $order_pkg_options{'cust_location'} = new FS::cust_location {
2315 map { $_ => $p->{$_} }
2316 qw( address1 address2 city county state zip country )
2320 #false laziness w/ClientAPI/Signup.pm
2322 my $cust_pkg = new FS::cust_pkg ( {
2323 'custnum' => $custnum,
2324 'pkgpart' => $p->{'pkgpart'},
2325 'quantity' => $p->{'quantity'} || 1,
2327 my $error = $cust_pkg->check;
2328 return { 'error' => $error } if $error;
2331 unless ( $p->{'svcpart'} eq 'none' ) {
2335 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2337 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2338 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2339 $svcdb = $part_svc->svcdb;
2341 $svcdb = 'svc_acct';
2343 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2346 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2347 'svc_domain' => [ qw( domain ) ],
2348 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2349 'svc_external' => [ qw( id title ) ],
2350 'svc_pbx' => [ qw( id title ) ],
2353 my $svc_x = "FS::$svcdb"->new( {
2354 'svcpart' => $svcpart,
2355 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2358 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2361 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2362 my $acct_snarf = new FS::acct_snarf ( {
2363 'machine' => $p->{"snarf_machine$snarfnum"},
2364 'protocol' => $p->{"snarf_protocol$snarfnum"},
2365 'username' => $p->{"snarf_username$snarfnum"},
2366 '_password' => $p->{"snarf_password$snarfnum"},
2369 push @acct_snarf, $acct_snarf;
2371 $svc_x->child_objects( \@acct_snarf );
2374 my $y = $svc_x->setdefault; # arguably should be in new method
2375 return { 'error' => $y } if $y && !ref($y);
2377 $error = $svc_x->check;
2378 return { 'error' => $error } if $error;
2384 $error = $cust_main->order_pkg(
2385 'cust_pkg' => $cust_pkg,
2390 return { 'error' => $error } if $error;
2392 my $conf = new FS::Conf;
2393 if ( $conf->exists('signup_server-realtime') ) {
2395 my $bill_error = _do_bop_realtime( $cust_main, $status );
2398 $cust_pkg->cancel('quiet'=>1);
2401 $cust_pkg->reexport;
2405 $cust_pkg->reexport;
2408 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2410 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2417 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2418 return { 'error' => $session } if $context eq 'error';
2420 my $conf = new FS::Conf;
2421 my $immutable = $conf->exists('selfservice_immutable-package');
2422 return { 'error' => "Package modification disabled" } if $immutable;
2424 my $search = { 'custnum' => $custnum };
2425 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2426 my $cust_main = qsearchs('cust_main', $search )
2427 or return { 'error' => "unknown custnum $custnum" };
2429 my $status = $cust_main->status;
2430 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2431 or return { 'error' => "unknown package $p->{pkgnum}" };
2433 #if someone does need self-service package change of suspended packages,
2434 # figure out how to be more discriminating
2435 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2436 if $cust_pkg->status eq 'suspended';
2438 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2439 'quantity' => $p->{'quantity'} || 1,
2442 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2443 unless ref($err_or_cust_pkg);
2445 if ( $conf->exists('signup_server-realtime') ) {
2447 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_credit'=>1 );
2450 $err_or_cust_pkg->suspend;
2453 $err_or_cust_pkg->reexport;
2457 $err_or_cust_pkg->reexport;
2460 return { error => '', pkgnum => $cust_pkg->pkgnum };
2464 sub order_recharge {
2467 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2468 return { 'error' => $session } if $context eq 'error';
2470 my $search = { 'custnum' => $custnum };
2471 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2472 my $cust_main = qsearchs('cust_main', $search )
2473 or return { 'error' => "unknown custnum $custnum" };
2475 my $status = $cust_main->status;
2476 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2477 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2479 my $svc_x = $cust_svc->svc_x;
2480 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2483 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2484 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2485 recharge_totalbytes );
2486 my $amount = $part_pkg->option('recharge_amount', 1);
2488 my ($l, $v, $d) = $cust_svc->label; # blah
2489 my $pkg = "Recharge $v";
2491 my $bill_error = $cust_main->charge($amount, $pkg,
2492 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2493 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2494 $part_pkg->taxclass); #meh
2496 my $conf = new FS::Conf;
2497 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2499 $bill_error = _do_bop_realtime( $cust_main, $status );
2504 my $error = $svc_x->recharge (\%vhash);
2505 return { 'error' => $error } if $error;
2509 my $error = $bill_error;
2510 $error ||= $svc_x->recharge (\%vhash);
2511 return { 'error' => $error } if $error;
2514 return { error => '', svc => $cust_svc->part_svc->svc };
2518 sub _do_bop_realtime {
2519 my ($cust_main, $status, %opt) = @_;
2521 my $old_balance = $cust_main->balance;
2523 my $bill_error = $cust_main->bill
2524 || $cust_main->apply_payments_and_credits;
2526 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2527 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2529 if ( $cust_main->balance > $old_balance
2530 && $cust_main->balance > 0
2531 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2532 || $status eq 'suspended'
2536 unless ( $opt{'no_credit'} ) {
2537 #this makes sense. credit is "un-doing" the invoice
2538 my $conf = new FS::Conf;
2539 $cust_main->credit( sprintf("%.2f", $cust_main->balance-$old_balance ),
2540 'self-service decline',
2541 reason_type=>$conf->config('signup_credit_type'),
2543 $cust_main->apply_credits( 'order' => 'newest' );
2546 return { 'error' => '_decline', 'bill_error' => $bill_error };
2555 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2556 return { 'error' => $session } if $context eq 'error';
2558 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2559 or return { 'error' => "unknown custnum $custnum" };
2561 my @cust_pkg = sort { $a->bill <=> $b->bill }
2562 grep { $_->part_pkg->freq ne '0' }
2563 $cust_main->ncancelled_pkgs;
2565 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2567 my $total = $cust_main->balance;
2570 my $bill = $_->bill;
2571 $total += $_->part_pkg->base_recur($_, \$bill);
2572 my $renew_date = $_->part_pkg->add_freq($_->bill);
2574 'pkgnum' => $_->pkgnum,
2575 'amount' => sprintf('%.2f', $total),
2576 'bill_date' => $_->bill,
2577 'bill_date_pretty' => time2str('%x', $_->bill),
2578 'renew_date' => $renew_date,
2579 'renew_date_pretty' => time2str('%x', $renew_date),
2580 'expire_date' => $_->expire,
2581 'expire_date_pretty' => time2str('%x', $_->expire),
2586 return { 'dates' => \@array };
2590 sub payment_info_renew_info {
2592 my $renew_info = renew_info($p);
2593 my $payment_info = payment_info($p);
2594 return { %$renew_info,
2602 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2603 return { 'error' => $session } if $context eq 'error';
2605 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2606 or return { 'error' => "unknown custnum $custnum" };
2608 my $date = $p->{'date'};
2612 #freeside-daily -n -d $date fs_daily $custnum
2613 $cust_main->bill_and_collect( 'time' => $date,
2614 'invoice_time' => $now,
2615 'actual_time' => $now,
2616 'check_freq' => '1d',
2619 return { 'error' => '' };
2625 my $session = _cache->get($p->{'session_id'})
2626 or return { 'error' => "Can't resume session" }; #better error message
2628 my $custnum = $session->{'custnum'};
2630 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2631 or return { 'error' => "unknown custnum $custnum" };
2633 my $conf = new FS::Conf;
2635 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2636 or return { 'error' => 'Permission denied' };
2638 my $pkgnum = $p->{'pkgnum'};
2640 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2641 'pkgnum' => $pkgnum, } )
2642 or return { 'error' => "unknown pkgnum $pkgnum" };
2644 my $error = $cust_pkg->suspend(reason => $reasonnum);
2645 return { 'error' => $error };
2651 my $session = _cache->get($p->{'session_id'})
2652 or return { 'error' => "Can't resume session" }; #better error message
2654 my $custnum = $session->{'custnum'};
2656 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2657 or return { 'error' => "unknown custnum $custnum" };
2659 my $pkgnum = $p->{'pkgnum'};
2661 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2662 'pkgnum' => $pkgnum, } )
2663 or return { 'error' => "unknown pkgnum $pkgnum" };
2665 my $error = $cust_pkg->cancel('quiet' => 1);
2666 return { 'error' => $error };
2670 sub provision_phone {
2673 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2675 #editing an existing phone number
2676 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2677 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2678 return { 'error' => $session } if $context eq 'error';
2680 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2681 return { 'error' => 'service not found' } unless $svc_phone;
2682 return { 'error' => 'invalid svcnum' }
2683 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2685 $svc_phone->email($p->{'email'})
2686 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2687 $svc_phone->forwarddst($p->{'forwarddst'})
2688 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2689 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2690 return { 'error' => $svc_phone->replace };
2694 unless ( $p->{'lnp'} ) {
2695 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2696 $p->{'lnp_status'} = "portingin";
2697 return _provision( 'FS::svc_phone',
2698 [qw(lnp_desired_due_date lnp_other_provider
2699 lnp_other_provider_account phonenum countrycode lnp_status)],
2700 [qw(phonenum countrycode)],
2706 # single DID order (the usual case)
2707 unless (scalar(@bulkdid)) {
2708 return _provision( 'FS::svc_phone',
2709 [qw(phonenum countrycode)],
2710 [qw(phonenum countrycode)],
2716 # bulk DID order case
2718 foreach my $did ( @bulkdid ) {
2719 $did =~ s/[^0-9]//g;
2720 $error = _provision( 'FS::svc_phone',
2721 [qw(phonenum countrycode)],
2722 [qw(phonenum countrycode)],
2724 'pkgnum' => $p->{'pkgnum'},
2725 'svcpart' => $p->{'svcpart'},
2727 'countrycode' => $p->{'countrycode'},
2728 'session_id' => $p->{'session_id'},
2731 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2733 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2738 warn "provision_pbx called\n"
2741 warn "provision_pbx calling _provision\n"
2743 _provision( 'FS::svc_pbx',
2744 [qw(id title max_extensions max_simultaneous ip_addr)],
2745 [qw(id title max_extensions max_simultaneous ip_addr)],
2751 sub provision_acct {
2753 warn "provision_acct called\n"
2756 return { 'error' => gettext('passwords_dont_match') }
2757 if $p->{'_password'} ne $p->{'_password2'};
2758 return { 'error' => gettext('empty_password') }
2759 unless length($p->{'_password'});
2761 if ($p->{'domsvc'}) {
2762 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2763 qw ( svcpart pkgnum ) );
2764 return { 'error' => gettext('invalid_domain') }
2765 unless ($domains{$p->{'domsvc'}});
2768 warn "provision_acct calling _provision\n"
2770 _provision( 'FS::svc_acct',
2771 [qw(username _password domsvc)],
2772 [qw(username _password domsvc)],
2778 sub provision_external {
2780 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2781 _provision( 'FS::svc_external',
2790 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2791 warn "_provision called for $class\n"
2794 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2795 return { 'error' => $session } if $context eq 'error';
2797 my $search = { 'custnum' => $custnum };
2798 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2799 my $cust_main = qsearchs('cust_main', $search )
2800 or return { 'error' => "unknown custnum $custnum" };
2802 my $pkgnum = $p->{'pkgnum'};
2804 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2806 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2807 'pkgnum' => $pkgnum,
2809 or return { 'error' => "unknown pkgnum $pkgnum" };
2811 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2813 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2814 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2816 return { error=> 'svcpart '. $p->{'svcpart'}. " is not a $class definition" }
2817 if $class ne 'FS::'. $part_svc->svcdb;
2819 warn "creating $class record\n"
2821 my $svc_x = $class->new( {
2822 'pkgnum' => $p->{'pkgnum'},
2823 'svcpart' => $p->{'svcpart'},
2824 map { $_ => $p->{$_} } @$fields
2827 my %insert_args = ();
2828 #i shouldn't be a special case here (pass an option or something)
2829 if ( $class eq 'FS::svc_phone'
2830 && grep length($p->{$_}), @location_editable_fields
2833 $insert_args{'cust_location'} = new FS::cust_location {
2834 map { $_ => $p->{$_} } @location_editable_fields
2838 warn "inserting $class record\n"
2840 my $error = $svc_x->insert(%insert_args);
2843 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2845 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2848 my $return = { 'svc' => $part_svc->svc,
2850 map { $_ => $svc_x->get($_) } @$return_fields
2852 warn "_provision returning ". Dumper($return). "\n"
2861 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2862 return { 'error' => $session } if $context eq 'error';
2864 my $search = { 'custnum' => $custnum };
2865 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2866 my $cust_main = qsearchs('cust_main', $search )
2867 or return { 'error' => "unknown custnum $custnum" };
2869 my $pkgnum = $p->{'pkgnum'};
2871 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2872 'pkgnum' => $pkgnum,
2874 or return { 'error' => "unknown pkgnum $pkgnum" };
2876 my $svcpart = $p->{'svcpart'};
2878 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2879 'svcpart' => $svcpart, } )
2880 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2881 my $part_svc = $pkg_svc->part_svc;
2883 my $conf = new FS::Conf;
2886 'svc' => $part_svc->svc,
2887 'svcdb' => $part_svc->svcdb,
2888 'pkgnum' => $pkgnum,
2889 'svcpart' => $svcpart,
2890 'custnum' => $custnum,
2892 'security_phrase' => 0, #XXX !
2893 'svc_acct_pop' => [], #XXX !
2895 'init_popstate' => '',
2900 small_custview( $cust_main, $conf->config('countrydefault') ),
2904 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2905 && $ret->{'svcdb'} eq 'svc_phone') {
2906 $ret->{'svcnum'} = $p->{'svcnum'};
2907 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2908 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2909 $ret->{'email'} = $svc_phone->email;
2910 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2917 sub unprovision_svc {
2920 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2921 return { 'error' => $session } if $context eq 'error';
2923 my $search = { 'custnum' => $custnum };
2924 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2925 my $cust_main = qsearchs('cust_main', $search )
2926 or return { 'error' => "unknown custnum $custnum" };
2928 my $svcnum = $p->{'svcnum'};
2930 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2931 or return { 'error' => "unknown svcnum $svcnum" };
2933 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2934 unless $cust_svc->cust_pkg->custnum == $custnum;
2936 my $conf = new FS::Conf;
2938 return { 'svc' => $cust_svc->part_svc->svc,
2939 'error' => $cust_svc->cancel,
2941 small_custview( $cust_main, $conf->config('countrydefault') ),
2946 sub myaccount_passwd {
2948 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2949 return { 'error' => $session } if $context eq 'error';
2951 return { 'error' => "New passwords don't match." }
2952 if $p->{'new_password'} ne $p->{'new_password2'};
2954 return { 'error' => 'Enter new password' }
2955 unless length($p->{'new_password'});
2957 #my $search = { 'custnum' => $custnum };
2958 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2959 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2960 my $search = " AND custnum = $1";
2961 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2963 my $svc_acct = qsearchs( {
2964 'table' => 'svc_acct',
2965 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2966 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2967 'LEFT JOIN cust_main USING ( custnum ) ',
2968 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2969 'extra_sql' => $search, #important
2971 or return { 'error' => "Service not found" };
2975 my $conf = new FS::Conf;
2977 return { 'error' => 'Incorrect current password.' }
2978 if ( exists($p->{'old_password'})
2979 || $conf->exists('selfservice-password_change_oldpass')
2981 && ! $svc_acct->check_password($p->{'old_password'});
2983 $error = 'Password too short.'
2984 if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2985 $error = 'Password too long.'
2986 if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2988 $svc_acct->set_password($p->{'new_password'});
2989 $error ||= $svc_acct->replace();
2991 #regular pw change in self-service should change contact pw too, otherwise its
2992 #way too confusing. hell its confusing they're separate at all, but alas.
2993 #need to support the "ISP provides email that's used as a contact email" case
2995 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
2996 if ( $contact && qsearchs('cust_contact', { contactnum=> $contact->contactnum,
2997 custnum => $custnum,
2998 selfservice_access => 'Y',
3002 #svc_acct was successful but this one returns an error? "shouldn't happen"
3003 $error ||= $contact->change_password($p->{'new_password'});
3006 my($label, $value) = $svc_acct->cust_svc->label;
3008 return { 'error' => $error,
3015 # sub contact_passwd {
3017 # my($context, $session, $custnum) = _custoragent_session_custnum($p);
3018 # return { 'error' => $session } if $context eq 'error';
3020 # return { 'error' => 'Not logged in as a contact.' }
3021 # unless $session->{'contactnum'};
3023 # return { 'error' => "New passwords don't match." }
3024 # if $p->{'new_password'} ne $p->{'new_password2'};
3026 # return { 'error' => 'Enter new password' }
3027 # unless length($p->{'new_password'});
3029 # #my $search = { 'custnum' => $custnum };
3030 # #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3031 # $custnum =~ /^(\d+)$/ or die "illegal custnum";
3032 # my $search = " AND selfservice_access IS NOT NULL ".
3033 # " AND selfservice_access = 'Y' ".
3034 # " AND ( disabled IS NULL OR disabled = '' )".
3035 # " AND custnum IS NOT NULL AND custnum = $1";
3036 # $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3038 # my $contact = qsearchs( {
3039 # 'table' => 'contact',
3040 # 'addl_from' => 'LEFT JOIN cust_main USING ( custnum ) ',
3041 # 'hashref' => { 'contactnum' => $session->{'contactnum'}, },
3042 # 'extra_sql' => $search, #important
3044 # or return { 'error' => "Email not found" }; #? how did we get logged in?
3045 # # deleted since then?
3049 # # use these svc_acct length restrictions??
3050 # my $conf = new FS::Conf;
3051 # $error = 'Password too short.'
3052 # if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
3053 # $error = 'Password too long.'
3054 # if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
3056 # $error ||= $contact->change_password($p->{'new_password'});
3058 # return { 'error' => $error, };
3065 my $info = skin_info($p);
3067 my $conf = new FS::Conf;
3068 my $verification = $conf->config('selfservice-password_reset_verification')
3069 or return { %$info, 'error' => 'Password resets disabled' };
3074 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3076 $contact = FS::contact->by_selfservice_email($p->{'email'});
3079 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3080 $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
3083 #also look for an svc_acct, otherwise it would be super confusing
3085 my($username, $domain) = split('@', $p->{'email'});
3086 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3087 if ( $svc_domain ) {
3088 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3089 'domsvc' => $svc_domain->svcnum }
3092 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3093 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3095 #precaution: don't change svc_acct password not part of the same
3096 # customer as contact
3097 $svc_acct = '' if ! $cust_pkg
3098 || $cust_pkg->custnum != $cust_main->custnum;
3103 return { %$info, 'error' => 'Email address not found' }
3104 unless $contact || $svc_acct;
3106 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3108 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3109 or return { %$info, 'error' => 'Account not found' };
3111 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3112 'domsvc' => $svc_domain->svcnum }
3114 or return { %$info, 'error' => 'Account not found' };
3116 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3117 or return { %$info, 'error' => 'Account not found' };
3119 $cust_main = $cust_pkg->cust_main;
3123 return { %$info, 'error' => 'Multi-customer contacts incompatible with customer-based verification' }
3124 if ! $cust_main && $verification ne 'email';
3127 'email' => sub { 1; },
3129 my( $p, $cust_main ) = @_;
3130 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3131 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3134 my( $p, $cust_main ) = @_;
3135 my $cust_pay = qsearchs({
3136 'table' => 'cust_pay',
3137 'hashref' => { 'custnum' => $cust_main->custnum },
3138 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3142 $p->{'amount'} == $cust_pay->paid;
3145 my( $p, $cust_main ) = @_;
3146 $p->{'zip'} eq $cust_main->zip
3147 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3151 foreach my $verify ( split(',', $verification) ) {
3153 &{ $verify{$verify} }( $p, $cust_main )
3154 or return { %$info, 'error' => 'Account not found' };
3158 #okay, we're verified
3162 my $error = $contact->send_reset_email(
3163 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3167 return { %$info, 'error' => $error }; #????
3170 } elsif ( $svc_acct ) {
3172 #create a unique session
3174 my $reset_session = {
3175 'svcnum' => $svc_acct->svcnum,
3179 my $timeout = '1 hour'; #?
3181 my $reset_session_id;
3183 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3184 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3187 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3191 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3192 $cust_main->agentnum);
3193 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3194 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3196 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3197 my $error = $msg_template->send( 'cust_main' => $cust_main,
3198 'object' => $svc_acct,
3199 'substitutions' => {
3200 'session_id' => $reset_session_id,
3204 return { %$info, 'error' => $error }; #????
3209 return { %$info, 'error' => '' };
3212 sub check_reset_passwd {
3215 my $conf = new FS::Conf;
3216 my $verification = $conf->config('selfservice-password_reset_verification')
3217 or return { 'error' => 'Password resets disabled' };
3219 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3220 or return { 'error' => "Can't resume session" }; #better error message
3222 if ( $reset_session->{'svcnum'} ) {
3224 my $svcnum = $reset_session->{'svcnum'};
3226 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3227 or return { 'error' => "Service not found" };
3229 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3230 my $info = skin_info($p);
3234 'session_id' => $p->{'session_id'},
3235 'username' => $svc_acct->username,
3238 } elsif ( $reset_session->{'contactnum'} ) {
3240 my $contactnum = $reset_session->{'contactnum'};
3242 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3243 or return { 'error' => "Contact not found" };
3245 my @contact_email = $contact->contact_email;
3246 return { 'error' => 'No contact email' } unless @contact_email;
3248 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3249 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3250 if scalar(@cust_contact) == 1;
3251 my $info = skin_info($p);
3255 'session_id' => $p->{'session_id'},
3256 'email' => $contact_email[0]->email, #the first?
3261 return { 'error' => 'No svcnum or contactnum in session' }; #??
3267 sub process_reset_passwd {
3270 my $conf = new FS::Conf;
3271 my $verification = $conf->config('selfservice-password_reset_verification')
3272 or return { 'error' => 'Password resets disabled' };
3274 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3275 or return { 'error' => "Can't resume session" }; #better error message
3280 if ( $reset_session->{'svcnum'} ) {
3282 my $svcnum = $reset_session->{'svcnum'};
3284 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3285 or return { 'error' => "Service not found" };
3287 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3288 $info ||= skin_info($p);
3293 if ( $reset_session->{'contactnum'} ) {
3295 my $contactnum = $reset_session->{'contactnum'};
3297 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3298 or return { 'error' => "Contact not found" };
3300 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3301 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3302 if scalar(@cust_contact) == 1;
3303 $info ||= skin_info($p);
3307 return { %$info, 'error' => "New passwords don't match." }
3308 if $p->{'new_password'} ne $p->{'new_password2'};
3310 return { %$info, 'error' => 'Enter new password' }
3311 unless length($p->{'new_password'});
3315 $svc_acct->set_password($p->{'new_password'});
3316 my $error = $svc_acct->replace();
3318 return { %$info, 'error' => $error } if $error;
3320 #my($label, $value) = $svc_acct->cust_svc->label;
3321 #return { 'error' => $error,
3322 # #'label' => $label,
3323 # #'value' => $value,
3330 my $error = $contact->change_password($p->{'new_password'});
3332 return { %$info, 'error' => $error }; # if $error;
3336 #password changed ,so remove session, don't want it reused
3337 _cache->remove($p->{'session_id'});
3339 return { %$info, 'error' => '' };
3345 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3346 return { 'error' => $session } if $context eq 'error';
3349 if ( $session->{'pkgnum'} ) {
3351 #tickets for specific service with pkg-balances on
3352 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3353 'pkgnum' => $session->{'pkgnum'} })
3354 or return { 'error' => 'unknown package' };
3355 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3356 push @tickets, $cust_svc->tickets( $p->{status} );
3361 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3362 or return { 'error' => "unknown custnum $custnum" };
3364 @tickets = $cust_main->tickets( $p->{status} );
3367 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3368 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3369 my $conf = new FS::Conf;
3370 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3374 ($a->{'_selfservice_priority'} eq '') <=>
3375 ($b->{'_selfservice_priority'} eq '')
3378 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3384 +{ tickets => \@tickets };
3391 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3392 return { 'error' => $session } if $context eq 'error';
3394 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3395 FS::TicketSystem->init();
3397 my $conf = new FS::Conf;
3398 my $queue = $p->{'queue'}
3399 || $conf->config('ticket_system-selfservice_queueid')
3400 || $conf->config('ticket_system-default_queueid');
3402 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3403 my $err_or_ticket = FS::TicketSystem->create_ticket(
3404 '', #create RT session based on FS CurrentUser (fs_selfservice)
3406 'custnum' => $custnum,
3407 'svcnum' => $session->{'svcnum'},
3408 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3411 if ( ref($err_or_ticket) ) {
3412 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3414 return { 'error' => '',
3415 'ticket_id' => $err_or_ticket->id,
3418 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3420 return { 'error' => $err_or_ticket };
3428 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3429 return { 'error' => $session } if $context eq 'error';
3431 return { error => 'requested format not implemented' }
3432 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3434 my $conf = new FS::Conf;
3435 my $age_threshold = 0;
3436 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3437 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3439 my $search = { 'custnum' => $custnum };
3440 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3441 my $cust_main = qsearchs('cust_main', $search )
3442 or return { 'error' => "unknown custnum $custnum" };
3444 # does it make more sense to just run one sql query for this instead of all the
3445 # insanity below? would increase performance greately for large data sets?
3447 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3448 my @part_svc = $cust_pkg->part_svc;
3449 foreach my $part_svc ( @part_svc ) {
3450 if($part_svc->svcdb eq 'svc_phone'){
3451 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3452 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3453 push @svc_phone, $cust_pkg_svc->svc_x
3454 if $cust_pkg_svc->date_inserted >= $age_threshold;
3462 my($xls_r,$xls_c) = (0,0);
3465 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3466 if($p->{'format'} eq 'csv') {
3467 $csv = new Text::CSV_XS { 'always_quote' => 1,
3470 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3471 $content .= $csv->string;
3473 elsif($p->{'format'} eq 'xls') {
3474 my $XLS1 = new IO::Scalar \$content;
3475 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3476 or return { 'error' => "Error opening .xls file: $!" };
3477 $xls = $xls_workbook->add_worksheet('DIDs');
3478 foreach ( @fields ) {
3479 $xls->write(0,$xls_c++,$_);
3484 foreach my $svc_phone ( @svc_phone ) {
3485 my @cols = map { $svc_phone->$_ } @fields;
3486 if($p->{'format'} eq 'csv') {
3487 return { 'error' => 'Unable to create CSV' }
3488 unless $csv->combine(@cols);
3489 $content .= $csv->string;
3491 elsif($p->{'format'} eq 'xls') {
3494 $xls->write($xls_r,$xls_c++,$_);
3500 $xls_workbook->close() if $p->{'format'} eq 'xls';
3502 { content => $content, format => $p->{'format'}, };
3507 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3508 return { 'error' => $session } if $context eq 'error';
3510 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3511 # FS::TicketSystem->init();
3512 # return { 'error' => 'get_ticket configuration error' }
3513 # if $FS::TicketSystem::system ne 'RT_Internal';
3515 # check existence and ownership as part of this
3516 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3517 my $rt_session = FS::TicketSystem->session('');
3518 my $Ticket = FS::TicketSystem->get_ticket_object(
3520 ticket_id => $p->{'ticket_id'},
3523 return { 'error' => 'ticket not found' } if !$Ticket;
3525 if ( length( $p->{'subject'} || '' ) ) {
3527 if ( $p->{'subject'} ne $Ticket->Subject ) {
3528 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3529 return { 'error' => "unable to set subject: $msg" } if !$val;
3533 if(length($p->{'reply'})) {
3534 my @err_or_res = FS::TicketSystem->correspond_ticket(
3536 'ticket_id' => $p->{'ticket_id'},
3537 'content' => $p->{'reply'},
3540 return { 'error' => 'unable to reply to ticket' }
3541 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3544 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3545 my $err_or_ticket = FS::TicketSystem->get_ticket(
3547 'ticket_id' => $p->{'ticket_id'},
3550 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3551 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3553 return { 'error' => $err_or_ticket };
3556 my @custs = @{$err_or_ticket->{'custs'}};
3557 my @txns = @{$err_or_ticket->{'txns'}};
3560 # superseded by check in get_ticket_object
3561 #return { 'error' => 'invalid ticket requested' }
3562 #unless grep($_ eq $custnum, @custs);
3564 foreach my $txn ( @txns ) {
3565 push @filtered_txns, $txn
3566 if ($txn->{'type'} eq 'EmailRecord'
3567 || $txn->{'type'} eq 'Correspond'
3568 || $txn->{'type'} eq 'Create');
3571 warn "$me get_ticket: successful: \n"
3573 return { 'error' => '',
3574 'transactions' => \@filtered_txns,
3575 'ticket_fields' => $err_or_ticket->{'fields'},
3576 'ticket_id' => $p->{'ticket_id'},
3580 sub adjust_ticket_priority {
3582 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3583 return { 'error' => $session } if $context eq 'error';
3585 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3586 # FS::TicketSystem->init;
3587 my $ss_priority = FS::TicketSystem->selfservice_priority;
3589 return { 'error' => 'adjust_ticket_priority configuration error' }
3590 if $FS::TicketSystem::system ne 'RT_Internal'
3593 my $values = $p->{'values'}; #hashref, id => priority value
3596 foreach my $id (keys %$values) {
3597 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3598 my $Ticket = FS::TicketSystem->get_ticket_object('',
3600 'custnum' => $custnum,
3603 $ticket_error{$id} = 'ticket not found';
3607 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3608 # We're not going to implement it for RT_External.
3609 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3610 my $new_value = $values->{$id};
3611 next if $old_value eq $new_value;
3613 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3615 # AddCustomFieldValue works fine (replacing any existing value) if it's
3616 # a single-valued custom field, which it should be. If it's not, you're
3617 # doing something wrong.
3619 if ( length($new_value) ) {
3620 ($val, $msg) = $Ticket->AddCustomFieldValue(
3621 Field => $ss_priority,
3622 Value => $new_value,
3626 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3627 Field => $ss_priority,
3628 Value => $old_value,
3632 $ticket_error{$id} = $msg if !$val;
3633 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3635 return { 'error' => '',
3636 'ticket_error' => \%ticket_error,
3637 %{ customer_info($p) } # send updated customer info back
3643 sub _custoragent_session_custnum {
3646 my($context, $session, $custnum);
3647 if ( $p->{'session_id'} ) {
3649 $context = 'customer';
3650 $session = _cache->get($p->{'session_id'})
3651 or return ( 'error' => "Can't resume session" ); #better error message
3652 $custnum = $session->{'custnum'};
3654 } elsif ( $p->{'agent_session_id'} ) {
3657 my $agent_cache = new FS::ClientAPI_SessionCache( {
3658 'namespace' => 'FS::ClientAPI::Agent',
3660 $session = $agent_cache->get($p->{'agent_session_id'})
3661 or return ( 'error' => "Can't resume session" ); #better error message
3662 $custnum = $p->{'custnum'};
3666 return ( 'error' => "Can't resume session" ); #better error message
3669 ($context, $session, $custnum);