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 'menu' => join("\n", $conf->config("ng_selfservice-menu", $agentnum ) ) ||
146 services.php Services
147 services.php My Services
148 services_new.php Order a new service
151 personal.php Personal Information
152 password.php Change Password
155 payment_cc.php Credit Card Payment
156 payment_ach.php Electronic Check Payment
157 payment_paypal.php PayPal Payment
158 payment_webpay.php Webpay Payments
161 usage_data.php Data usage
162 usage_cdr.php Call usage
164 tickets.php Help Desk
165 tickets.php Open Tickets
166 tickets_resolved.php Resolved Tickets
167 ticket_create.php Create a new ticket
175 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
179 #{ %$skin_info_cache_agent };
180 $skin_info_cache_agent;
187 my $conf = new FS::Conf;
191 'phone_login' => $conf->exists('selfservice_server-phone_login'),
192 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
193 'banner_url' => scalar($conf->config('selfservice-login_banner_url')),
194 'banner_image_md5' =>
195 md5_hex($conf->config_binary('selfservice-login_banner_image')),
202 sub login_banner_image {
204 my $conf = new FS::Conf;
205 my $image = $conf->config_binary('selfservice-login_banner_image');
207 'md5' => md5_hex($image),
212 #false laziness w/FS::ClientAPI::passwd::passwd
216 my $conf = new FS::Conf;
220 if ( $p->{'domain'} eq 'svc_phone'
221 && $conf->exists('selfservice_server-phone_login') ) {
223 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
224 return { error => 'Number not found.' } unless $svc_phone;
227 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
228 #return { error => 'Only primary user may log in.' }
229 # if $conf->exists('selfservice_server-primary_only')
230 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
232 return { error => 'Incorrect PIN.' }
233 unless $svc_phone->check_pin($p->{'password'});
237 } elsif ( $p->{email}
238 && (my $contact = FS::contact->by_selfservice_email($p->{email}))
241 return { error => 'Incorrect contact password.' }
242 unless $contact->authenticate_password($p->{'password'});
244 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
245 if ( scalar(@cust_contact) == 1 ) {
246 $session->{'custnum'} = $cust_contact[0]->custnum;
247 } elsif ( scalar(@cust_contact) ) {
248 $session->{'customers'} = { map { $_->custnum => $_->cust_main->name }
252 return { error => 'No customer self-service access for contact' }; #??
257 ( $p->{username}, $p->{domain} ) = split('@', $p->{email}) if $p->{email};
259 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
260 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
262 my $svc_acct = qsearchs( 'svc_acct', { 'username' => $p->{'username'},
263 'domsvc' => $svc_domain->svcnum, }
265 return { error => 'User not found.' } unless $svc_acct;
267 if($conf->exists('selfservice_server-login_svcpart')) {
268 my @svcpart = $conf->config('selfservice_server-login_svcpart');
269 my $svcpart = $svc_acct->cust_svc->svcpart;
270 return { error => 'Invalid user.' }
271 unless grep($_ eq $svcpart, @svcpart);
274 return { error => 'Incorrect password.' }
275 unless $svc_acct->check_password($p->{'password'});
283 $session->{'svcnum'} = $svc_x->svcnum;
285 my $cust_svc = $svc_x->cust_svc;
286 my $cust_pkg = $cust_svc->cust_pkg;
288 my $cust_main = $cust_pkg->cust_main;
289 $session->{'custnum'} = $cust_main->custnum;
290 if ( $conf->exists('pkg-balances') ) {
291 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
292 $cust_main->ncancelled_pkgs;
293 $session->{'pkgnum'} = $cust_pkg->pkgnum
294 if scalar(@cust_pkg) > 1;
298 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
299 #return { error => 'Only primary user may log in.' }
300 # if $conf->exists('selfservice_server-primary_only')
301 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
302 my $part_pkg = $cust_pkg->part_pkg;
303 return { error => 'Only primary user may log in.' }
304 if $conf->exists('selfservice_server-primary_only')
305 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
311 $session_id = sha512_hex(time(). {}. rand(). $$)
312 } until ( ! defined _cache->get($session_id) ); #just in case
314 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
315 _cache->set( $session_id, $session, $timeout );
317 return { 'error' => '',
318 'session_id' => $session_id,
325 my $skin_info = skin_info($p);
326 if ( $p->{'session_id'} ) {
327 _cache->remove($p->{'session_id'});
328 return { %$skin_info, 'error' => '' };
330 return { %$skin_info, 'error' => "Can't resume session" }; #better error message
337 my($context, $session, $custnum) = _custoragent_session_custnum($p);
338 return { 'error' => $session } if $context eq 'error';
340 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
341 or return { 'error' => "Service not found" };
343 $session->{'svcnum'} = $svc_acct->svcnum;
345 my $conf = new FS::Conf;
346 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
347 _cache->set( $p->{'session_id'}, $session, $timeout );
349 return { 'error' => '' };
355 my($context, $session, $custnum) = _custoragent_session_custnum($p);
356 return { 'error' => $session } if $context eq 'error';
358 $session->{'custnum'} = $p->{'custnum'}
359 if exists $session->{'customers'}{ $p->{'custnum'} };
361 my $conf = new FS::Conf;
362 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
363 _cache->set( $p->{'session_id'}, $session, $timeout );
365 return { 'error' => '',
366 %{ customer_info( { session_id=>$p->{'session_id'} } ) },
370 sub payment_gateway {
372 # takes a cust_main and a cust_payby entry, returns the payment_gateway
373 my $conf = new FS::Conf;
374 my $cust_main = shift;
375 my $cust_payby = shift;
376 my $gatewaynum = $conf->config('selfservice-payment_gateway');
378 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
379 die "configured gatewaynum $gatewaynum not found!" if !$pg;
383 return '' if ! FS::payby->realtime($cust_payby);
384 my $pg = $cust_main->agent->payment_gateway(
385 'method' => FS::payby->payby2bop($cust_payby),
395 my $conf = new FS::Conf;
397 my $info = skin_info($p);
399 use vars qw( $cust_paybys ); #cache for performance
400 unless ( $cust_paybys ) {
402 my %cust_paybys = map { $_ => 1 }
403 map { FS::payby->payby2payment($_) }
404 $conf->config('signup_server-payby');
406 $cust_paybys = [ keys %cust_paybys ];
409 $info->{'cust_paybys'} = $cust_paybys;
411 my($context, $session, $custnum) = _custoragent_session_custnum($p);
412 return { 'error' => $session } if $context eq 'error';
414 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } );
416 $info->{'hide_payment_fields'} = [
418 my $pg = $cust_main && payment_gateway($cust_main, $_);
419 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
420 } @{ $info->{cust_paybys} }
423 $info->{'self_suspend_reason'} =
424 $conf->config('selfservice-self_suspend_reason',
425 $cust_main ? $cust_main->agentnum : ''
428 $info->{'edit_ticket_subject'} =
429 $conf->exists('ticket_system-selfservice_edit_subject') &&
430 $cust_main && $cust_main->edit_subject;
432 $info->{'timeout'} = $conf->config('selfservice-timeout') || 3600;
434 $info->{'hide_usage'} = $conf->exists('selfservice_hide-usage');
437 'custnum' => $custnum,
438 'access_pkgnum' => $session->{'pkgnum'},
439 'access_svcnum' => $session->{'svcnum'},
446 my($context, $session, $custnum) = _custoragent_session_custnum($p);
447 return { 'error' => $session } if $context eq 'error';
451 my $conf = new FS::Conf;
452 $return{'require_address2'} = $conf->exists('cust_main-require_address2');
454 # if ( $FS::TicketSystem::system ) {
455 # warn "$me customer_info: initializing ticket system\n" if $DEBUG;
456 # FS::TicketSystem->init();
459 if ( $custnum ) { #customer record
461 %return = ( %return, %{ customer_info_short($p) } );
463 #redundant with customer_info_short, but we need it for several things below
464 my $search = { 'custnum' => $custnum };
465 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
466 my $cust_main = qsearchs('cust_main', $search )
467 or return { 'error' => "customer_info: unknown custnum $custnum" };
469 my $list_tickets = list_tickets($p);
470 $return{'tickets'} = $list_tickets->{'tickets'};
472 if ( $session->{'pkgnum'} ) {
473 #XXX open invoices in the pkg-balances case
477 invnum => $_->invnum,
478 date => time2str("%b %o, %Y", $_->_date),
481 } $cust_main->open_cust_bill;
482 $return{open_invoices} = \@open;
484 my $sql = 'SELECT MAX(_date) FROM cust_bill WHERE custnum = ?';
485 my $sth = dbh->prepare($sql) or die dbh->errstr;
486 $sth->execute($custnum) or die $sth->errstr;
487 $return{'last_invoice_date'} = $sth->fetchrow_arrayref->[0];
488 $return{'last_invoice_date_pretty'} =
489 time2str('%m/%d/%Y', $return{'last_invoice_date'} );
492 #customer_info_short always has nobalance on..
493 $return{small_custview} =
494 small_custview( $cust_main,
495 $return{countrydefault},
496 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
499 $return{has_ship_address} = $cust_main->has_ship_address;
500 $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
501 $return{statuscolor} = $cust_main->statuscolor;
502 $return{status_label} = $cust_main->status_label;
504 # compatibility: some places in selfservice use this to determine
505 # if there's a ship address
506 if ( $return{has_ship_address} ) {
507 $return{ship_last} = $cust_main->last;
508 $return{ship_first} = $cust_main->first;
511 if (scalar($conf->config('support_packages'))) {
512 my @support_services = ();
513 foreach ($cust_main->support_services) {
514 my $seconds = $_->svc_x->seconds || 0;
515 my $time_remaining = (($seconds < 0) ? '-' : '' ).
516 int(abs($seconds)/3600)."h".
517 sprintf("%02d",(abs($seconds)%3600)/60)."m";
518 my $cust_pkg = $_->cust_pkg;
521 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
522 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
523 push @support_services, { svcnum => $_->svcnum,
524 time => $time_remaining,
529 $return{support_services} = \@support_services;
532 if ( $conf->config('prepayment_discounts-credit_type') ) {
534 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
537 } elsif ( $session->{'svcnum'} ) { #no customer record
539 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
540 or die "unknown svcnum";
541 $return{name} = $svc_acct->email;
545 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
549 return { 'error' => '',
550 'custnum' => $custnum,
556 sub customer_info_short {
559 my($context, $session, $custnum) = _custoragent_session_custnum($p);
560 return { 'error' => $session } if $context eq 'error';
564 my $conf = new FS::Conf;
566 if ( $custnum ) { #customer record
568 my $search = { 'custnum' => $custnum };
569 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
570 my $cust_main = qsearchs('cust_main', $search )
571 or return { 'error' => "customer_info_short: unknown custnum $custnum" };
573 $return{display_custnum} = $cust_main->display_custnum;
575 if ( $session->{'pkgnum'} ) {
576 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
577 #next_bill_date from cust_pkg?
579 $return{balance} = $cust_main->balance;
580 $return{next_bill_date} = $cust_main->next_bill_date;
581 $return{next_bill_date_pretty} =
582 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
586 $return{countrydefault} = scalar($conf->config('countrydefault'));
588 $return{small_custview} =
589 small_custview( $cust_main,
590 $return{countrydefault},
594 $return{first} = $cust_main->first;
595 $return{'last'} = $cust_main->get('last');
596 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
598 $return{payby} = $cust_main->payby;
600 #none of these are terribly expensive if we want 'em...
601 for (@cust_main_editable_fields) {
602 $return{$_} = $cust_main->get($_);
604 #maybe a little more expensive, but it should be cached by now
605 for (@location_editable_fields) {
606 $return{$_} = $cust_main->bill_location->get($_)
607 if $cust_main->bill_locationnum;
608 $return{'ship_'.$_} = $cust_main->ship_location->get($_)
609 if $cust_main->ship_locationnum;
612 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
613 $return{payinfo} = $cust_main->paymask;
614 @return{'month', 'year'} = $cust_main->paydate_monthyear;
617 my @invoicing_list = $cust_main->invoicing_list;
618 $return{'invoicing_list'} =
619 join(', ', grep { $_ !~ /^(POST|FAX)$/ } @invoicing_list );
620 $return{'postal_invoicing'} =
621 0 < ( grep { $_ eq 'POST' } @invoicing_list );
623 if ( $session->{'svcnum'} ) {
624 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
625 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
626 $return{'svcnum'} = $session->{'svcnum'};
629 } elsif ( $session->{'svcnum'} ) { #no customer record
631 #uuh, not supproted yet... die?
632 return { 'error' => 'customer_info_short not yet supported as agent' };
636 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
640 return { 'error' => '',
641 'custnum' => $custnum,
646 sub billing_history {
649 my($context, $session, $custnum) = _custoragent_session_custnum($p);
650 return { 'error' => $session } if $context eq 'error';
652 return { 'error' => 'No customer' } unless $custnum;
654 my $search = { 'custnum' => $custnum };
655 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
656 my $cust_main = qsearchs('cust_main', $search )
657 or return { 'error' => "unknown custnum $custnum" };
661 if ( $session->{'pkgnum'} ) {
662 #$return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
663 #next_bill_date from cust_pkg?
664 return { 'error' => 'No history for package' };
667 $return{balance} = $cust_main->balance;
668 $return{next_bill_date} = $cust_main->next_bill_date;
669 $return{next_bill_date_pretty} =
670 $return{next_bill_date} ? time2str('%m/%d/%Y', $return{next_bill_date} )
675 my $conf = new FS::Conf;
677 if ( $conf->exists('selfservice-billing_history-line_items') ) {
679 foreach my $cust_bill ( $cust_main->cust_bill ) {
682 'type' => 'Line item',
683 'description' => $_->desc( $cust_main->locale ).
684 ( $_->sdate && $_->edate
685 ? ' '. time2str('%d-%b-%Y', $_->sdate).
686 ' To '. time2str('%d-%b-%Y', $_->edate)
689 'amount' => sprintf('%.2f', $_->setup + $_->recur ),
690 'date' => $cust_bill->_date,
691 'date_pretty' => time2str('%m/%d/%Y', $cust_bill->_date ),
693 foreach $cust_bill->cust_bill_pkg;
701 'description' => 'Invoice #'. $_->display_invnum,
702 'amount' => sprintf('%.2f', $_->charged ),
704 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
706 foreach $cust_main->cust_bill;
712 'description' => 'Payment', #XXX type
713 'amount' => sprintf('%.2f', 0 - $_->paid ),
715 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
717 foreach $cust_main->cust_pay;
721 'description' => 'Credit', #more info?
722 'amount' => sprintf('%.2f', 0 -$_->amount ),
724 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
726 foreach $cust_main->cust_credit;
730 'description' => 'Refund', #more info? type, like payment?
731 'amount' => $_->refund,
733 'date_pretty' => time2str('%m/%d/%Y', $_->_date ),
735 foreach $cust_main->cust_refund;
737 @history = sort { $b->{'date'} <=> $a->{'date'} } @history;
739 $return{'history'} = \@history;
747 my $session = _cache->get($p->{'session_id'})
748 or return { 'error' => "Can't resume session" }; #better error message
750 my $custnum = $session->{'custnum'}
751 or return { 'error' => "no customer record" };
753 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
754 or return { 'error' => "unknown custnum $custnum" };
756 my $new = new FS::cust_main { $cust_main->hash };
758 $new->set( $_ => $p->{$_} )
759 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
761 if ( exists($p->{address1}) ) {
762 my $bill_location = FS::cust_location->new({
763 map { $_ => $p->{$_} } @location_editable_fields
765 # if this is unchanged from before, cust_main::replace will ignore it
766 $new->set('bill_location' => $bill_location);
769 if ( exists($p->{ship_address1}) ) {
770 my $ship_location = FS::cust_location->new({
771 map { $_ => $p->{"ship_$_"} } @location_editable_fields
773 if ( !grep { length($p->{"ship_$_"}) } @location_editable_fields ) {
774 # Selfservice unfortunately tries to indicate "same as billing
775 # address" by sending all fields empty. Did this ever work?
776 $ship_location = $cust_main->bill_location;
778 $new->set('ship_location' => $ship_location);
780 # but if it hasn't been passed in at all, leave ship_location alone--
781 # DON'T change it to match bill_location.
784 if (exists($p->{'payby'})) {
785 $p->{'payby'} =~ /^([A-Z]{4})$/
786 or return { 'error' => "illegal_payby " . $p->{'payby'} };
790 my $conf = new FS::Conf;
792 if ( $payby =~ /^(CARD|DCRD)$/ ) {
794 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
796 if ( $new->payinfo eq $cust_main->paymask ) {
797 $new->payinfo($cust_main->payinfo);
799 $new->payinfo($p->{'payinfo'});
802 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
804 if ( $conf->exists('selfservice-onfile_require_cvv') ){
805 return { 'error' => 'CVV2 is required' } unless $p->{'paycvv'};
808 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
811 $p->{'payinfo1'} =~ /^([\dx]+)$/
812 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
814 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by echeck-country CA ?
815 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
817 $payinfo = $payinfo1. '@'. $payinfo2;
819 $new->payinfo( ($payinfo eq $cust_main->paymask)
820 ? $cust_main->payinfo
824 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
826 } elsif ( $payby =~ /^(BILL)$/ ) {
828 } elsif ( $payby ) { #notyet ready
829 return { 'error' => "unknown payby $payby" };
833 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
834 #false laziness with httemplate/edit/process/cust_main.cgi
835 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
836 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
838 @invoicing_list = $cust_main->invoicing_list;
841 my $error = $new->replace($cust_main, \@invoicing_list);
842 return { 'error' => $error } if $error;
845 return { 'error' => '' };
850 my $session = _cache->get($p->{'session_id'})
851 or return { 'error' => "Can't resume session" }; #better error message
857 my $conf = new FS::Conf;
858 use vars qw($payment_info); #cache for performance
859 unless ( $payment_info ) {
861 my %states = map { $_->state => 1 }
862 qsearch('cust_main_county', {
863 'country' => $conf->config('countrydefault') || 'US'
866 my %cust_paybys = map { $_ => 1 }
867 map { FS::payby->payby2payment($_) }
868 $conf->config('signup_server-payby');
870 my @cust_paybys = keys %cust_paybys;
874 #list all counties/states/countries
875 'cust_main_county' =>
876 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
878 #shortcut for one-country folks
880 [ sort { $a cmp $b } keys %states ],
882 'card_types' => card_types(),
884 'withcvv' => $conf->exists('selfservice-require_cvv'), #or enable optional cvv?
885 'require_cvv' => $conf->exists('selfservice-require_cvv'),
886 'onfile_require_cvv' => $conf->exists('selfservice-onfile_require_cvv'),
888 'paytypes' => [ @FS::cust_main::paytypes ],
890 'paybys' => [ $conf->config('signup_server-payby') ],
891 'cust_paybys' => \@cust_paybys,
893 'stateid_label' => FS::Msgcat::_gettext('stateid'),
894 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
896 'show_ss' => $conf->exists('show_ss'),
897 'show_stateid' => $conf->exists('show_stateid'),
898 'show_paystate' => $conf->exists('show_bankstate'),
900 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
902 'credit_card_surcharge_percentage' => scalar($conf->config('credit-card-surcharge-percentage')),
911 my %return = %$payment_info;
913 my $custnum = $session->{'custnum'};
915 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
916 or return { 'error' => "unknown custnum $custnum" };
918 $return{'hide_payment_fields'} = [
920 my $pg = payment_gateway($cust_main, $_);
921 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
922 } @{ $return{cust_paybys} }
925 $return{balance} = $cust_main->balance; #XXX pkg-balances?
927 $return{payname} = $cust_main->payname
928 || ( $cust_main->first. ' '. $cust_main->get('last') );
930 $return{$_} = $cust_main->bill_location->get($_)
931 for qw(address1 address2 city state zip);
933 $return{payby} = $cust_main->payby;
934 $return{stateid_state} = $cust_main->stateid_state;
936 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
937 $return{card_type} = cardtype($cust_main->payinfo);
938 $return{payinfo} = $cust_main->paymask;
940 @return{'month', 'year'} = $cust_main->paydate_monthyear;
944 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
945 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
946 $return{payinfo1} = $payinfo1;
947 $return{payinfo2} = $payinfo2;
948 $return{paytype} = $cust_main->paytype;
949 $return{paystate} = $cust_main->paystate;
950 $return{payname} = $cust_main->payname; # override 'first/last name' default from above, if any. Is instution-name here. (#15819)
953 if ( $conf->config('prepayment_discounts-credit_type') ) {
955 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
958 #doubleclick protection
960 $return{payunique} = "webui-MyAccount-$_date-$$-". rand() * 2**32; #new
961 $return{paybatch} = $return{payunique}; #back compat
963 return { 'error' => '',
969 #some false laziness with httemplate/process/payment.cgi - look there for
970 #ACH and CVV support stuff
972 sub validate_payment {
975 my $session = _cache->get($p->{'session_id'})
976 or return { 'error' => "Can't resume session" }; #better error message
978 my $custnum = $session->{'custnum'};
980 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
981 or return { 'error' => "unknown custnum $custnum" };
983 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
984 or return { 'error' => gettext('illegal_amount') };
986 return { error => 'Amount must be greater than 0' } unless $amount > 0;
988 #false laziness w/tr-amount_fee.html, but we don't want selfservice users
989 #changing the hidden form values
990 my $conf = new FS::Conf;
991 my $fee_display = $conf->config('selfservice_process-display') || 'add';
992 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
993 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
994 if ( $fee_display eq 'add'
996 and ! $fee_skip_first || scalar($cust_main->cust_pay)
999 my $fee_pkg = qsearchs('part_pkg', { pkgpart=>$fee_pkgpart } );
1000 $amount = sprintf('%.2f', $amount + $fee_pkg->option('setup_fee') );
1003 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
1004 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
1005 my $discount_term = $1;
1007 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
1008 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
1011 $p->{'payunique'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1012 or return { 'error' => gettext('illegal_text'). " payunique: ". $p->{'payunique'} };
1015 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1016 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
1019 $payunique = $paybatch if ! length($payunique) && length($paybatch);
1021 $p->{'payby'} ||= 'CARD';
1022 $p->{'payby'} =~ /^([A-Z]{4})$/
1023 or return { 'error' => "illegal_payby " . $p->{'payby'} };
1026 #false laziness w/process/payment.cgi
1029 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
1031 $p->{'payinfo1'} =~ /^([\dx]+)$/
1032 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
1034 $p->{'payinfo2'} =~ /^([\dx]+)$/
1035 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
1037 $payinfo = $payinfo1. '@'. $payinfo2;
1039 $payinfo = $cust_main->payinfo
1040 if $cust_main->paymask eq $payinfo;
1042 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
1044 $payinfo = $p->{'payinfo'};
1048 #more intelligent matching will be needed here if you change
1049 #card_masking_method and don't remove existing paymasks
1050 if ( $cust_main->paymask eq $payinfo ) {
1051 $payinfo = $cust_main->payinfo;
1055 $payinfo =~ s/\D//g;
1056 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
1057 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1061 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
1062 return { 'error' => gettext('unknown_card_type') }
1063 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
1065 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
1066 if ( cardtype($payinfo) eq 'American Express card' ) {
1067 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
1068 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
1071 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
1072 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
1075 } elsif ( $conf->exists('selfservice-onfile_require_cvv') ) {
1076 return { 'error' => 'CVV2 is required' };
1077 } elsif ( !$onfile && $conf->exists('selfservice-require_cvv') ) {
1078 return { 'error' => 'CVV2 is required' };
1082 die "unknown payby $payby";
1085 my %payby2fields = (
1086 'CARD' => [ qw( paystart_month paystart_year payissue payip
1087 address1 address2 city state zip country ) ],
1088 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
1092 $card_type = cardtype($payinfo) if $payby eq 'CARD';
1095 'cust_main' => $cust_main, #XXX or just custnum??
1096 'amount' => sprintf('%.2f', $amount),
1098 'payinfo' => $payinfo,
1099 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
1100 'card_type' => $card_type,
1101 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
1102 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
1103 'month' => $p->{'month'},
1104 'year' => $p->{'year'},
1105 'payname' => $payname,
1106 'payunique' => $payunique,
1107 'paybatch' => $paybatch,
1108 'paycvv' => $paycvv,
1109 'payname' => $payname,
1110 'discount_term' => $discount_term,
1111 'pkgnum' => $session->{'pkgnum'},
1112 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
1122 my $validate = validate_payment($p);
1123 return $validate if $validate->{'error'};
1125 my $conf = new FS::Conf;
1126 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
1127 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
1129 +{ map { $_=>$validate->{$_} }
1130 qw( card_type paymask payname paydate_pretty month year amount
1131 address1 address2 city state zip country
1137 sub process_stored_payment {
1140 my $session_id = $p->{'session_id'};
1142 my $payment_info = _cache->get( "payment_$session_id" )
1143 or return { 'error' => "Can't resume session" }; #better error message
1145 do_process_payment($payment_info);
1149 sub process_payment {
1152 my $payment_info = validate_payment($p);
1153 return $payment_info if $payment_info->{'error'};
1155 do_process_payment($payment_info);
1159 sub do_process_payment {
1160 my $validate = shift;
1162 my $cust_main = $validate->{'cust_main'};
1164 my $amount = delete $validate->{'amount'};
1167 my $payby = delete $validate->{'payby'};
1169 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
1173 'paynum_ref' => \$paynum,
1176 return { 'error' => $error } if $error;
1178 #no error, so order the fee package if applicable...
1179 my $conf = new FS::Conf;
1180 my $fee_pkgpart = $conf->config('selfservice_process-pkgpart', $cust_main->agentnum);
1181 my $fee_skip_first = $conf->exists('selfservice_process-skip_first');
1183 if ( $fee_pkgpart and ! $fee_skip_first || scalar($cust_main->cust_pay) ) {
1185 my $cust_pkg = new FS::cust_pkg { 'pkgpart' => $fee_pkgpart };
1187 $error = $cust_main->order_pkg( 'cust_pkg' => $cust_pkg );
1188 return { 'error' => "payment processed successfully, but error ordering fee: $error" }
1191 #and generate an invoice for it now too
1192 $error = $cust_main->bill( 'pkg_list' => [ $cust_pkg ] );
1193 return { 'error' => "payment processed and fee ordered sucessfully, but error billing fee: $error" }
1198 $cust_main->apply_payments;
1200 if ( $validate->{'save'} ) {
1201 my $new = new FS::cust_main { $cust_main->hash };
1202 if ($payby eq 'CARD' || $payby eq 'DCRD') {
1203 $new->set( $_ => $validate->{$_} )
1204 foreach qw( payname paystart_month paystart_year payissue payip );
1205 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
1207 my $bill_location = FS::cust_location->new({
1208 map { $_ => $validate->{$_} }
1209 qw(address1 address2 city state country zip)
1211 $new->set('bill_location' => $bill_location);
1212 # but don't allow the service address to change this way.
1214 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
1215 $new->set( $_ => $validate->{$_} )
1216 foreach qw( payname payip paytype paystate
1217 stateid stateid_state );
1218 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
1220 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
1221 $new->set( 'paydate' => $validate->{'paydate'} );
1222 my $error = $new->replace($cust_main);
1224 #no, this causes customers to process their payments again
1225 #return { 'error' => $error };
1226 #XXX just warn verosely for now so i can figure out how these happen in
1227 # the first place, eventually should redirect them to the "change
1228 #address" page but indicate the payment did process??
1229 delete($validate->{'payinfo'}); #don't want to log this!
1230 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
1231 "NEW: ". Dumper($new)."\n".
1232 "OLD: ". Dumper($cust_main)."\n".
1233 "PACKET: ". Dumper($validate)."\n";
1241 my $receipt_html = '';
1243 # currently supported for realtime CC only; send receipt data to SS
1244 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
1247 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
1250 <TD ALIGN="right">Payment#</TD>
1251 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
1255 <TD ALIGN="right">Date</TD>
1257 <TD BGCOLOR="#FFFFFF"><B>! .
1258 time2str("%a %b %o, %Y %r", $cust_pay->_date)
1264 <TD ALIGN="right">Amount</TD>
1265 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
1270 <TD ALIGN="right">Payment method</TD>
1271 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
1284 'amount' => sprintf('%.2f', $cust_pay->paid),
1285 'date' => $cust_pay->_date,
1286 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
1287 'time_pretty' => time2str('%T', $cust_pay->_date),
1288 'auth_num' => $cust_pay->auth,
1289 'order_num' => $cust_pay->order_number,
1290 'receipt_html' => $receipt_html,
1297 'receipt_html' => '',
1304 sub realtime_collect {
1307 my $session = _cache->get($p->{'session_id'})
1308 or return { 'error' => "Can't resume session" }; #better error message
1310 my $custnum = $session->{'custnum'};
1312 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1313 or return { 'error' => "unknown custnum $custnum" };
1316 if ( $p->{'amount'} ) {
1317 $amount = $p->{'amount'};
1319 elsif ( $session->{'pkgnum'} ) {
1320 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1323 $amount = $cust_main->balance;
1326 my $error = $cust_main->realtime_collect(
1327 'method' => $p->{'method'},
1328 'amount' => $amount,
1329 'pkgnum' => $session->{'pkgnum'},
1330 'session_id' => $p->{'session_id'},
1334 return { 'error' => $error } unless ref( $error );
1336 return { 'error' => '', amount => $amount, %$error };
1339 sub start_thirdparty {
1341 my $session = _cache->get($p->{'session_id'})
1342 or return { 'error' => "Can't resume session" }; #better error message
1343 my $custnum = $session->{'custnum'};
1344 my $cust_main = FS::cust_main->by_key($custnum);
1346 my $amount = $p->{'amount'}
1347 or return { error => 'no amount' };
1349 my $result = $cust_main->create_payment(
1350 'method' => $p->{'method'},
1351 'amount' => $p->{'amount'},
1352 'pkgnum' => $session->{'pkgnum'},
1353 'session_id' => $p->{'session_id'},
1356 if ( ref($result) ) { # hashref or error
1359 return { error => $result };
1363 sub finish_thirdparty {
1365 my $session_id = delete $p->{'session_id'};
1366 my $session = _cache->get($session_id)
1367 or return { 'error' => "Can't resume session" };
1368 my $custnum = $session->{'custnum'};
1369 my $cust_main = FS::cust_main->by_key($custnum);
1371 if ( $p->{_cancel} ) {
1372 # customer backed out of making a payment
1373 return $cust_main->cancel_payment( $session_id );
1375 my $result = $cust_main->execute_payment( $session_id, %$p );
1376 if ( ref($result) ) {
1379 return { error => $result };
1383 sub process_payment_order_pkg {
1386 my $hr = process_payment($p);
1387 return $hr if $hr->{'error'};
1392 sub process_payment_order_renew {
1395 my $hr = process_payment($p);
1396 return $hr if $hr->{'error'};
1401 sub process_prepay {
1405 my $session = _cache->get($p->{'session_id'})
1406 or return { 'error' => "Can't resume session" }; #better error message
1410 my $custnum = $session->{'custnum'};
1412 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1413 or return { 'error' => "unknown custnum $custnum" };
1415 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1416 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1424 return { 'error' => $error } if $error;
1426 return { 'error' => '',
1427 'amount' => $amount,
1428 'seconds' => $seconds,
1429 'duration' => duration_exact($seconds),
1430 'upbytes' => $upbytes,
1431 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1432 'downbytes' => $downbytes,
1433 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1434 'totalbytes'=> $totalbytes,
1435 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1442 my $session = _cache->get($p->{'session_id'})
1443 or return { 'error' => "Can't resume session" }; #better error message
1445 my $custnum = $session->{'custnum'};
1447 my $invnum = $p->{'invnum'};
1449 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1450 'custnum' => $custnum } )
1451 or return { 'error' => "Can't find invnum" };
1455 return { 'error' => '',
1456 'invnum' => $invnum,
1457 'invoice_text' => join('', $cust_bill->print_text ),
1458 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1465 my $session = _cache->get($p->{'session_id'})
1466 or return { 'error' => "Can't resume session" }; #better error message
1468 my $custnum = $session->{'custnum'};
1470 my $invnum = $p->{'invnum'};
1472 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1473 'custnum' => $custnum } )
1474 or return { 'error' => "Can't find invnum" };
1478 return { 'error' => '',
1479 'invnum' => $invnum,
1480 'invoice_pdf' => $cust_bill->print_pdf({
1481 'unsquelch_cdr' => 1,
1482 'locale' => $p->{'locale'},
1488 sub legacy_invoice {
1490 my $session = _cache->get($p->{'session_id'})
1491 or return { 'error' => "Can't resume session" }; #better error message
1493 my $custnum = $session->{'custnum'};
1495 my $legacyinvnum = $p->{'legacyinvnum'};
1498 'legacyinvnum' => $legacyinvnum,
1499 'custnum' => $custnum,
1502 my $legacy_cust_bill =
1503 qsearchs('legacy_cust_bill', { %hash, 'locale' => $p->{'locale'} } )
1504 || qsearchs('legacy_cust_bill', \%hash )
1505 or return { 'error' => "Can't find legacyinvnum" };
1509 return { 'error' => '',
1510 'legacyinvnum' => $legacyinvnum,
1511 'legacyid' => $legacy_cust_bill->legacyid,
1512 'invoice_html' => $legacy_cust_bill->content_html,
1517 sub legacy_invoice_pdf {
1519 my $session = _cache->get($p->{'session_id'})
1520 or return { 'error' => "Can't resume session" }; #better error message
1522 my $custnum = $session->{'custnum'};
1524 my $legacyinvnum = $p->{'legacyinvnum'};
1526 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1527 'legacyinvnum' => $legacyinvnum,
1528 'custnum' => $custnum,
1529 }) or return { 'error' => "Can't find legacyinvnum" };
1533 return { 'error' => '',
1534 'legacyinvnum' => $legacyinvnum,
1535 'legacyid' => $legacy_cust_bill->legacyid,
1536 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1544 #sessioning for this? how do we get the session id to the backend invoice
1545 # template so it can add it to the link, blah
1548 if ( $p->{'invnum'} ) {
1549 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1550 or return { 'error' => 'unknown invnum' };
1551 $agentnum = $cust_bill->cust_main->agentnum;
1554 my $templatename = $p->{'template'} || $p->{'templatename'};
1556 #false laziness-ish w/view/cust_bill-logo.cgi
1558 my $conf = new FS::Conf;
1559 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1560 $templatename = "_$1";
1565 my $filename = "logo$templatename.png";
1567 return { 'error' => '',
1568 'logo' => $conf->config_binary($filename, $agentnum),
1569 'content_type' => 'image/png', #should allow gif, jpg too
1576 my $session = _cache->get($p->{'session_id'})
1577 or return { 'error' => "Can't resume session" }; #better error message
1579 my $custnum = $session->{'custnum'};
1581 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1582 or return { 'error' => "unknown custnum $custnum" };
1584 my $conf = new FS::Conf;
1586 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1588 my @cust_bill = grep ! $_->hide, $cust_main->cust_bill;
1592 return { 'error' => '',
1593 'balance' => $cust_main->balance,
1596 my $owed = $_->owed;
1598 +{ 'invnum' => $_->invnum,
1599 '_date' => $_->_date,
1600 'date' => time2str("%b %o, %Y", $_->_date),
1601 'date_short' => time2str("%m-%d-%Y", $_->_date),
1602 'previous' => sprintf('%.2f', ($_->previous)[0]),
1603 'charged' => sprintf('%.2f', $_->charged),
1604 'owed' => sprintf('%.2f', $owed),
1605 'balance' => sprintf('%.2f', $balance),
1610 'legacy_invoices' => [
1612 +{ 'legacyinvnum' => $_->legacyinvnum,
1613 'legacyid' => $_->legacyid,
1614 '_date' => $_->_date,
1615 'date' => time2str("%b %o, %Y", $_->_date),
1616 'date_short' => time2str("%m-%d-%Y", $_->_date),
1617 'charged' => sprintf('%.2f', $_->charged),
1618 'has_content' => ( length($_->content_pdf)
1619 || length($_->content_html) ),
1629 my $session = _cache->get($p->{'session_id'})
1630 or return { 'error' => "Can't resume session" }; #better error message
1632 my $custnum = $session->{'custnum'};
1634 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1635 or return { 'error' => "unknown custnum $custnum" };
1637 my @errors = $cust_main->cancel( 'quiet'=>1 );
1639 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1641 return { 'error' => $error };
1648 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1649 return { 'error' => $session } if $context eq 'error';
1651 my $search = { 'custnum' => $custnum };
1652 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1653 my $cust_main = qsearchs('cust_main', $search )
1654 or return { 'error' => "unknown custnum $custnum" };
1656 my $conf = new FS::Conf;
1657 my $immutable = $conf->exists('selfservice_immutable-package');
1659 # the duplication below is necessary:
1660 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1661 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1662 # non-backwards-compatible change breaking the software of anyone using the API
1663 # instead of the stock selfservice
1664 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1665 if( $conf->exists('selfservice_server-view-wholesale') ) {
1666 return { 'svcnum' => $session->{'svcnum'},
1667 'custnum' => $custnum,
1668 'cust_pkg' => [ map {
1670 immutable => $immutable,
1671 part_pkg => [ map $_->hashref, $_->part_pkg ],
1673 [ map $_->hashref, $_->available_part_svc ],
1675 [ map { my $ref = { $_->hash,
1676 label => [ $_->label ],
1678 $ref->{_password} = $_->svc_x->_password
1679 if $context eq 'agent'
1680 && $conf->exists('agent-showpasswords')
1681 && $_->part_svc->svcdb eq 'svc_acct';
1686 } $cust_main->cust_pkg
1689 small_custview( $cust_main, $conf->config('countrydefault') ),
1690 'wholesale_view' => 1,
1691 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1692 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1693 'lnp' => $conf->exists('svc_phone-lnp'),
1697 { 'svcnum' => $session->{'svcnum'},
1698 'custnum' => $custnum,
1699 'cust_pkg' => [ map {
1700 my $primary_cust_svc = $_->primary_cust_svc;
1703 immutable => $immutable,
1704 pkg_label => $_->pkg_locale,
1705 status => $_->status,
1706 statuscolor => $_->statuscolor,
1708 [ map { $_->hashref }
1709 grep { $_->selfservice_access ne 'hidden' }
1710 $_->available_part_svc
1713 [ map { my $ref = { $_->hash,
1714 label => [ $_->label ],
1716 $ref->{_password} = $_->svc_x->_password
1717 if $context eq 'agent'
1718 && $conf->exists('agent-showpasswords')
1719 && $_->part_svc->svcdb eq 'svc_acct';
1720 $ref->{svchash} = { $_->svc_x->hash } if
1721 $_->part_svc->svcdb eq 'svc_phone';
1722 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1723 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1726 grep { $_->part_svc->selfservice_access ne 'hidden' }
1731 ? { $primary_cust_svc->hash,
1732 label => [ $primary_cust_svc->label ],
1733 finger => $primary_cust_svc->svc_x->finger, #uuh
1734 $primary_cust_svc->part_svc->hash,
1738 } $cust_main->ncancelled_pkgs
1741 small_custview( $cust_main, $conf->config('countrydefault') ),
1742 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1750 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1751 return { 'error' => $session } if $context eq 'error';
1753 my $conf = new FS::Conf;
1755 my $hide_usage = $conf->exists('selfservice_hide-usage') ? 1 : 0;
1756 my $search = { 'custnum' => $custnum };
1757 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1758 my $cust_main = qsearchs('cust_main', $search )
1759 or return { 'error' => "unknown custnum $custnum" };
1761 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1762 if ( ! $pkgnum && $p->{'svcnum'} ) {
1763 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1764 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1768 my @cust_pkg_usage = ();
1769 foreach my $cust_pkg ( $p->{'ncancelled'}
1770 ? $cust_main->ncancelled_pkgs
1771 : $cust_main->unsuspended_pkgs ) {
1772 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1773 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1774 push @cust_pkg_usage, $cust_pkg->cust_pkg_usage;
1777 @cust_svc = grep { $_->part_svc->selfservice_access ne 'hidden' } @cust_svc;
1780 foreach (@cust_pkg_usage) {
1781 my $part = $_->part_pkg_usage;
1782 my $tag = $part->description . ($part->shared ? 1 : 0);
1783 my $row = $usage_pools{$tag}
1784 ||= [ $part->description, 0, 0, $part->shared ? 1 : 0 ];
1785 $row->[1] += sprintf('%.1f', $_->minutes); # minutes remaining
1786 $row->[2] += $part->minutes; # minutes total
1788 } # otherwise just leave them empty
1790 if ( $p->{'svcdb'} ) {
1791 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1793 : ref($p->{'svcdb'}) eq 'ARRAY'
1794 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1795 : { $p->{'svcdb'} => 1 };
1796 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1799 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1802 my @svcs; # stuff to return to the client
1803 foreach my $cust_svc (@cust_svc) {
1804 my $svc_x = $cust_svc->svc_x;
1805 my($label, $value) = $cust_svc->label;
1806 my $part_svc = $cust_svc->part_svc;
1807 my $svcdb = $part_svc->svcdb;
1808 my $cust_pkg = $cust_svc->cust_pkg;
1809 my $part_pkg = $cust_pkg->part_pkg;
1812 'svcnum' => $cust_svc->svcnum,
1813 'display_svcnum' => $cust_svc->display_svcnum,
1817 'pkg_label' => $cust_pkg->pkg_locale,
1818 'pkg_status' => $cust_pkg->status,
1819 'readonly' => ($part_svc->selfservice_access eq 'readonly'),
1822 # would it make sense to put this in a svc_* method?
1824 if ( $svcdb eq 'svc_acct' ) {
1825 foreach (qw(username email finger seconds)) {
1826 $hash{$_} = $svc_x->$_;
1832 'upbytes' => display_bytecount($svc_x->upbytes),
1833 'downbytes' => display_bytecount($svc_x->downbytes),
1834 'totalbytes' => display_bytecount($svc_x->totalbytes),
1836 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1837 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1838 'recharge_upbytes' =>
1839 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1840 'recharge_downbytes' =>
1841 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1842 'recharge_totalbytes' =>
1843 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1848 } elsif ( $svcdb eq 'svc_dsl' ) {
1850 $hash{'phonenum'} = $svc_x->phonenum;
1851 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1852 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1853 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1856 $hash{'name'} = $cust_main->name;
1858 # no usage to hide here
1860 } elsif ( $svcdb eq 'svc_phone' ) {
1862 # could potentially show lots of things...
1863 $hash{'outbound'} = 1;
1864 $hash{'inbound'} = 0;
1865 if ( $part_pkg->plan eq 'voip_inbound' ) {
1866 $hash{'outbound'} = 0;
1867 $hash{'inbound'} = 1;
1868 } elsif ( $part_pkg->option('selfservice_inbound_format')
1869 or $conf->config('selfservice-default_inbound_cdr_format')
1871 $hash{'inbound'} = 1;
1873 foreach (qw(inbound outbound)) {
1874 # hmm...we can't filter by status here, because there might
1875 # not be cdr_terminations at all. have to go by date.
1876 # find all since the last bill date.
1877 # XXX cdr types? we are going to need them.
1879 my $sum_cdr = $svc_x->sum_cdrs(
1880 'inbound' => ( $_ eq 'inbound' ? 1 : 0 ),
1881 'begin' => ($cust_pkg->last_bill || 0),
1883 'disable_charged_party' => 1,
1885 $hash{$_} = $sum_cdr->hashref;
1888 } # not hiding usage
1892 } # foreach $cust_svc
1895 'svcnum' => $session->{'svcnum'},
1896 'custnum' => $custnum,
1897 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1898 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1901 map { $usage_pools{$_} }
1905 'hide_usage' => $hide_usage,
1910 sub _customer_svc_x {
1911 my($custnum, $svcnum, $table) = (shift, shift, shift);
1912 my $hashref = ref($svcnum) ? $svcnum : { 'svcnum' => $svcnum };
1914 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1915 my $search = " AND custnum = $1";
1916 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1919 'table' => ($table || 'svc_acct'),
1920 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1921 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1922 #'LEFT JOIN cust_main USING ( custnum ) ',
1923 'hashref' => $hashref,
1924 'extra_sql' => $search, #important
1929 sub svc_status_html {
1932 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1933 return { 'error' => $session } if $context eq 'error';
1935 #XXX only svc_dsl for now
1936 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl')
1937 or return { 'error' => "Service not found" };
1939 my $html = $svc_x->getstatus_html;
1941 return { 'html' => $html };
1945 sub svc_status_hash {
1948 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1949 return { 'error' => $session } if $context eq 'error';
1951 #XXX only svc_acct for now
1952 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1953 or return { 'error' => "Service not found" };
1955 my ( $html, $hashref ) = $svc_x->export_getstatus;
1960 sub set_svc_status_hash { _svc_method_X(shift, 'export_setstatus') }
1961 sub set_svc_status_listadd { _svc_method_X(shift, 'export_setstatus_listadd') }
1962 sub set_svc_status_listdel { _svc_method_X(shift, 'export_setstatus_listdel') }
1963 sub set_svc_status_vacationadd { _svc_method_X(shift, 'export_setstatus_vacationadd') }
1964 sub set_svc_status_vacationdel { _svc_method_X(shift, 'export_setstatus_vacationdel') }
1967 my( $p, $method ) = @_;
1969 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1970 return { 'error' => $session } if $context eq 'error';
1972 #XXX only svc_acct for now
1973 my $svc_x = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct')
1974 or return { 'error' => "Service not found" };
1976 warn "$method ". join(' / ', map "$_=>".$p->{$_}, keys %$p )
1978 my $error = $svc_x->$method($p); #$p? returns error?
1979 return { 'error' => $error } if $error;
1981 return {}; #? { 'error' => '' }
1985 sub acct_forward_info {
1988 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1989 return { 'error' => $session } if $context eq 'error';
1991 my $svc_forward = _customer_svc_x( $custnum,
1992 { 'srcsvc' => $p->{'svcnum'} },
1995 or return { 'error' => '',
1999 return { 'error' => '',
2000 'dst' => $svc_forward->dst || $svc_forward->dstsvc_acct->email,
2005 sub process_acct_forward {
2007 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2008 return { 'error' => $session } if $context eq 'error';
2010 my $old = _customer_svc_x( $custnum,
2011 { 'srcsvc' => $p->{'svcnum'} },
2015 if ( $p->{'dst'} eq '' ) {
2017 my $error = $old->delete;
2018 return { 'error' => $error };
2020 return { 'error' => '' };
2023 my $new = new FS::svc_forward { 'srcsvc' => $p->{'svcnum'},
2024 'dst' => $p->{'dst'},
2029 $new->svcnum($old->svcnum);
2030 my $cust_svc = $old->cust_svc;
2031 $new->svcpart($old->svcpart);
2032 $new->pkgnuym($old->pkgnum);
2033 $error = $new->replace($old);
2035 my $conf = new FS::Conf;
2036 $new->svcpart($conf->config('selfservice-svc_forward_svcpart'));
2038 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
2039 or return { 'error' => 'No service' }; #how would we even get here?
2041 $new->pkgnum( $svc_acct->cust_svc->pkgnum );
2043 $error = $new->insert;
2046 return { 'error' => $error };
2050 sub list_dsl_devices {
2053 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2054 return { 'error' => $session } if $context eq 'error';
2056 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2057 or return { 'error' => "Service not found" };
2060 'devices' => [ map {
2061 +{ 'mac_addr' => $_->mac_addr };
2062 } $svc_dsl->dsl_device
2068 sub add_dsl_device {
2071 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2072 return { 'error' => $session } if $context eq 'error';
2074 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2075 or return { 'error' => "Service not found" };
2077 return { 'error' => 'No MAC address supplied' }
2078 unless length($p->{'mac_addr'});
2080 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
2081 'mac_addr' => scalar($p->{'mac_addr'}),
2083 my $error = $dsl_device->insert;
2084 return { 'error' => $error };
2088 sub delete_dsl_device {
2091 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2092 return { 'error' => $session } if $context eq 'error';
2094 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
2095 or return { 'error' => "Service not found" };
2097 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
2098 'mac_addr' => scalar($p->{'mac_addr'}),
2101 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
2103 my $error = $dsl_device->delete;
2104 return { 'error' => $error };
2110 _usage_details( \&_port_graph, $p,
2111 'svcdb' => 'svc_port',
2116 my($svc_port, $begin, $end) = @_;
2118 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
2119 push @usage, { 'png' => $pngOrError };
2123 sub _list_svc_usage {
2124 my($svc_acct, $begin, $end) = @_;
2126 foreach my $part_export (
2127 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
2128 qw( sqlradius sqlradius_withdomain )
2130 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
2135 sub list_svc_usage {
2136 _usage_details(\&_list_svc_usage, @_);
2139 sub _list_support_usage {
2140 my($svc_acct, $begin, $end) = @_;
2142 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
2143 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
2145 push @usage, { 'seconds' => $_->seconds,
2146 'support' => $_->support,
2147 '_date' => $_->_date,
2148 'id' => $_->transaction_id,
2149 'creator' => $_->creator,
2150 'subject' => $_->subject,
2151 'status' => $_->status,
2152 'ticketid' => $_->ticketid,
2158 sub list_support_usage {
2159 _usage_details(\&_list_support_usage, @_);
2162 sub _list_cdr_usage {
2163 # XXX CDR type support...
2164 # XXX any way to do a paged search on this?
2165 # we have to return the results all at once...
2166 my($svc_phone, $begin, $end, %opt) = @_;
2167 map [ $_->downstream_csv(%opt, 'keeparray' => 1) ],
2168 $svc_phone->get_cdrs(
2171 'disable_charged_party' => 1,
2176 sub list_cdr_usage {
2178 _usage_details( \&_list_cdr_usage, $p,
2179 'svcdb' => 'svc_phone',
2183 sub _usage_details {
2184 my($callback, $p, %opt) = @_;
2185 my $conf = FS::Conf->new;
2187 if ( $conf->exists('selfservice_hide-usage') ) {
2188 return { 'error' => 'Viewing usage is not allowed.' };
2191 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2192 return { 'error' => $session } if $context eq 'error';
2194 my $search = { 'svcnum' => $p->{'svcnum'} };
2195 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2197 my $svcdb = $opt{'svcdb'} || 'svc_acct';
2199 my $svc_x = qsearchs( $svcdb, $search );
2200 return { 'error' => 'No service selected in list_svc_usage' }
2203 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
2204 my $freq = $cust_pkg->part_pkg->freq;
2207 if ( $svcdb eq 'svc_phone' ) {
2209 if ( $p->{inbound} ) {
2210 $format = $cust_pkg->part_pkg->option('selfservice_inbound_format')
2211 || $conf->config('selfservice-default_inbound_cdr_format')
2212 || 'source_default';
2213 $callback_opt{inbound} = 1;
2215 $format = $cust_pkg->part_pkg->option('selfservice_format')
2216 || $conf->config('selfservice-default_cdr_format')
2220 $callback_opt{format} = $format;
2221 $callback_opt{use_clid} = 1;
2222 $header = [ split(',', FS::cdr::invoice_header($format) ) ];
2225 my $start = $cust_pkg->setup;
2226 #my $end = $cust_pkg->bill; # or time?
2229 unless ( $p->{beginning} ) {
2230 $p->{beginning} = $cust_pkg->last_bill;
2231 $p->{ending} = $end;
2234 die "illegal beginning" if $p->{beginning} !~ /^\d*$/;
2235 die "illegal ending" if $p->{ending} !~ /^\d*$/;
2237 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending},
2241 if ( $conf->exists('selfservice-hide_cdr_price') ) {
2242 # ugly kludge, I know
2243 my ($delete_col) = grep { $header->[$_] eq 'Price' } (0..scalar(@$header));
2244 if (defined $delete_col) {
2245 delete($_->[$delete_col]) foreach ($header, @usage);
2249 #kinda false laziness with FS::cust_main::bill, but perhaps
2250 #we should really change this bit to DateTime and DateTime::Duration
2252 #change this bit to use Date::Manip? CAREFUL with timezones (see
2253 # mailing list archive)
2254 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
2255 (localtime($p->{ending}) )[0,1,2,3,4,5];
2256 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
2257 (localtime($p->{beginning}) )[0,1,2,3,4,5];
2259 if ( $freq =~ /^\d+$/ ) {
2261 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
2263 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
2264 } elsif ( $freq =~ /^(\d+)w$/ ) {
2266 $nmday += $weeks * 7;
2267 $pmday -= $weeks * 7;
2268 } elsif ( $freq =~ /^(\d+)d$/ ) {
2272 } elsif ( $freq =~ /^(\d+)h$/ ) {
2277 return { 'error' => "unparsable frequency: ". $freq };
2280 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
2281 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
2285 'svcnum' => $p->{svcnum},
2286 'beginning' => $p->{beginning},
2287 'ending' => $p->{ending},
2288 'inbound' => $p->{inbound},
2289 'previous' => ($previous > $start) ? $previous : $start,
2290 'next' => ($next < $end) ? $next : $end,
2291 'header' => $header,
2299 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2300 return { 'error' => $session } if $context eq 'error';
2302 my $search = { 'custnum' => $custnum };
2303 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2304 my $cust_main = qsearchs('cust_main', $search )
2305 or return { 'error' => "unknown custnum $custnum" };
2307 my $status = $cust_main->status;
2309 my %order_pkg_options = ();
2310 if ( $p->{locationnum} > 0 ) {
2311 $order_pkg_options{locationnum} = delete($p->{locationnum});
2312 } elsif ( $p->{address1} ) {
2313 $order_pkg_options{'cust_location'} = new FS::cust_location {
2314 map { $_ => $p->{$_} }
2315 qw( address1 address2 city county state zip country )
2319 #false laziness w/ClientAPI/Signup.pm
2321 my $cust_pkg = new FS::cust_pkg ( {
2322 'custnum' => $custnum,
2323 'pkgpart' => $p->{'pkgpart'},
2324 'quantity' => $p->{'quantity'} || 1,
2326 my $error = $cust_pkg->check;
2327 return { 'error' => $error } if $error;
2330 unless ( $p->{'svcpart'} eq 'none' ) {
2334 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
2336 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
2337 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
2338 $svcdb = $part_svc->svcdb;
2340 $svcdb = 'svc_acct';
2342 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
2345 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
2346 'svc_domain' => [ qw( domain ) ],
2347 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
2348 'svc_external' => [ qw( id title ) ],
2349 'svc_pbx' => [ qw( id title ) ],
2352 my $svc_x = "FS::$svcdb"->new( {
2353 'svcpart' => $svcpart,
2354 map { $_ => $p->{$_} } @{$fields{$svcdb}}
2357 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
2360 while ( length($p->{"snarf_machine$snarfnum"}) ) {
2361 my $acct_snarf = new FS::acct_snarf ( {
2362 'machine' => $p->{"snarf_machine$snarfnum"},
2363 'protocol' => $p->{"snarf_protocol$snarfnum"},
2364 'username' => $p->{"snarf_username$snarfnum"},
2365 '_password' => $p->{"snarf_password$snarfnum"},
2368 push @acct_snarf, $acct_snarf;
2370 $svc_x->child_objects( \@acct_snarf );
2373 my $y = $svc_x->setdefault; # arguably should be in new method
2374 return { 'error' => $y } if $y && !ref($y);
2376 $error = $svc_x->check;
2377 return { 'error' => $error } if $error;
2383 $error = $cust_main->order_pkg(
2384 'cust_pkg' => $cust_pkg,
2389 return { 'error' => $error } if $error;
2391 my $conf = new FS::Conf;
2392 if ( $conf->exists('signup_server-realtime') ) {
2394 my $bill_error = _do_bop_realtime( $cust_main, $status );
2397 $cust_pkg->cancel('quiet'=>1);
2400 $cust_pkg->reexport;
2404 $cust_pkg->reexport;
2407 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
2409 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
2416 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2417 return { 'error' => $session } if $context eq 'error';
2419 my $conf = new FS::Conf;
2420 my $immutable = $conf->exists('selfservice_immutable-package');
2421 return { 'error' => "Package modification disabled" } if $immutable;
2423 my $search = { 'custnum' => $custnum };
2424 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2425 my $cust_main = qsearchs('cust_main', $search )
2426 or return { 'error' => "unknown custnum $custnum" };
2428 my $status = $cust_main->status;
2429 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
2430 or return { 'error' => "unknown package $p->{pkgnum}" };
2432 #if someone does need self-service package change of suspended packages,
2433 # figure out how to be more discriminating
2434 return { error=>"Can't change a suspended package", pkgnum=>$cust_pkg->pkgnum}
2435 if $cust_pkg->status eq 'suspended';
2437 my $err_or_cust_pkg = $cust_pkg->change( 'pkgpart' => $p->{'pkgpart'},
2438 'quantity' => $p->{'quantity'} || 1,
2441 return { error=>$err_or_cust_pkg, pkgnum=>$cust_pkg->pkgnum }
2442 unless ref($err_or_cust_pkg);
2444 if ( $conf->exists('signup_server-realtime') ) {
2446 my $bill_error = _do_bop_realtime( $cust_main, $status, 'no_credit'=>1 );
2449 $err_or_cust_pkg->suspend;
2452 $err_or_cust_pkg->reexport;
2456 $err_or_cust_pkg->reexport;
2459 return { error => '', pkgnum => $cust_pkg->pkgnum };
2463 sub order_recharge {
2466 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2467 return { 'error' => $session } if $context eq 'error';
2469 my $search = { 'custnum' => $custnum };
2470 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2471 my $cust_main = qsearchs('cust_main', $search )
2472 or return { 'error' => "unknown custnum $custnum" };
2474 my $status = $cust_main->status;
2475 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
2476 or return { 'error' => "unknown service " . $p->{'svcnum'} };
2478 my $svc_x = $cust_svc->svc_x;
2479 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
2482 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
2483 qw ( recharge_seconds recharge_upbytes recharge_downbytes
2484 recharge_totalbytes );
2485 my $amount = $part_pkg->option('recharge_amount', 1);
2487 my ($l, $v, $d) = $cust_svc->label; # blah
2488 my $pkg = "Recharge $v";
2490 my $bill_error = $cust_main->charge($amount, $pkg,
2491 "time: $vhash{seconds}, up: $vhash{upbytes}," .
2492 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
2493 $part_pkg->taxclass); #meh
2495 my $conf = new FS::Conf;
2496 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
2498 $bill_error = _do_bop_realtime( $cust_main, $status );
2503 my $error = $svc_x->recharge (\%vhash);
2504 return { 'error' => $error } if $error;
2508 my $error = $bill_error;
2509 $error ||= $svc_x->recharge (\%vhash);
2510 return { 'error' => $error } if $error;
2513 return { error => '', svc => $cust_svc->part_svc->svc };
2517 sub _do_bop_realtime {
2518 my ($cust_main, $status, %opt) = @_;
2520 my $old_balance = $cust_main->balance;
2522 my $bill_error = $cust_main->bill
2523 || $cust_main->apply_payments_and_credits;
2525 $bill_error ||= $cust_main->realtime_collect('selfservice' => 1)
2526 if $cust_main->payby =~ /^(CARD|CHEK)$/;
2528 if ( $cust_main->balance > $old_balance
2529 && $cust_main->balance > 0
2530 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/
2531 || $status eq 'suspended'
2535 unless ( $opt{'no_credit'} ) {
2536 #this makes sense. credit is "un-doing" the invoice
2537 my $conf = new FS::Conf;
2538 $cust_main->credit( sprintf("%.2f", $cust_main->balance-$old_balance ),
2539 'self-service decline',
2540 reason_type=>$conf->config('signup_credit_type'),
2542 $cust_main->apply_credits( 'order' => 'newest' );
2545 return { 'error' => '_decline', 'bill_error' => $bill_error };
2554 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2555 return { 'error' => $session } if $context eq 'error';
2557 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2558 or return { 'error' => "unknown custnum $custnum" };
2560 my @cust_pkg = sort { $a->bill <=> $b->bill }
2561 grep { $_->part_pkg->freq ne '0' }
2562 $cust_main->ncancelled_pkgs;
2564 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
2566 my $total = $cust_main->balance;
2569 my $bill = $_->bill;
2570 $total += $_->part_pkg->base_recur($_, \$bill);
2571 my $renew_date = $_->part_pkg->add_freq($_->bill);
2573 'pkgnum' => $_->pkgnum,
2574 'amount' => sprintf('%.2f', $total),
2575 'bill_date' => $_->bill,
2576 'bill_date_pretty' => time2str('%x', $_->bill),
2577 'renew_date' => $renew_date,
2578 'renew_date_pretty' => time2str('%x', $renew_date),
2579 'expire_date' => $_->expire,
2580 'expire_date_pretty' => time2str('%x', $_->expire),
2585 return { 'dates' => \@array };
2589 sub payment_info_renew_info {
2591 my $renew_info = renew_info($p);
2592 my $payment_info = payment_info($p);
2593 return { %$renew_info,
2601 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2602 return { 'error' => $session } if $context eq 'error';
2604 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2605 or return { 'error' => "unknown custnum $custnum" };
2607 my $date = $p->{'date'};
2611 #freeside-daily -n -d $date fs_daily $custnum
2612 $cust_main->bill_and_collect( 'time' => $date,
2613 'invoice_time' => $now,
2614 'actual_time' => $now,
2615 'check_freq' => '1d',
2618 return { 'error' => '' };
2624 my $session = _cache->get($p->{'session_id'})
2625 or return { 'error' => "Can't resume session" }; #better error message
2627 my $custnum = $session->{'custnum'};
2629 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2630 or return { 'error' => "unknown custnum $custnum" };
2632 my $conf = new FS::Conf;
2634 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2635 or return { 'error' => 'Permission denied' };
2637 my $pkgnum = $p->{'pkgnum'};
2639 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2640 'pkgnum' => $pkgnum, } )
2641 or return { 'error' => "unknown pkgnum $pkgnum" };
2643 my $error = $cust_pkg->suspend(reason => $reasonnum);
2644 return { 'error' => $error };
2650 my $session = _cache->get($p->{'session_id'})
2651 or return { 'error' => "Can't resume session" }; #better error message
2653 my $custnum = $session->{'custnum'};
2655 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2656 or return { 'error' => "unknown custnum $custnum" };
2658 my $pkgnum = $p->{'pkgnum'};
2660 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2661 'pkgnum' => $pkgnum, } )
2662 or return { 'error' => "unknown pkgnum $pkgnum" };
2664 my $error = $cust_pkg->cancel('quiet' => 1);
2665 return { 'error' => $error };
2669 sub provision_phone {
2672 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2674 #editing an existing phone number
2675 if ( $p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ ) {
2676 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2677 return { 'error' => $session } if $context eq 'error';
2679 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2680 return { 'error' => 'service not found' } unless $svc_phone;
2681 return { 'error' => 'invalid svcnum' }
2682 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2684 $svc_phone->email($p->{'email'})
2685 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2686 $svc_phone->forwarddst($p->{'forwarddst'})
2687 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2688 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2689 return { 'error' => $svc_phone->replace };
2693 unless ( $p->{'lnp'} ) {
2694 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2695 $p->{'lnp_status'} = "portingin";
2696 return _provision( 'FS::svc_phone',
2697 [qw(lnp_desired_due_date lnp_other_provider
2698 lnp_other_provider_account phonenum countrycode lnp_status)],
2699 [qw(phonenum countrycode)],
2705 # single DID order (the usual case)
2706 unless (scalar(@bulkdid)) {
2707 return _provision( 'FS::svc_phone',
2708 [qw(phonenum countrycode)],
2709 [qw(phonenum countrycode)],
2715 # bulk DID order case
2717 foreach my $did ( @bulkdid ) {
2718 $did =~ s/[^0-9]//g;
2719 $error = _provision( 'FS::svc_phone',
2720 [qw(phonenum countrycode)],
2721 [qw(phonenum countrycode)],
2723 'pkgnum' => $p->{'pkgnum'},
2724 'svcpart' => $p->{'svcpart'},
2726 'countrycode' => $p->{'countrycode'},
2727 'session_id' => $p->{'session_id'},
2730 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2732 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2735 sub provision_acct {
2737 warn "provision_acct called\n"
2740 return { 'error' => gettext('passwords_dont_match') }
2741 if $p->{'_password'} ne $p->{'_password2'};
2742 return { 'error' => gettext('empty_password') }
2743 unless length($p->{'_password'});
2745 if ($p->{'domsvc'}) {
2746 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2747 qw ( svcpart pkgnum ) );
2748 return { 'error' => gettext('invalid_domain') }
2749 unless ($domains{$p->{'domsvc'}});
2752 warn "provision_acct calling _provision\n"
2754 _provision( 'FS::svc_acct',
2755 [qw(username _password domsvc)],
2756 [qw(username _password domsvc)],
2762 sub provision_external {
2764 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2765 _provision( 'FS::svc_external',
2774 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2775 warn "_provision called for $class\n"
2778 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2779 return { 'error' => $session } if $context eq 'error';
2781 my $search = { 'custnum' => $custnum };
2782 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2783 my $cust_main = qsearchs('cust_main', $search )
2784 or return { 'error' => "unknown custnum $custnum" };
2786 my $pkgnum = $p->{'pkgnum'};
2788 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2790 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2791 'pkgnum' => $pkgnum,
2793 or return { 'error' => "unknown pkgnum $pkgnum" };
2795 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2797 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2798 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2800 warn "creating $class record\n"
2802 my $svc_x = $class->new( {
2803 'pkgnum' => $p->{'pkgnum'},
2804 'svcpart' => $p->{'svcpart'},
2805 map { $_ => $p->{$_} } @$fields
2808 my %insert_args = ();
2809 #i shouldn't be a special case here (pass an option or something)
2810 if ( $class eq 'FS::svc_phone'
2811 && grep length($p->{$_}), @location_editable_fields
2814 $insert_args{'cust_location'} = new FS::cust_location {
2815 map { $_ => $p->{$_} } @location_editable_fields
2819 warn "inserting $class record\n"
2821 my $error = $svc_x->insert(%insert_args);
2824 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2826 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2829 my $return = { 'svc' => $part_svc->svc,
2831 map { $_ => $svc_x->get($_) } @$return_fields
2833 warn "_provision returning ". Dumper($return). "\n"
2842 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2843 return { 'error' => $session } if $context eq 'error';
2845 my $search = { 'custnum' => $custnum };
2846 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2847 my $cust_main = qsearchs('cust_main', $search )
2848 or return { 'error' => "unknown custnum $custnum" };
2850 my $pkgnum = $p->{'pkgnum'};
2852 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2853 'pkgnum' => $pkgnum,
2855 or return { 'error' => "unknown pkgnum $pkgnum" };
2857 my $svcpart = $p->{'svcpart'};
2859 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2860 'svcpart' => $svcpart, } )
2861 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2862 my $part_svc = $pkg_svc->part_svc;
2864 my $conf = new FS::Conf;
2867 'svc' => $part_svc->svc,
2868 'svcdb' => $part_svc->svcdb,
2869 'pkgnum' => $pkgnum,
2870 'svcpart' => $svcpart,
2871 'custnum' => $custnum,
2873 'security_phrase' => 0, #XXX !
2874 'svc_acct_pop' => [], #XXX !
2876 'init_popstate' => '',
2881 small_custview( $cust_main, $conf->config('countrydefault') ),
2885 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2886 && $ret->{'svcdb'} eq 'svc_phone') {
2887 $ret->{'svcnum'} = $p->{'svcnum'};
2888 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2889 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2890 $ret->{'email'} = $svc_phone->email;
2891 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2898 sub unprovision_svc {
2901 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2902 return { 'error' => $session } if $context eq 'error';
2904 my $search = { 'custnum' => $custnum };
2905 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2906 my $cust_main = qsearchs('cust_main', $search )
2907 or return { 'error' => "unknown custnum $custnum" };
2909 my $svcnum = $p->{'svcnum'};
2911 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2912 or return { 'error' => "unknown svcnum $svcnum" };
2914 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2915 unless $cust_svc->cust_pkg->custnum == $custnum;
2917 my $conf = new FS::Conf;
2919 return { 'svc' => $cust_svc->part_svc->svc,
2920 'error' => $cust_svc->cancel,
2922 small_custview( $cust_main, $conf->config('countrydefault') ),
2927 sub myaccount_passwd {
2929 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2930 return { 'error' => $session } if $context eq 'error';
2932 return { 'error' => "New passwords don't match." }
2933 if $p->{'new_password'} ne $p->{'new_password2'};
2935 return { 'error' => 'Enter new password' }
2936 unless length($p->{'new_password'});
2938 #my $search = { 'custnum' => $custnum };
2939 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2940 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2941 my $search = " AND custnum = $1";
2942 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2944 my $svc_acct = qsearchs( {
2945 'table' => 'svc_acct',
2946 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2947 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2948 'LEFT JOIN cust_main USING ( custnum ) ',
2949 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2950 'extra_sql' => $search, #important
2952 or return { 'error' => "Service not found" };
2956 my $conf = new FS::Conf;
2958 return { 'error' => 'Incorrect current password.' }
2959 if ( exists($p->{'old_password'})
2960 || $conf->exists('selfservice-password_change_oldpass')
2962 && ! $svc_acct->check_password($p->{'old_password'});
2964 $error = 'Password too short.'
2965 if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
2966 $error = 'Password too long.'
2967 if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
2969 $svc_acct->set_password($p->{'new_password'});
2970 $error ||= $svc_acct->replace();
2972 #regular pw change in self-service should change contact pw too, otherwise its
2973 #way too confusing. hell its confusing they're separate at all, but alas.
2974 #need to support the "ISP provides email that's used as a contact email" case
2976 my $contact = FS::contact->by_selfservice_email($svc_acct->email);
2977 if ( $contact && qsearchs('cust_contact', { contactnum=> $contact->contactnum,
2978 custnum => $custnum,
2979 selfservice_access => 'Y',
2983 #svc_acct was successful but this one returns an error? "shouldn't happen"
2984 $error ||= $contact->change_password($p->{'new_password'});
2987 my($label, $value) = $svc_acct->cust_svc->label;
2989 return { 'error' => $error,
2996 # sub contact_passwd {
2998 # my($context, $session, $custnum) = _custoragent_session_custnum($p);
2999 # return { 'error' => $session } if $context eq 'error';
3001 # return { 'error' => 'Not logged in as a contact.' }
3002 # unless $session->{'contactnum'};
3004 # return { 'error' => "New passwords don't match." }
3005 # if $p->{'new_password'} ne $p->{'new_password2'};
3007 # return { 'error' => 'Enter new password' }
3008 # unless length($p->{'new_password'});
3010 # #my $search = { 'custnum' => $custnum };
3011 # #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3012 # $custnum =~ /^(\d+)$/ or die "illegal custnum";
3013 # my $search = " AND selfservice_access IS NOT NULL ".
3014 # " AND selfservice_access = 'Y' ".
3015 # " AND ( disabled IS NULL OR disabled = '' )".
3016 # " AND custnum IS NOT NULL AND custnum = $1";
3017 # $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
3019 # my $contact = qsearchs( {
3020 # 'table' => 'contact',
3021 # 'addl_from' => 'LEFT JOIN cust_main USING ( custnum ) ',
3022 # 'hashref' => { 'contactnum' => $session->{'contactnum'}, },
3023 # 'extra_sql' => $search, #important
3025 # or return { 'error' => "Email not found" }; #? how did we get logged in?
3026 # # deleted since then?
3030 # # use these svc_acct length restrictions??
3031 # my $conf = new FS::Conf;
3032 # $error = 'Password too short.'
3033 # if length($p->{'new_password'}) < ($conf->config('passwordmin') || 6);
3034 # $error = 'Password too long.'
3035 # if length($p->{'new_password'}) > ($conf->config('passwordmax') || 8);
3037 # $error ||= $contact->change_password($p->{'new_password'});
3039 # return { 'error' => $error, };
3046 my $info = skin_info($p);
3048 my $conf = new FS::Conf;
3049 my $verification = $conf->config('selfservice-password_reset_verification')
3050 or return { %$info, 'error' => 'Password resets disabled' };
3055 if ( $p->{'email'} ) { #new-style, changes contact and svc_acct
3057 $contact = FS::contact->by_selfservice_email($p->{'email'});
3060 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3061 $cust_main = $cust_contact[0]->cust_main if scalar(@cust_contact) == 1;
3064 #also look for an svc_acct, otherwise it would be super confusing
3066 my($username, $domain) = split('@', $p->{'email'});
3067 my $svc_domain = qsearchs('svc_domain', { 'domain' => $domain } );
3068 if ( $svc_domain ) {
3069 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3070 'domsvc' => $svc_domain->svcnum }
3073 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3074 $cust_main ||= $cust_pkg->cust_main if $cust_pkg;
3076 #precaution: don't change svc_acct password not part of the same
3077 # customer as contact
3078 $svc_acct = '' if ! $cust_pkg
3079 || $cust_pkg->custnum != $cust_main->custnum;
3084 return { %$info, 'error' => 'Email address not found' }
3085 unless $contact || $svc_acct;
3087 } elsif ( $p->{'username'} ) { #old style, looks in svc_acct only
3089 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
3090 or return { %$info, 'error' => 'Account not found' };
3092 $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
3093 'domsvc' => $svc_domain->svcnum }
3095 or return { %$info, 'error' => 'Account not found' };
3097 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
3098 or return { %$info, 'error' => 'Account not found' };
3100 $cust_main = $cust_pkg->cust_main;
3104 return { %$info, 'error' => 'Multi-customer contacts incompatible with customer-based verification' }
3105 if ! $cust_main && $verification ne 'email';
3108 'email' => sub { 1; },
3110 my( $p, $cust_main ) = @_;
3111 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
3112 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
3115 my( $p, $cust_main ) = @_;
3116 my $cust_pay = qsearchs({
3117 'table' => 'cust_pay',
3118 'hashref' => { 'custnum' => $cust_main->custnum },
3119 'order_by' => 'ORDER BY _date DESC LIMIT 1',
3123 $p->{'amount'} == $cust_pay->paid;
3126 my( $p, $cust_main ) = @_;
3127 $p->{'zip'} eq $cust_main->zip
3128 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
3132 foreach my $verify ( split(',', $verification) ) {
3134 &{ $verify{$verify} }( $p, $cust_main )
3135 or return { %$info, 'error' => 'Account not found' };
3139 #okay, we're verified
3143 my $error = $contact->send_reset_email(
3144 'svcnum' => ($svc_acct ? $svc_acct->svcnum : ''),
3148 return { %$info, 'error' => $error }; #????
3151 } elsif ( $svc_acct ) {
3153 #create a unique session
3155 my $reset_session = {
3156 'svcnum' => $svc_acct->svcnum,
3160 my $timeout = '1 hour'; #?
3162 my $reset_session_id;
3164 $reset_session_id = sha512_hex(time(). {}. rand(). $$)
3165 } until ( ! defined _cache->get("reset_passwd_$reset_session_id") );
3168 _cache->set( "reset_passwd_$reset_session_id", $reset_session, $timeout );
3172 my $msgnum = $conf->config('selfservice-password_reset_msgnum',
3173 $cust_main->agentnum);
3174 #die "selfservice-password_reset_msgnum unset" unless $msgnum;
3175 return { %$info, 'error' => "selfservice-password_reset_msgnum unset" }
3177 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum } );
3178 my $error = $msg_template->send( 'cust_main' => $cust_main,
3179 'object' => $svc_acct,
3180 'substitutions' => {
3181 'session_id' => $reset_session_id,
3185 return { %$info, 'error' => $error }; #????
3190 return { %$info, 'error' => '' };
3193 sub check_reset_passwd {
3196 my $conf = new FS::Conf;
3197 my $verification = $conf->config('selfservice-password_reset_verification')
3198 or return { 'error' => 'Password resets disabled' };
3200 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3201 or return { 'error' => "Can't resume session" }; #better error message
3203 if ( $reset_session->{'svcnum'} ) {
3205 my $svcnum = $reset_session->{'svcnum'};
3207 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3208 or return { 'error' => "Service not found" };
3210 $p->{'agentnum'} = $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3211 my $info = skin_info($p);
3215 'session_id' => $p->{'session_id'},
3216 'username' => $svc_acct->username,
3219 } elsif ( $reset_session->{'contactnum'} ) {
3221 my $contactnum = $reset_session->{'contactnum'};
3223 my $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3224 or return { 'error' => "Contact not found" };
3226 my @contact_email = $contact->contact_email;
3227 return { 'error' => 'No contact email' } unless @contact_email;
3229 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3230 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3231 if scalar(@cust_contact) == 1;
3232 my $info = skin_info($p);
3236 'session_id' => $p->{'session_id'},
3237 'email' => $contact_email[0]->email, #the first?
3242 return { 'error' => 'No svcnum or contactnum in session' }; #??
3248 sub process_reset_passwd {
3251 my $conf = new FS::Conf;
3252 my $verification = $conf->config('selfservice-password_reset_verification')
3253 or return { 'error' => 'Password resets disabled' };
3255 my $reset_session = _cache->get('reset_passwd_'. $p->{'session_id'})
3256 or return { 'error' => "Can't resume session" }; #better error message
3261 if ( $reset_session->{'svcnum'} ) {
3263 my $svcnum = $reset_session->{'svcnum'};
3265 $svc_acct = qsearchs('svc_acct', { 'svcnum' => $svcnum } )
3266 or return { 'error' => "Service not found" };
3268 $p->{'agentnum'} ||= $svc_acct->cust_svc->cust_pkg->cust_main->agentnum;
3269 $info ||= skin_info($p);
3274 if ( $reset_session->{'contactnum'} ) {
3276 my $contactnum = $reset_session->{'contactnum'};
3278 $contact = qsearchs('contact', { 'contactnum' => $contactnum } )
3279 or return { 'error' => "Contact not found" };
3281 my @cust_contact = grep $_->selfservice_access, $contact->cust_contact;
3282 $p->{'agentnum'} = $cust_contact[0]->cust_main->agentnum
3283 if scalar(@cust_contact) == 1;
3284 $info ||= skin_info($p);
3288 return { %$info, 'error' => "New passwords don't match." }
3289 if $p->{'new_password'} ne $p->{'new_password2'};
3291 return { %$info, 'error' => 'Enter new password' }
3292 unless length($p->{'new_password'});
3296 $svc_acct->set_password($p->{'new_password'});
3297 my $error = $svc_acct->replace();
3299 return { %$info, 'error' => $error } if $error;
3301 #my($label, $value) = $svc_acct->cust_svc->label;
3302 #return { 'error' => $error,
3303 # #'label' => $label,
3304 # #'value' => $value,
3311 my $error = $contact->change_password($p->{'new_password'});
3313 return { %$info, 'error' => $error }; # if $error;
3317 #password changed ,so remove session, don't want it reused
3318 _cache->remove($p->{'session_id'});
3320 return { %$info, 'error' => '' };
3326 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3327 return { 'error' => $session } if $context eq 'error';
3330 if ( $session->{'pkgnum'} ) {
3332 #tickets for specific service with pkg-balances on
3333 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
3334 'pkgnum' => $session->{'pkgnum'} })
3335 or return { 'error' => 'unknown package' };
3336 foreach my $cust_svc ( $cust_pkg->cust_svc ) {
3337 push @tickets, $cust_svc->tickets( $p->{status} );
3342 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
3343 or return { 'error' => "unknown custnum $custnum" };
3345 @tickets = $cust_main->tickets( $p->{status} );
3348 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
3349 if ( $FS::TicketSystem::system && FS::TicketSystem->selfservice_priority ) {
3350 my $conf = new FS::Conf;
3351 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
3355 ($a->{'_selfservice_priority'} eq '') <=>
3356 ($b->{'_selfservice_priority'} eq '')
3359 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
3365 +{ tickets => \@tickets };
3372 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3373 return { 'error' => $session } if $context eq 'error';
3375 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
3376 FS::TicketSystem->init();
3378 my $conf = new FS::Conf;
3379 my $queue = $p->{'queue'}
3380 || $conf->config('ticket_system-selfservice_queueid')
3381 || $conf->config('ticket_system-default_queueid');
3383 warn "$me create_ticket: creating ticket\n" if $DEBUG;
3384 my $err_or_ticket = FS::TicketSystem->create_ticket(
3385 '', #create RT session based on FS CurrentUser (fs_selfservice)
3387 'custnum' => $custnum,
3388 'svcnum' => $session->{'svcnum'},
3389 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
3392 if ( ref($err_or_ticket) ) {
3393 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
3395 return { 'error' => '',
3396 'ticket_id' => $err_or_ticket->id,
3399 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
3401 return { 'error' => $err_or_ticket };
3409 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3410 return { 'error' => $session } if $context eq 'error';
3412 return { error => 'requested format not implemented' }
3413 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
3415 my $conf = new FS::Conf;
3416 my $age_threshold = 0;
3417 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
3418 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
3420 my $search = { 'custnum' => $custnum };
3421 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
3422 my $cust_main = qsearchs('cust_main', $search )
3423 or return { 'error' => "unknown custnum $custnum" };
3425 # does it make more sense to just run one sql query for this instead of all the
3426 # insanity below? would increase performance greately for large data sets?
3428 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
3429 my @part_svc = $cust_pkg->part_svc;
3430 foreach my $part_svc ( @part_svc ) {
3431 if($part_svc->svcdb eq 'svc_phone'){
3432 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
3433 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
3434 push @svc_phone, $cust_pkg_svc->svc_x
3435 if $cust_pkg_svc->date_inserted >= $age_threshold;
3443 my($xls_r,$xls_c) = (0,0);
3446 my @fields = qw( countrycode phonenum pin sip_password phone_name );
3447 if($p->{'format'} eq 'csv') {
3448 $csv = new Text::CSV_XS { 'always_quote' => 1,
3451 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
3452 $content .= $csv->string;
3454 elsif($p->{'format'} eq 'xls') {
3455 my $XLS1 = new IO::Scalar \$content;
3456 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
3457 or return { 'error' => "Error opening .xls file: $!" };
3458 $xls = $xls_workbook->add_worksheet('DIDs');
3459 foreach ( @fields ) {
3460 $xls->write(0,$xls_c++,$_);
3465 foreach my $svc_phone ( @svc_phone ) {
3466 my @cols = map { $svc_phone->$_ } @fields;
3467 if($p->{'format'} eq 'csv') {
3468 return { 'error' => 'Unable to create CSV' }
3469 unless $csv->combine(@cols);
3470 $content .= $csv->string;
3472 elsif($p->{'format'} eq 'xls') {
3475 $xls->write($xls_r,$xls_c++,$_);
3481 $xls_workbook->close() if $p->{'format'} eq 'xls';
3483 { content => $content, format => $p->{'format'}, };
3488 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3489 return { 'error' => $session } if $context eq 'error';
3491 # warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
3492 # FS::TicketSystem->init();
3493 # return { 'error' => 'get_ticket configuration error' }
3494 # if $FS::TicketSystem::system ne 'RT_Internal';
3496 # check existence and ownership as part of this
3497 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
3498 my $rt_session = FS::TicketSystem->session('');
3499 my $Ticket = FS::TicketSystem->get_ticket_object(
3501 ticket_id => $p->{'ticket_id'},
3504 return { 'error' => 'ticket not found' } if !$Ticket;
3506 if ( length( $p->{'subject'} || '' ) ) {
3508 if ( $p->{'subject'} ne $Ticket->Subject ) {
3509 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
3510 return { 'error' => "unable to set subject: $msg" } if !$val;
3514 if(length($p->{'reply'})) {
3515 my @err_or_res = FS::TicketSystem->correspond_ticket(
3517 'ticket_id' => $p->{'ticket_id'},
3518 'content' => $p->{'reply'},
3521 return { 'error' => 'unable to reply to ticket' }
3522 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
3525 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
3526 my $err_or_ticket = FS::TicketSystem->get_ticket(
3528 'ticket_id' => $p->{'ticket_id'},
3531 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
3532 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
3534 return { 'error' => $err_or_ticket };
3537 my @custs = @{$err_or_ticket->{'custs'}};
3538 my @txns = @{$err_or_ticket->{'txns'}};
3541 # superseded by check in get_ticket_object
3542 #return { 'error' => 'invalid ticket requested' }
3543 #unless grep($_ eq $custnum, @custs);
3545 foreach my $txn ( @txns ) {
3546 push @filtered_txns, $txn
3547 if ($txn->{'type'} eq 'EmailRecord'
3548 || $txn->{'type'} eq 'Correspond'
3549 || $txn->{'type'} eq 'Create');
3552 warn "$me get_ticket: successful: \n"
3554 return { 'error' => '',
3555 'transactions' => \@filtered_txns,
3556 'ticket_fields' => $err_or_ticket->{'fields'},
3557 'ticket_id' => $p->{'ticket_id'},
3561 sub adjust_ticket_priority {
3563 my($context, $session, $custnum) = _custoragent_session_custnum($p);
3564 return { 'error' => $session } if $context eq 'error';
3566 # warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
3567 # FS::TicketSystem->init;
3568 my $ss_priority = FS::TicketSystem->selfservice_priority;
3570 return { 'error' => 'adjust_ticket_priority configuration error' }
3571 if $FS::TicketSystem::system ne 'RT_Internal'
3574 my $values = $p->{'values'}; #hashref, id => priority value
3577 foreach my $id (keys %$values) {
3578 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
3579 my $Ticket = FS::TicketSystem->get_ticket_object('',
3581 'custnum' => $custnum,
3584 $ticket_error{$id} = 'ticket not found';
3588 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
3589 # We're not going to implement it for RT_External.
3590 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
3591 my $new_value = $values->{$id};
3592 next if $old_value eq $new_value;
3594 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
3596 # AddCustomFieldValue works fine (replacing any existing value) if it's
3597 # a single-valued custom field, which it should be. If it's not, you're
3598 # doing something wrong.
3600 if ( length($new_value) ) {
3601 ($val, $msg) = $Ticket->AddCustomFieldValue(
3602 Field => $ss_priority,
3603 Value => $new_value,
3607 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
3608 Field => $ss_priority,
3609 Value => $old_value,
3613 $ticket_error{$id} = $msg if !$val;
3614 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
3616 return { 'error' => '',
3617 'ticket_error' => \%ticket_error,
3618 %{ customer_info($p) } # send updated customer info back
3624 sub _custoragent_session_custnum {
3627 my($context, $session, $custnum);
3628 if ( $p->{'session_id'} ) {
3630 $context = 'customer';
3631 $session = _cache->get($p->{'session_id'})
3632 or return ( 'error' => "Can't resume session" ); #better error message
3633 $custnum = $session->{'custnum'};
3635 } elsif ( $p->{'agent_session_id'} ) {
3638 my $agent_cache = new FS::ClientAPI_SessionCache( {
3639 'namespace' => 'FS::ClientAPI::Agent',
3641 $session = $agent_cache->get($p->{'agent_session_id'})
3642 or return ( 'error' => "Can't resume session" ); #better error message
3643 $custnum = $p->{'custnum'};
3647 return ( 'error' => "Can't resume session" ); #better error message
3650 ($context, $session, $custnum);