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 );
8 use Digest::MD5 qw(md5_hex);
10 use Business::CreditCard;
12 use Time::Local qw(timelocal_nocheck);
13 use FS::UI::Web::small_custview qw(small_custview); #less doh
15 use FS::UI::bytecount qw( display_bytecount );
18 use FS::Record qw(qsearch qsearchs dbh);
19 use FS::Msgcat qw(gettext);
20 use FS::Misc qw(card_types);
21 use FS::Misc::DateTime qw(parse_datetime);
22 use FS::ClientAPI_SessionCache;
33 use FS::legacy_cust_bill;
34 use FS::cust_main_county;
37 use FS::acct_rt_transaction;
42 use Spreadsheet::WriteExcel;
45 $me = '[FS::ClientAPI::MyAccount]';
47 use vars qw( @cust_main_editable_fields );
48 @cust_main_editable_fields = qw(
49 first last company address1 address2 city
50 county state zip country
51 daytime night fax mobile
52 ship_first ship_last ship_company ship_address1 ship_address2 ship_city
53 ship_state ship_zip ship_country
54 ship_daytime ship_night ship_fax ship_mobile
56 payby payinfo payname paystart_month paystart_year payissue payip
57 ss paytype paystate stateid stateid_state
60 BEGIN { #preload to reduce time customer_info takes
61 if ( $FS::TicketSystem::system ) {
62 warn "$me: initializing ticket system\n" if $DEBUG;
63 FS::TicketSystem->init();
68 $cache ||= new FS::ClientAPI_SessionCache( {
69 'namespace' => 'FS::ClientAPI::MyAccount',
76 my($context, $session, $custnum) = _custoragent_session_custnum($p);
77 #return { 'error' => $session } if $context eq 'error';
80 if ( $context eq 'customer' ) {
82 my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
85 $sth->execute($custnum) or die $sth->errstr;
87 $agentnum = $sth->fetchrow_arrayref->[0]
88 or die "no agentnum for custnum $custnum";
90 #} elsif ( $context eq 'agent' ) {
91 } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
95 my $conf = new FS::Conf;
97 #false laziness w/Signup.pm
99 my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
101 if ( $skin_info_cache_agent ) {
103 warn "$me loading cached skin info for agentnum $agentnum\n"
108 warn "$me populating skin info cache for agentnum $agentnum\n"
111 $skin_info_cache_agent = {
112 'agentnum' => $agentnum,
113 ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
114 qw( company_name date_format ) ),
115 ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
116 qw( body_bgcolor box_bgcolor
117 text_color link_color vlink_color hlink_color alink_color
118 font title_color title_align title_size menu_bgcolor menu_fontsize
121 ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
122 qw( menu_skipblanks menu_skipheadings menu_nounderline )
124 ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
125 qw( title_left_image title_right_image
126 menu_top_image menu_body_image menu_bottom_image
129 'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
130 ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
131 qw( head body_header body_footer company_address ) ),
134 _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
138 #{ %$skin_info_cache_agent };
139 $skin_info_cache_agent;
146 my $conf = new FS::Conf;
150 'phone_login' => $conf->exists('selfservice_server-phone_login'),
151 'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
158 #false laziness w/FS::ClientAPI::passwd::passwd
162 my $conf = new FS::Conf;
165 if ( $p->{'domain'} eq 'svc_phone'
166 && $conf->exists('selfservice_server-phone_login') ) {
168 my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
169 return { error => 'Number not found.' } unless $svc_phone;
172 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
173 #return { error => 'Only primary user may log in.' }
174 # if $conf->exists('selfservice_server-primary_only')
175 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
177 return { error => 'Incorrect PIN.' }
178 unless $svc_phone->check_pin($p->{'password'});
184 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
185 or return { error => 'Domain '. $p->{'domain'}. ' not found' };
187 my $svc_acct = qsearchs( 'svc_acct', { 'username' => $p->{'username'},
188 'domsvc' => $svc_domain->svcnum, }
190 return { error => 'User not found.' } unless $svc_acct;
192 if($conf->exists('selfservice_server-login_svcpart')) {
193 my @svcpart = $conf->config('selfservice_server-login_svcpart');
194 my $svcpart = $svc_acct->cust_svc->svcpart;
195 return { error => 'Invalid user.' }
196 unless grep($_ eq $svcpart, @svcpart);
199 return { error => 'Incorrect password.' }
200 unless $svc_acct->check_password($p->{'password'});
207 'svcnum' => $svc_x->svcnum,
210 my $cust_svc = $svc_x->cust_svc;
211 my $cust_pkg = $cust_svc->cust_pkg;
213 my $cust_main = $cust_pkg->cust_main;
214 $session->{'custnum'} = $cust_main->custnum;
215 if ( $conf->exists('pkg-balances') ) {
216 my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
217 $cust_main->ncancelled_pkgs;
218 $session->{'pkgnum'} = $cust_pkg->pkgnum
219 if scalar(@cust_pkg) > 1;
223 #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
224 #return { error => 'Only primary user may log in.' }
225 # if $conf->exists('selfservice_server-primary_only')
226 # && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
227 my $part_pkg = $cust_pkg->part_pkg;
228 return { error => 'Only primary user may log in.' }
229 if $conf->exists('selfservice_server-primary_only')
230 && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
234 $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
235 } until ( ! defined _cache->get($session_id) ); #just in case
237 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
238 _cache->set( $session_id, $session, $timeout );
240 return { 'error' => '',
241 'session_id' => $session_id,
247 if ( $p->{'session_id'} ) {
248 _cache->remove($p->{'session_id'});
249 return { %{ skin_info($p) }, 'error' => '' };
251 return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
258 my($context, $session, $custnum) = _custoragent_session_custnum($p);
259 return { 'error' => $session } if $context eq 'error';
261 my $svc_acct = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_acct' )
262 or return { 'error' => "Service not found" };
264 $session->{'svcnum'} = $svc_acct->svcnum;
266 my $conf = new FS::Conf;
267 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
268 _cache->set( $p->{'session_id'}, $session, $timeout );
270 return { 'error' => '' };
274 sub payment_gateway {
276 # takes a cust_main and a cust_payby entry, returns the payment_gateway
277 my $conf = new FS::Conf;
278 my $cust_main = shift;
279 my $cust_payby = shift;
280 my $gatewaynum = $conf->config('selfservice-payment_gateway');
282 my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
283 die "configured gatewaynum $gatewaynum not found!" if !$pg;
287 return '' if ! FS::payby->realtime($cust_payby);
288 my $pg = $cust_main->agent->payment_gateway(
289 'method' => FS::payby->payby2bop($cust_payby),
299 my $conf = new FS::Conf;
301 my $info = skin_info($p);
303 use vars qw( $cust_paybys ); #cache for performance
304 unless ( $cust_paybys ) {
306 my %cust_paybys = map { $_ => 1 }
307 map { FS::payby->payby2payment($_) }
308 $conf->config('signup_server-payby');
310 $cust_paybys = [ keys %cust_paybys ];
313 $info->{'cust_paybys'} = $cust_paybys;
315 my($context, $session, $custnum) = _custoragent_session_custnum($p);
316 return { 'error' => $session } if $context eq 'error';
318 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
319 or return { 'error' => "unknown custnum $custnum" };
321 $info->{'hide_payment_fields'} = [
323 my $pg = payment_gateway($cust_main, $_);
324 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
325 } @{ $info->{cust_paybys} }
328 $info->{'self_suspend_reason'} =
329 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
331 $info->{'edit_ticket_subject'} =
332 $conf->exists('ticket_system-selfservice_edit_subject') &&
333 $cust_main->edit_subject;
336 'custnum' => $custnum,
337 'access_pkgnum' => $session->{'pkgnum'},
338 'access_svcnum' => $session->{'svcnum'},
345 my($context, $session, $custnum) = _custoragent_session_custnum($p);
346 return { 'error' => $session } if $context eq 'error';
350 my $conf = new FS::Conf;
351 if ($conf->exists('cust_main-require_address2')) {
352 $return{'require_address2'} = '1';
354 $return{'require_address2'} = '';
357 if ( $FS::TicketSystem::system ) {
358 warn "$me customer_info: initializing ticket system\n" if $DEBUG;
359 FS::TicketSystem->init();
362 if ( $custnum ) { #customer record
364 my $search = { 'custnum' => $custnum };
365 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
366 my $cust_main = qsearchs('cust_main', $search )
367 or return { 'error' => "unknown custnum $custnum" };
369 if ( $session->{'pkgnum'} ) {
370 $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
372 $return{balance} = $cust_main->balance;
375 my @tickets = $cust_main->tickets;
376 # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
377 if ( FS::TicketSystem->selfservice_priority ) {
378 my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
382 ($a->{'_selfservice_priority'} eq '') <=>
383 ($b->{'_selfservice_priority'} eq '')
386 ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'})
392 $return{tickets} = \@tickets;
395 unless ( $session->{'pkgnum'} ) {
398 invnum => $_->invnum,
399 date => time2str("%b %o, %Y", $_->_date),
402 } $cust_main->open_cust_bill;
403 $return{open_invoices} = \@open;
406 $return{small_custview} =
407 small_custview( $cust_main,
408 scalar($conf->config('countrydefault')),
409 ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
412 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
413 $return{ship_name} = $cust_main->ship_first. ' '. $cust_main->get('ship_last');
415 for (@cust_main_editable_fields) {
416 $return{$_} = $cust_main->get($_);
419 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
420 $return{payinfo} = $cust_main->paymask;
421 @return{'month', 'year'} = $cust_main->paydate_monthyear;
424 $return{'invoicing_list'} =
425 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
426 $return{'postal_invoicing'} =
427 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
429 if (scalar($conf->config('support_packages'))) {
430 my @support_services = ();
431 foreach ($cust_main->support_services) {
432 my $seconds = $_->svc_x->seconds;
433 my $time_remaining = (($seconds < 0) ? '-' : '' ).
434 int(abs($seconds)/3600)."h".
435 sprintf("%02d",(abs($seconds)%3600)/60)."m";
436 my $cust_pkg = $_->cust_pkg;
439 $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
440 $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
441 push @support_services, { svcnum => $_->svcnum,
442 time => $time_remaining,
447 $return{support_services} = \@support_services;
450 if ( $conf->config('prepayment_discounts-credit_type') ) {
452 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
455 if ( $session->{'svcnum'} ) {
456 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
457 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
458 $return{'svcnum'} = $session->{'svcnum'};
461 } elsif ( $session->{'svcnum'} ) { #no customer record
463 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
464 or die "unknown svcnum";
465 $return{name} = $svc_acct->email;
469 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
473 return { 'error' => '',
474 'custnum' => $custnum,
480 sub customer_info_short {
483 my($context, $session, $custnum) = _custoragent_session_custnum($p);
484 return { 'error' => $session } if $context eq 'error';
488 my $conf = new FS::Conf;
490 if ( $custnum ) { #customer record
492 my $search = { 'custnum' => $custnum };
493 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
494 my $cust_main = qsearchs('cust_main', $search )
495 or return { 'error' => "unknown custnum $custnum" };
497 $return{small_custview} =
498 small_custview( $cust_main,
499 scalar($conf->config('countrydefault')),
503 $return{name} = $cust_main->first. ' '. $cust_main->get('last');
504 $return{ship_name} = $cust_main->ship_first. ' '. $cust_main->get('ship_last');
506 $return{payby} = $cust_main->payby;
508 #none of these are terribly expensive if we want 'em...
509 for (@cust_main_editable_fields) {
510 $return{$_} = $cust_main->get($_);
513 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
514 $return{payinfo} = $cust_main->paymask;
515 @return{'month', 'year'} = $cust_main->paydate_monthyear;
518 $return{'invoicing_list'} =
519 join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
520 #$return{'postal_invoicing'} =
521 # 0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
523 if ( $session->{'svcnum'} ) {
524 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
525 $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
526 $return{'svcnum'} = $session->{'svcnum'};
529 } elsif ( $session->{'svcnum'} ) { #no customer record
531 #uuh, not supproted yet... die?
532 return { 'error' => 'customer_info_short not yet supported as agent' };
536 return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
540 return { 'error' => '',
541 'custnum' => $custnum,
548 my $session = _cache->get($p->{'session_id'})
549 or return { 'error' => "Can't resume session" }; #better error message
551 my $custnum = $session->{'custnum'}
552 or return { 'error' => "no customer record" };
554 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
555 or return { 'error' => "unknown custnum $custnum" };
557 my $new = new FS::cust_main { $cust_main->hash };
558 $new->set( $_ => $p->{$_} )
559 foreach grep { exists $p->{$_} } @cust_main_editable_fields;
562 if (exists($p->{'payby'})) {
563 $p->{'payby'} =~ /^([A-Z]{4})$/
564 or return { 'error' => "illegal_payby " . $p->{'payby'} };
568 if ( $payby =~ /^(CARD|DCRD)$/ ) {
570 $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
572 if ( $new->payinfo eq $cust_main->paymask ) {
573 $new->payinfo($cust_main->payinfo);
575 $new->payinfo($p->{'payinfo'});
578 $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
580 } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
583 $p->{'payinfo1'} =~ /^([\dx]+)$/
584 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
586 $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by -require-bank-branch?
587 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
589 $payinfo = $payinfo1. '@'. $payinfo2;
591 $new->payinfo( ($payinfo eq $cust_main->paymask)
592 ? $cust_main->payinfo
596 $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
598 } elsif ( $payby =~ /^(BILL)$/ ) {
600 } elsif ( $payby ) { #notyet ready
601 return { 'error' => "unknown payby $payby" };
605 if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
606 #false laziness with httemplate/edit/process/cust_main.cgi
607 @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
608 push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
610 @invoicing_list = $cust_main->invoicing_list;
613 my $error = $new->replace($cust_main, \@invoicing_list);
614 return { 'error' => $error } if $error;
617 return { 'error' => '' };
622 my $session = _cache->get($p->{'session_id'})
623 or return { 'error' => "Can't resume session" }; #better error message
629 my $conf = new FS::Conf;
630 use vars qw($payment_info); #cache for performance
631 unless ( $payment_info ) {
633 my %states = map { $_->state => 1 }
634 qsearch('cust_main_county', {
635 'country' => $conf->config('countrydefault') || 'US'
638 my %cust_paybys = map { $_ => 1 }
639 map { FS::payby->payby2payment($_) }
640 $conf->config('signup_server-payby');
642 my @cust_paybys = keys %cust_paybys;
646 #list all counties/states/countries
647 'cust_main_county' =>
648 [ map { $_->hashref } qsearch('cust_main_county', {}) ],
650 #shortcut for one-country folks
652 [ sort { $a cmp $b } keys %states ],
654 'card_types' => card_types(),
656 'paytypes' => [ @FS::cust_main::paytypes ],
658 'paybys' => [ $conf->config('signup_server-payby') ],
659 'cust_paybys' => \@cust_paybys,
661 'stateid_label' => FS::Msgcat::_gettext('stateid'),
662 'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
664 'show_ss' => $conf->exists('show_ss'),
665 'show_stateid' => $conf->exists('show_stateid'),
666 'show_paystate' => $conf->exists('show_bankstate'),
668 'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
670 'credit_card_surcharge_percentage' => $conf->config('credit-card-surcharge-percentage'),
679 my %return = %$payment_info;
681 my $custnum = $session->{'custnum'};
683 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
684 or return { 'error' => "unknown custnum $custnum" };
686 $return{'hide_payment_fields'} = [
688 my $pg = payment_gateway($cust_main, $_);
689 $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
690 } @{ $return{cust_paybys} }
693 $return{balance} = $cust_main->balance; #XXX pkg-balances?
695 $return{payname} = $cust_main->payname
696 || ( $cust_main->first. ' '. $cust_main->get('last') );
698 $return{$_} = $cust_main->get($_) for qw(address1 address2 city state zip);
700 $return{payby} = $cust_main->payby;
701 $return{stateid_state} = $cust_main->stateid_state;
703 if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
704 $return{card_type} = cardtype($cust_main->payinfo);
705 $return{payinfo} = $cust_main->paymask;
707 @return{'month', 'year'} = $cust_main->paydate_monthyear;
711 if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
712 my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
713 $return{payinfo1} = $payinfo1;
714 $return{payinfo2} = $payinfo2;
715 $return{paytype} = $cust_main->paytype;
716 $return{paystate} = $cust_main->paystate;
720 if ( $conf->config('prepayment_discounts-credit_type') ) {
722 $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
725 #doubleclick protection
727 $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
729 return { 'error' => '',
735 #some false laziness with httemplate/process/payment.cgi - look there for
736 #ACH and CVV support stuff
738 sub validate_payment {
741 my $session = _cache->get($p->{'session_id'})
742 or return { 'error' => "Can't resume session" }; #better error message
744 my $custnum = $session->{'custnum'};
746 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
747 or return { 'error' => "unknown custnum $custnum" };
749 $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
750 or return { 'error' => gettext('illegal_amount') };
752 return { error => 'Amount must be greater than 0' } unless $amount > 0;
754 $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
755 or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
756 my $discount_term = $1;
758 $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
759 or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
762 $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
763 or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
766 $p->{'payby'} ||= 'CARD';
767 $p->{'payby'} =~ /^([A-Z]{4})$/
768 or return { 'error' => "illegal_payby " . $p->{'payby'} };
771 #false laziness w/process/payment.cgi
774 if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
776 $p->{'payinfo1'} =~ /^([\dx]+)$/
777 or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
779 $p->{'payinfo2'} =~ /^([\dx]+)$/
780 or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
782 $payinfo = $payinfo1. '@'. $payinfo2;
784 $payinfo = $cust_main->payinfo
785 if $cust_main->paymask eq $payinfo;
787 } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
789 $payinfo = $p->{'payinfo'};
791 #more intelligent mathing will be needed here if you change
792 #card_masking_method and don't remove existing paymasks
793 $payinfo = $cust_main->payinfo
794 if $cust_main->paymask eq $payinfo;
797 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
798 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
802 or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
803 return { 'error' => gettext('unknown_card_type') }
804 if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
806 if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
807 if ( cardtype($payinfo) eq 'American Express card' ) {
808 $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
809 or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
812 $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
813 or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
819 die "unknown payby $payby";
823 'CARD' => [ qw( paystart_month paystart_year payissue payip
824 address1 address2 city state zip country ) ],
825 'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
829 $card_type = cardtype($payinfo) if $payby eq 'CARD';
832 'cust_main' => $cust_main, #XXX or just custnum??
835 'payinfo' => $payinfo,
836 'paymask' => $cust_main->mask_payinfo( $payby, $payinfo ),
837 'card_type' => $card_type,
838 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01',
839 'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
840 'payname' => $payname,
841 'paybatch' => $paybatch, #this doesn't actually do anything
843 'payname' => $payname,
844 'discount_term' => $discount_term,
845 'pkgnum' => $session->{'pkgnum'},
846 map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
856 my $validate = validate_payment($p);
857 return $validate if $validate->{'error'};
859 my $conf = new FS::Conf;
860 my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
861 _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
863 +{ map { $_=>$validate->{$_} }
864 qw( card_type paymask payname paydate_pretty amount )
869 sub process_stored_payment {
872 my $session_id = $p->{'session_id'};
874 my $payment_info = _cache->get( "payment_$session_id" )
875 or return { 'error' => "Can't resume session" }; #better error message
877 do_process_payment($payment_info);
881 sub process_payment {
884 my $payment_info = validate_payment($p);
885 return $payment_info if $payment_info->{'error'};
887 do_process_payment($payment_info);
891 sub do_process_payment {
892 my $validate = shift;
894 my $cust_main = $validate->{'cust_main'};
896 my $amount = delete $validate->{'amount'};
899 my $payby = delete $validate->{'payby'};
901 my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
904 'paynum_ref' => \$paynum,
907 return { 'error' => $error } if $error;
909 $cust_main->apply_payments;
911 if ( $validate->{'save'} ) {
912 my $new = new FS::cust_main { $cust_main->hash };
913 if ($validate->{'payby'} eq 'CARD' || $validate->{'payby'} eq 'DCRD') {
914 $new->set( $_ => $validate->{$_} )
915 foreach qw( payname paystart_month paystart_year payissue payip
916 address1 address2 city state zip country );
917 $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
918 } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
919 $new->set( $_ => $validate->{$_} )
920 foreach qw( payname payip paytype paystate
921 stateid stateid_state );
922 $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
924 $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
925 $new->set( 'paydate' => $validate->{'paydate'} );
926 my $error = $new->replace($cust_main);
928 #no, this causes customers to process their payments again
929 #return { 'error' => $error };
930 #XXX just warn verosely for now so i can figure out how these happen in
931 # the first place, eventually should redirect them to the "change
932 #address" page but indicate the payment did process??
933 delete($validate->{'payinfo'}); #don't want to log this!
934 warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
935 "NEW: ". Dumper($new)."\n".
936 "OLD: ". Dumper($cust_main)."\n".
937 "PACKET: ". Dumper($validate)."\n";
945 my $receipt_html = '';
947 # currently supported for realtime CC only; send receipt data to SS
948 $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
951 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
954 <TD ALIGN="right">Payment#</TD>
955 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
959 <TD ALIGN="right">Date</TD>
961 <TD BGCOLOR="#FFFFFF"><B>! .
962 time2str("%a %b %o, %Y %r", $cust_pay->_date)
968 <TD ALIGN="right">Amount</TD>
969 <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
974 <TD ALIGN="right">Payment method</TD>
975 <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
986 my($gw, $auth, $order) = split(':', $cust_pay->paybatch);
990 'amount' => sprintf('%.2f', $cust_pay->paid),
991 'date' => $cust_pay->_date,
992 'date_pretty' => time2str('%Y-%m-%d', $cust_pay->_date),
993 'time_pretty' => time2str('%T', $cust_pay->_date),
995 'order_num' => $order,
996 'receipt_html' => $receipt_html,
1003 'receipt_html' => '',
1010 sub realtime_collect {
1013 my $session = _cache->get($p->{'session_id'})
1014 or return { 'error' => "Can't resume session" }; #better error message
1016 my $custnum = $session->{'custnum'};
1018 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1019 or return { 'error' => "unknown custnum $custnum" };
1022 if ( $p->{'amount'} ) {
1023 $amount = $p->{'amount'};
1025 elsif ( $session->{'pkgnum'} ) {
1026 $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1029 $amount = $cust_main->balance;
1032 my $error = $cust_main->realtime_collect(
1033 'method' => $p->{'method'},
1034 'amount' => $amount,
1035 'pkgnum' => $session->{'pkgnum'},
1036 'session_id' => $p->{'session_id'},
1040 return { 'error' => $error } unless ref( $error );
1042 return { 'error' => '', amount => $amount, %$error };
1045 sub process_payment_order_pkg {
1048 my $hr = process_payment($p);
1049 return $hr if $hr->{'error'};
1054 sub process_payment_order_renew {
1057 my $hr = process_payment($p);
1058 return $hr if $hr->{'error'};
1063 sub process_prepay {
1067 my $session = _cache->get($p->{'session_id'})
1068 or return { 'error' => "Can't resume session" }; #better error message
1072 my $custnum = $session->{'custnum'};
1074 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1075 or return { 'error' => "unknown custnum $custnum" };
1077 my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1078 my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1086 return { 'error' => $error } if $error;
1088 return { 'error' => '',
1089 'amount' => $amount,
1090 'seconds' => $seconds,
1091 'duration' => duration_exact($seconds),
1092 'upbytes' => $upbytes,
1093 'upload' => FS::UI::bytecount::bytecount_unexact($upbytes),
1094 'downbytes' => $downbytes,
1095 'download' => FS::UI::bytecount::bytecount_unexact($downbytes),
1096 'totalbytes'=> $totalbytes,
1097 'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1104 my $session = _cache->get($p->{'session_id'})
1105 or return { 'error' => "Can't resume session" }; #better error message
1107 my $custnum = $session->{'custnum'};
1109 my $invnum = $p->{'invnum'};
1111 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1112 'custnum' => $custnum } )
1113 or return { 'error' => "Can't find invnum" };
1117 return { 'error' => '',
1118 'invnum' => $invnum,
1119 'invoice_text' => join('', $cust_bill->print_text ),
1120 'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1127 my $session = _cache->get($p->{'session_id'})
1128 or return { 'error' => "Can't resume session" }; #better error message
1130 my $custnum = $session->{'custnum'};
1132 my $invnum = $p->{'invnum'};
1134 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum,
1135 'custnum' => $custnum } )
1136 or return { 'error' => "Can't find invnum" };
1140 return { 'error' => '',
1141 'invnum' => $invnum,
1142 'invoice_pdf' => $cust_bill->print_pdf( { unsquelch_cdr => 1 } ),
1147 sub legacy_invoice {
1149 my $session = _cache->get($p->{'session_id'})
1150 or return { 'error' => "Can't resume session" }; #better error message
1152 my $custnum = $session->{'custnum'};
1154 my $legacyinvnum = $p->{'legacyinvnum'};
1156 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1157 'legacyinvnum' => $legacyinvnum,
1158 'custnum' => $custnum,
1159 }) or return { 'error' => "Can't find legacyinvnum" };
1163 return { 'error' => '',
1164 'legacyinvnum' => $legacyinvnum,
1165 'invoice_html' => $legacy_cust_bill->content_html,
1170 sub legacy_invoice_pdf {
1172 my $session = _cache->get($p->{'session_id'})
1173 or return { 'error' => "Can't resume session" }; #better error message
1175 my $custnum = $session->{'custnum'};
1177 my $legacyinvnum = $p->{'legacyinvnum'};
1179 my $legacy_cust_bill = qsearchs('legacy_cust_bill', {
1180 'legacyinvnum' => $legacyinvnum,
1181 'custnum' => $custnum,
1182 }) or return { 'error' => "Can't find legacyinvnum" };
1186 return { 'error' => '',
1187 'legacyinvnum' => $legacyinvnum,
1188 'invoice_pdf' => $legacy_cust_bill->content_pdf,
1196 #sessioning for this? how do we get the session id to the backend invoice
1197 # template so it can add it to the link, blah
1200 if ( $p->{'invnum'} ) {
1201 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1202 or return { 'error' => 'unknown invnum' };
1203 $agentnum = $cust_bill->cust_main->agentnum;
1206 my $templatename = $p->{'template'} || $p->{'templatename'};
1208 #false laziness-ish w/view/cust_bill-logo.cgi
1210 my $conf = new FS::Conf;
1211 if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1212 $templatename = "_$1";
1217 my $filename = "logo$templatename.png";
1219 return { 'error' => '',
1220 'logo' => $conf->config_binary($filename, $agentnum),
1221 'content_type' => 'image/png', #should allow gif, jpg too
1228 my $session = _cache->get($p->{'session_id'})
1229 or return { 'error' => "Can't resume session" }; #better error message
1231 my $custnum = $session->{'custnum'};
1233 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1234 or return { 'error' => "unknown custnum $custnum" };
1236 my @cust_bill = $cust_main->cust_bill;
1237 my @legacy_cust_bill = $cust_main->legacy_cust_bill;
1241 return { 'error' => '',
1242 'balance' => $cust_main->balance,
1245 my $owed = $_->owed;
1247 +{ 'invnum' => $_->invnum,
1248 '_date' => $_->_date,
1249 'date' => time2str("%b %o, %Y", $_->_date),
1250 'date_short' => time2str("%m-%d-%Y", $_->_date),
1251 'previous' => sprintf('%.2f', ($_->previous)[0]),
1252 'charged' => sprintf('%.2f', $_->charged),
1253 'owed' => sprintf('%.2f', $owed),
1254 'balance' => sprintf('%.2f', $balance),
1259 'legacy_invoices' => [
1261 +{ 'legacyinvnum' => $_->legacyinvnum,
1262 'legacyid' => $_->legacyid,
1263 '_date' => $_->_date,
1264 'date' => time2str("%b %o, %Y", $_->_date),
1265 'date_short' => time2str("%m-%d-%Y", $_->_date),
1266 'charged' => sprintf('%.2f', $_->charged),
1267 'has_content' => ( length($_->content_pdf)
1268 || length($_->content_html) ),
1278 my $session = _cache->get($p->{'session_id'})
1279 or return { 'error' => "Can't resume session" }; #better error message
1281 my $custnum = $session->{'custnum'};
1283 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1284 or return { 'error' => "unknown custnum $custnum" };
1286 my @errors = $cust_main->cancel( 'quiet'=>1 );
1288 my $error = scalar(@errors) ? join(' / ', @errors) : '';
1290 return { 'error' => $error };
1297 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1298 return { 'error' => $session } if $context eq 'error';
1300 my $search = { 'custnum' => $custnum };
1301 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1302 my $cust_main = qsearchs('cust_main', $search )
1303 or return { 'error' => "unknown custnum $custnum" };
1305 my $conf = new FS::Conf;
1307 # the duplication below is necessary:
1308 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1309 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1310 # non-backwards-compatible change breaking the software of anyone using the API
1311 # instead of the stock selfservice
1312 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1313 if( $conf->exists('selfservice_server-view-wholesale') ) {
1314 return { 'svcnum' => $session->{'svcnum'},
1315 'custnum' => $custnum,
1316 'cust_pkg' => [ map {
1318 part_pkg => [ map $_->hashref, $_->part_pkg ],
1320 [ map $_->hashref, $_->available_part_svc ],
1322 [ map { my $ref = { $_->hash,
1323 label => [ $_->label ],
1325 $ref->{_password} = $_->svc_x->_password
1326 if $context eq 'agent'
1327 && $conf->exists('agent-showpasswords')
1328 && $_->part_svc->svcdb eq 'svc_acct';
1333 } $cust_main->cust_pkg
1336 small_custview( $cust_main, $conf->config('countrydefault') ),
1337 'wholesale_view' => 1,
1338 'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1339 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1340 'lnp' => $conf->exists('svc_phone-lnp'),
1344 { 'svcnum' => $session->{'svcnum'},
1345 'custnum' => $custnum,
1346 'cust_pkg' => [ map {
1347 my $primary_cust_svc = $_->primary_cust_svc;
1350 status => $_->status,
1352 [ map $_->hashref, $_->available_part_svc ],
1354 [ map { my $ref = { $_->hash,
1355 label => [ $_->label ],
1357 $ref->{_password} = $_->svc_x->_password
1358 if $context eq 'agent'
1359 && $conf->exists('agent-showpasswords')
1360 && $_->part_svc->svcdb eq 'svc_acct';
1361 $ref->{svchash} = { $_->svc_x->hash } if
1362 $_->part_svc->svcdb eq 'svc_phone';
1363 $ref->{svchash}->{svcpart} = $_->part_svc->svcpart
1364 if $_->part_svc->svcdb eq 'svc_phone'; # hack
1370 ? { $primary_cust_svc->hash,
1371 label => [ $primary_cust_svc->label ],
1372 finger => $primary_cust_svc->svc_x->finger, #uuh
1373 $primary_cust_svc->part_svc->hash,
1377 } $cust_main->ncancelled_pkgs
1380 small_custview( $cust_main, $conf->config('countrydefault') ),
1388 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1389 return { 'error' => $session } if $context eq 'error';
1391 my $search = { 'custnum' => $custnum };
1392 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1393 my $cust_main = qsearchs('cust_main', $search )
1394 or return { 'error' => "unknown custnum $custnum" };
1396 my $pkgnum = $session->{'pkgnum'} || $p->{'pkgnum'} || '';
1397 if ( ! $pkgnum && $p->{'svcnum'} ) {
1398 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $p->{'svcnum'} } );
1399 $pkgnum = $cust_svc->pkgnum if $cust_svc;
1403 #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1404 foreach my $cust_pkg ( $p->{'ncancelled'}
1405 ? $cust_main->ncancelled_pkgs
1406 : $cust_main->unsuspended_pkgs ) {
1407 next if $pkgnum && $cust_pkg->pkgnum != $pkgnum;
1408 push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1410 if ( $p->{'svcdb'} ) {
1411 my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1413 : ref($p->{'svcdb'}) eq 'ARRAY'
1414 ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1415 : { $p->{'svcdb'} => 1 };
1416 @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1419 #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1422 my $conf = new FS::Conf;
1425 'svcnum' => $session->{'svcnum'},
1426 'custnum' => $custnum,
1427 'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1428 'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1431 my $svc_x = $_->svc_x;
1432 my($label, $value) = $_->label;
1433 my $svcdb = $_->part_svc->svcdb;
1434 my $part_pkg = $_->cust_pkg->part_pkg;
1437 'svcnum' => $_->svcnum,
1443 if ( $svcdb eq 'svc_acct' ) {
1446 'username' => $svc_x->username,
1447 'email' => $svc_x->email,
1448 'finger' => $svc_x->finger,
1449 'seconds' => $svc_x->seconds,
1450 'upbytes' => display_bytecount($svc_x->upbytes),
1451 'downbytes' => display_bytecount($svc_x->downbytes),
1452 'totalbytes' => display_bytecount($svc_x->totalbytes),
1454 'recharge_amount' => $part_pkg->option('recharge_amount',1),
1455 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1456 'recharge_upbytes' =>
1457 display_bytecount($part_pkg->option('recharge_upbytes',1)),
1458 'recharge_downbytes' =>
1459 display_bytecount($part_pkg->option('recharge_downbytes',1)),
1460 'recharge_totalbytes' =>
1461 display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1465 } elsif ( $svcdb eq 'svc_dsl' ) {
1466 $hash{'phonenum'} = $svc_x->phonenum;
1467 if ( $svc_x->first || $svc_x->get('last') || $svc_x->company ) {
1468 $hash{'name'} = $svc_x->first. ' '. $svc_x->get('last');
1469 $hash{'name'} = $svc_x->company. ' ('. $hash{'name'}. ')'
1472 $hash{'name'} = $cust_main->name;
1475 # elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1489 sub _customer_svc_x {
1490 my($custnum, $svcnum, $table) = @_;
1492 $custnum =~ /^(\d+)$/ or die "illegal custnum";
1493 my $search = " AND custnum = $1";
1494 #$search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1497 'table' => ($table || 'svc_acct'),
1498 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
1499 'LEFT JOIN cust_pkg USING ( pkgnum ) ',#.
1500 #'LEFT JOIN cust_main USING ( custnum ) ',
1501 'hashref' => { 'svcnum' => $svcnum, },
1502 'extra_sql' => $search, #important
1507 sub list_dsl_devices {
1510 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1511 return { 'error' => $session } if $context eq 'error';
1513 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1514 or return { 'error' => "Service not found" };
1517 'devices' => [ map {
1518 +{ 'mac_addr' => $_->mac_addr };
1519 } $svc_dsl->dsl_device
1525 sub add_dsl_device {
1528 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1529 return { 'error' => $session } if $context eq 'error';
1531 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1532 or return { 'error' => "Service not found" };
1534 return { 'error' => 'No MAC address supplied' }
1535 unless length($p->{'mac_addr'});
1537 my $dsl_device = new FS::dsl_device { 'svcnum' => $svc_dsl->svcnum,
1538 'mac_addr' => scalar($p->{'mac_addr'}),
1540 my $error = $dsl_device->insert;
1541 return { 'error' => $error };
1545 sub delete_dsl_device {
1548 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1549 return { 'error' => $session } if $context eq 'error';
1551 my $svc_dsl = _customer_svc_x( $custnum, $p->{'svcnum'}, 'svc_dsl' )
1552 or return { 'error' => "Service not found" };
1554 my $dsl_device = qsearchs('dsl_device', { 'svcnum' => $svc_dsl->svcnum,
1555 'mac_addr' => scalar($p->{'mac_addr'}),
1558 or return { 'error' => 'Unknown MAC address: '. $p->{'mac_addr'} };
1560 my $error = $dsl_device->delete;
1561 return { 'error' => $error };
1567 _usage_details( \&_port_graph, $p,
1568 'svcdb' => 'svc_port',
1573 my($svc_port, $begin, $end) = @_;
1575 my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
1576 push @usage, { 'png' => $pngOrError };
1580 sub _list_svc_usage {
1581 my($svc_acct, $begin, $end) = @_;
1583 foreach my $part_export (
1584 map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1585 qw( sqlradius sqlradius_withdomain )
1587 push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1592 sub list_svc_usage {
1593 _usage_details(\&_list_svc_usage, @_);
1596 sub _list_support_usage {
1597 my($svc_acct, $begin, $end) = @_;
1599 foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1600 qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1602 push @usage, { 'seconds' => $_->seconds,
1603 'support' => $_->support,
1604 '_date' => $_->_date,
1605 'id' => $_->transaction_id,
1606 'creator' => $_->creator,
1607 'subject' => $_->subject,
1608 'status' => $_->status,
1609 'ticketid' => $_->ticketid,
1615 sub list_support_usage {
1616 _usage_details(\&_list_support_usage, @_);
1619 sub _list_cdr_usage {
1620 my($svc_phone, $begin, $end) = @_;
1621 map [ $_->downstream_csv('format' => 'default', 'keeparray' => 1) ], #XXX config for format
1622 $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1625 sub list_cdr_usage {
1627 _usage_details( \&_list_cdr_usage, $p,
1628 'svcdb' => 'svc_phone',
1632 sub _usage_details {
1633 my($callback, $p, %opt) = @_;
1635 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1636 return { 'error' => $session } if $context eq 'error';
1638 my $search = { 'svcnum' => $p->{'svcnum'} };
1639 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1641 my $svcdb = $opt{'svcdb'} || 'svc_acct';
1643 my $svc_x = qsearchs( $svcdb, $search );
1644 return { 'error' => 'No service selected in list_svc_usage' }
1647 my $header = $svcdb eq 'svc_phone'
1648 ? [ split(',', FS::cdr::invoice_header('default') ) ] #XXX
1651 my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1652 my $freq = $cust_pkg->part_pkg->freq;
1653 my $start = $cust_pkg->setup;
1654 #my $end = $cust_pkg->bill; # or time?
1657 unless ( $p->{beginning} ) {
1658 $p->{beginning} = $cust_pkg->last_bill;
1659 $p->{ending} = $end;
1662 my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending});
1664 #kinda false laziness with FS::cust_main::bill, but perhaps
1665 #we should really change this bit to DateTime and DateTime::Duration
1667 #change this bit to use Date::Manip? CAREFUL with timezones (see
1668 # mailing list archive)
1669 my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
1670 (localtime($p->{ending}) )[0,1,2,3,4,5];
1671 my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
1672 (localtime($p->{beginning}) )[0,1,2,3,4,5];
1674 if ( $freq =~ /^\d+$/ ) {
1676 until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
1678 until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
1679 } elsif ( $freq =~ /^(\d+)w$/ ) {
1681 $nmday += $weeks * 7;
1682 $pmday -= $weeks * 7;
1683 } elsif ( $freq =~ /^(\d+)d$/ ) {
1687 } elsif ( $freq =~ /^(\d+)h$/ ) {
1692 return { 'error' => "unparsable frequency: ". $freq };
1695 my $previous = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
1696 my $next = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
1700 'svcnum' => $p->{svcnum},
1701 'beginning' => $p->{beginning},
1702 'ending' => $p->{ending},
1703 'previous' => ($previous > $start) ? $previous : $start,
1704 'next' => ($next < $end) ? $next : $end,
1705 'header' => $header,
1713 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1714 return { 'error' => $session } if $context eq 'error';
1716 my $search = { 'custnum' => $custnum };
1717 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1718 my $cust_main = qsearchs('cust_main', $search )
1719 or return { 'error' => "unknown custnum $custnum" };
1721 my $status = $cust_main->status;
1722 #false laziness w/ClientAPI/Signup.pm
1724 my $cust_pkg = new FS::cust_pkg ( {
1725 'custnum' => $custnum,
1726 'pkgpart' => $p->{'pkgpart'},
1728 my $error = $cust_pkg->check;
1729 return { 'error' => $error } if $error;
1732 unless ( $p->{'svcpart'} eq 'none' ) {
1736 if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
1738 my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
1739 return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
1740 $svcdb = $part_svc->svcdb;
1742 $svcdb = 'svc_acct';
1744 $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
1747 'svc_acct' => [ qw( username domsvc _password sec_phrase popnum ) ],
1748 'svc_domain' => [ qw( domain ) ],
1749 'svc_phone' => [ qw( phonenum pin sip_password phone_name ) ],
1750 'svc_external' => [ qw( id title ) ],
1751 'svc_pbx' => [ qw( id title ) ],
1754 my $svc_x = "FS::$svcdb"->new( {
1755 'svcpart' => $svcpart,
1756 map { $_ => $p->{$_} } @{$fields{$svcdb}}
1759 if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
1762 while ( length($p->{"snarf_machine$snarfnum"}) ) {
1763 my $acct_snarf = new FS::acct_snarf ( {
1764 'machine' => $p->{"snarf_machine$snarfnum"},
1765 'protocol' => $p->{"snarf_protocol$snarfnum"},
1766 'username' => $p->{"snarf_username$snarfnum"},
1767 '_password' => $p->{"snarf_password$snarfnum"},
1770 push @acct_snarf, $acct_snarf;
1772 $svc_x->child_objects( \@acct_snarf );
1775 my $y = $svc_x->setdefault; # arguably should be in new method
1776 return { 'error' => $y } if $y && !ref($y);
1778 $error = $svc_x->check;
1779 return { 'error' => $error } if $error;
1786 tie my %hash, 'Tie::RefHash';
1787 %hash = ( $cust_pkg => \@svc );
1789 $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
1790 return { 'error' => $error } if $error;
1792 my $conf = new FS::Conf;
1793 if ( $conf->exists('signup_server-realtime') ) {
1795 my $bill_error = _do_bop_realtime( $cust_main, $status );
1798 $cust_pkg->cancel('quiet'=>1);
1801 $cust_pkg->reexport;
1805 $cust_pkg->reexport;
1808 my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
1810 return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
1817 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1818 return { 'error' => $session } if $context eq 'error';
1820 my $search = { 'custnum' => $custnum };
1821 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1822 my $cust_main = qsearchs('cust_main', $search )
1823 or return { 'error' => "unknown custnum $custnum" };
1825 my $status = $cust_main->status;
1826 my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
1827 or return { 'error' => "unknown package $p->{pkgnum}" };
1830 my $error = FS::cust_pkg::order( $custnum,
1836 my $conf = new FS::Conf;
1837 if ( $conf->exists('signup_server-realtime') ) {
1839 my $bill_error = _do_bop_realtime( $cust_main, $status );
1842 $newpkg[0]->suspend;
1845 $newpkg[0]->reexport;
1849 $newpkg[0]->reexport;
1852 return { error => '', pkgnum => $cust_pkg->pkgnum };
1856 sub order_recharge {
1859 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1860 return { 'error' => $session } if $context eq 'error';
1862 my $search = { 'custnum' => $custnum };
1863 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1864 my $cust_main = qsearchs('cust_main', $search )
1865 or return { 'error' => "unknown custnum $custnum" };
1867 my $status = $cust_main->status;
1868 my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
1869 or return { 'error' => "unknown service " . $p->{'svcnum'} };
1871 my $svc_x = $cust_svc->svc_x;
1872 my $part_pkg = $cust_svc->cust_pkg->part_pkg;
1875 map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) }
1876 qw ( recharge_seconds recharge_upbytes recharge_downbytes
1877 recharge_totalbytes );
1878 my $amount = $part_pkg->option('recharge_amount', 1);
1880 my ($l, $v, $d) = $cust_svc->label; # blah
1881 my $pkg = "Recharge $v";
1883 my $bill_error = $cust_main->charge($amount, $pkg,
1884 "time: $vhash{seconds}, up: $vhash{upbytes}," .
1885 "down: $vhash{downbytes}, total: $vhash{totalbytes}",
1886 $part_pkg->taxclass); #meh
1888 my $conf = new FS::Conf;
1889 if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
1891 $bill_error = _do_bop_realtime( $cust_main, $status );
1896 my $error = $svc_x->recharge (\%vhash);
1897 return { 'error' => $error } if $error;
1901 my $error = $bill_error;
1902 $error ||= $svc_x->recharge (\%vhash);
1903 return { 'error' => $error } if $error;
1906 return { error => '', svc => $cust_svc->part_svc->svc };
1910 sub _do_bop_realtime {
1911 my ($cust_main, $status) = (shift, shift);
1913 my $old_balance = $cust_main->balance;
1915 my $bill_error = $cust_main->bill
1916 || $cust_main->apply_payments_and_credits
1917 || $cust_main->realtime_collect('selfservice' => 1);
1919 if ( $cust_main->balance > $old_balance
1920 && $cust_main->balance > 0
1921 && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
1922 1 : $status eq 'suspended' ) ) {
1923 #this makes sense. credit is "un-doing" the invoice
1924 my $conf = new FS::Conf;
1925 $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
1926 'self-service decline',
1927 'reason_type' => $conf->config('signup_credit_type'),
1929 $cust_main->apply_credits( 'order' => 'newest' );
1931 return { 'error' => '_decline', 'bill_error' => $bill_error };
1940 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1941 return { 'error' => $session } if $context eq 'error';
1943 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1944 or return { 'error' => "unknown custnum $custnum" };
1946 my @cust_pkg = sort { $a->bill <=> $b->bill }
1947 grep { $_->part_pkg->freq ne '0' }
1948 $cust_main->ncancelled_pkgs;
1950 #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
1952 my $total = $cust_main->balance;
1955 my $bill = $_->bill;
1956 $total += $_->part_pkg->base_recur($_, \$bill);
1957 my $renew_date = $_->part_pkg->add_freq($_->bill);
1959 'pkgnum' => $_->pkgnum,
1960 'amount' => sprintf('%.2f', $total),
1961 'bill_date' => $_->bill,
1962 'bill_date_pretty' => time2str('%x', $_->bill),
1963 'renew_date' => $renew_date,
1964 'renew_date_pretty' => time2str('%x', $renew_date),
1965 'expire_date' => $_->expire,
1966 'expire_date_pretty' => time2str('%x', $_->expire),
1971 return { 'dates' => \@array };
1975 sub payment_info_renew_info {
1977 my $renew_info = renew_info($p);
1978 my $payment_info = payment_info($p);
1979 return { %$renew_info,
1987 my($context, $session, $custnum) = _custoragent_session_custnum($p);
1988 return { 'error' => $session } if $context eq 'error';
1990 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1991 or return { 'error' => "unknown custnum $custnum" };
1993 my $date = $p->{'date'};
1997 #freeside-daily -n -d $date fs_daily $custnum
1998 $cust_main->bill_and_collect( 'time' => $date,
1999 'invoice_time' => $now,
2000 'actual_time' => $now,
2001 'check_freq' => '1d',
2004 return { 'error' => '' };
2010 my $session = _cache->get($p->{'session_id'})
2011 or return { 'error' => "Can't resume session" }; #better error message
2013 my $custnum = $session->{'custnum'};
2015 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2016 or return { 'error' => "unknown custnum $custnum" };
2018 my $conf = new FS::Conf;
2020 $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
2021 or return { 'error' => 'Permission denied' };
2023 my $pkgnum = $p->{'pkgnum'};
2025 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2026 'pkgnum' => $pkgnum, } )
2027 or return { 'error' => "unknown pkgnum $pkgnum" };
2029 my $error = $cust_pkg->suspend(reason => $reasonnum);
2030 return { 'error' => $error };
2036 my $session = _cache->get($p->{'session_id'})
2037 or return { 'error' => "Can't resume session" }; #better error message
2039 my $custnum = $session->{'custnum'};
2041 my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
2042 or return { 'error' => "unknown custnum $custnum" };
2044 my $pkgnum = $p->{'pkgnum'};
2046 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2047 'pkgnum' => $pkgnum, } )
2048 or return { 'error' => "unknown pkgnum $pkgnum" };
2050 my $error = $cust_pkg->cancel('quiet' => 1);
2051 return { 'error' => $error };
2055 sub provision_phone {
2058 @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
2060 if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
2061 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2062 return { 'error' => $session } if $context eq 'error';
2064 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2065 return { 'error' => 'service not found' } unless $svc_phone;
2066 return { 'error' => 'invalid svcnum' }
2067 if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
2069 $svc_phone->email($p->{'email'})
2070 if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
2071 $svc_phone->forwarddst($p->{'forwarddst'})
2072 if $svc_phone->forwarddst ne $p->{'forwarddst'}
2073 && $p->{'forwarddst'} =~ /^(\d+|)$/;
2074 return { 'error' => $svc_phone->replace };
2078 unless($p->{'lnp'}) {
2079 $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
2080 $p->{'lnp_status'} = "portingin";
2081 return _provision( 'FS::svc_phone',
2082 [qw(lnp_desired_due_date lnp_other_provider
2083 lnp_other_provider_account phonenum countrycode lnp_status)],
2084 [qw(phonenum countrycode)],
2091 unless (scalar(@bulkdid)) {
2092 return _provision( 'FS::svc_phone',
2093 [qw(phonenum countrycode)],
2094 [qw(phonenum countrycode)],
2100 # bulk DID order case
2102 foreach my $did ( @bulkdid ) {
2103 $did =~ s/[^0-9]//g;
2104 $error = _provision( 'FS::svc_phone',
2105 [qw(phonenum countrycode)],
2106 [qw(phonenum countrycode)],
2108 'pkgnum' => $p->{'pkgnum'},
2109 'svcpart' => $p->{'svcpart'},
2111 'countrycode' => $p->{'countrycode'},
2112 'session_id' => $p->{'session_id'},
2115 return $error if ($error->{'error'} && length($error->{'error'}) > 1);
2117 { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
2120 sub provision_acct {
2122 warn "provision_acct called\n"
2125 return { 'error' => gettext('passwords_dont_match') }
2126 if $p->{'_password'} ne $p->{'_password2'};
2127 return { 'error' => gettext('empty_password') }
2128 unless length($p->{'_password'});
2130 if ($p->{'domsvc'}) {
2131 my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
2132 qw ( svcpart pkgnum ) );
2133 return { 'error' => gettext('invalid_domain') }
2134 unless ($domains{$p->{'domsvc'}});
2137 warn "provision_acct calling _provision\n"
2139 _provision( 'FS::svc_acct',
2140 [qw(username _password domsvc)],
2141 [qw(username _password domsvc)],
2147 sub provision_external {
2149 #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
2150 _provision( 'FS::svc_external',
2159 my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
2160 warn "_provision called for $class\n"
2163 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2164 return { 'error' => $session } if $context eq 'error';
2166 my $search = { 'custnum' => $custnum };
2167 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2168 my $cust_main = qsearchs('cust_main', $search )
2169 or return { 'error' => "unknown custnum $custnum" };
2171 my $pkgnum = $p->{'pkgnum'};
2173 warn "searching for custnum $custnum pkgnum $pkgnum\n"
2175 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2176 'pkgnum' => $pkgnum,
2178 or return { 'error' => "unknown pkgnum $pkgnum" };
2180 warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2182 my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2183 or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2185 warn "creating $class record\n"
2187 my $svc_x = $class->new( {
2188 'pkgnum' => $p->{'pkgnum'},
2189 'svcpart' => $p->{'svcpart'},
2190 map { $_ => $p->{$_} } @$fields
2192 warn "inserting $class record\n"
2194 my $error = $svc_x->insert;
2197 warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2199 $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2202 my $return = { 'svc' => $part_svc->svc,
2204 map { $_ => $svc_x->get($_) } @$return_fields
2206 warn "_provision returning ". Dumper($return). "\n"
2215 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2216 return { 'error' => $session } if $context eq 'error';
2218 my $search = { 'custnum' => $custnum };
2219 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2220 my $cust_main = qsearchs('cust_main', $search )
2221 or return { 'error' => "unknown custnum $custnum" };
2223 my $pkgnum = $p->{'pkgnum'};
2225 my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2226 'pkgnum' => $pkgnum,
2228 or return { 'error' => "unknown pkgnum $pkgnum" };
2230 my $svcpart = $p->{'svcpart'};
2232 my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2233 'svcpart' => $svcpart, } )
2234 or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2235 my $part_svc = $pkg_svc->part_svc;
2237 my $conf = new FS::Conf;
2240 'svc' => $part_svc->svc,
2241 'svcdb' => $part_svc->svcdb,
2242 'pkgnum' => $pkgnum,
2243 'svcpart' => $svcpart,
2244 'custnum' => $custnum,
2246 'security_phrase' => 0, #XXX !
2247 'svc_acct_pop' => [], #XXX !
2249 'init_popstate' => '',
2254 small_custview( $cust_main, $conf->config('countrydefault') ),
2258 if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/
2259 && $ret->{'svcdb'} eq 'svc_phone') {
2260 $ret->{'svcnum'} = $p->{'svcnum'};
2261 my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2262 if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2263 $ret->{'email'} = $svc_phone->email;
2264 $ret->{'forwarddst'} = $svc_phone->forwarddst;
2271 sub unprovision_svc {
2274 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2275 return { 'error' => $session } if $context eq 'error';
2277 my $search = { 'custnum' => $custnum };
2278 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2279 my $cust_main = qsearchs('cust_main', $search )
2280 or return { 'error' => "unknown custnum $custnum" };
2282 my $svcnum = $p->{'svcnum'};
2284 my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $svcnum, } )
2285 or return { 'error' => "unknown svcnum $svcnum" };
2287 return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2288 unless $cust_svc->cust_pkg->custnum == $custnum;
2290 my $conf = new FS::Conf;
2292 return { 'svc' => $cust_svc->part_svc->svc,
2293 'error' => $cust_svc->cancel,
2295 small_custview( $cust_main, $conf->config('countrydefault') ),
2300 sub myaccount_passwd {
2302 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2303 return { 'error' => $session } if $context eq 'error';
2305 return { 'error' => "New passwords don't match." }
2306 if $p->{'new_password'} ne $p->{'new_password2'};
2308 return { 'error' => 'Enter new password' }
2309 unless length($p->{'new_password'});
2311 #my $search = { 'custnum' => $custnum };
2312 #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2313 $custnum =~ /^(\d+)$/ or die "illegal custnum";
2314 my $search = " AND custnum = $1";
2315 $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2317 my $svc_acct = qsearchs( {
2318 'table' => 'svc_acct',
2319 'addl_from' => 'LEFT JOIN cust_svc USING ( svcnum ) '.
2320 'LEFT JOIN cust_pkg USING ( pkgnum ) '.
2321 'LEFT JOIN cust_main USING ( custnum ) ',
2322 'hashref' => { 'svcnum' => $p->{'svcnum'}, },
2323 'extra_sql' => $search, #important
2325 or return { 'error' => "Service not found" };
2327 if ( exists($p->{'old_password'}) ) {
2328 return { 'error' => "Incorrect password." }
2329 unless $svc_acct->check_password($p->{'old_password'});
2332 $svc_acct->_password($p->{'new_password'});
2333 my $error = $svc_acct->replace();
2335 my($label, $value) = $svc_acct->cust_svc->label;
2337 return { 'error' => $error,
2347 my $conf = new FS::Conf;
2348 my $verification = $conf->config('selfservice-password_reset_verification')
2349 or return { 'error' => 'Password resets disabled' };
2351 my $username = $p->{'username'};
2353 my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
2354 or return { 'error' => 'Account not found' };
2356 my $svc_acct = qsearchs('svc_acct', { 'username' => $p->{'username'},
2357 'domsvc' => $svc_domain->svcnum }
2359 or return { 'error' => 'Account not found' };
2361 my $cust_pkg = $svc_acct->cust_svc->cust_pkg
2362 or return { 'error' => 'Account not found' };
2364 my $cust_main = $cust_pkg->cust_main;
2368 my( $p, $cust_main ) = @_;
2369 $cust_main->payby =~ /^(CARD|DCRD|CHEK|DCHK)$/
2370 && $p->{'paymask'} eq substr($cust_main->paymask, -4)
2373 my( $p, $cust_main ) = @_;
2374 my $cust_pay = qsearchs({
2375 'table' => 'cust_pay',
2376 'hashref' => { 'custnum' => $cust_main->custnum },
2377 'order_by' => 'ORDER BY _date DESC LIMIT 1',
2381 $p->{'amount'} == $cust_pay->paid;
2384 my( $p, $cust_main ) = @_;
2385 $p->{'zip'} eq $cust_main->zip
2386 || ( $cust_main->ship_zip && $p->{'zip'} eq $cust_main->ship_zip );
2390 foreach my $verify ( split(',', $verification) ) {
2392 &{ $verify{$verify} }( $p, $cust_main )
2393 or return { 'error' => 'Account not found' };
2397 #we're verified. now what?
2400 return { 'error' => '' };
2406 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2407 return { 'error' => $session } if $context eq 'error';
2409 warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
2410 FS::TicketSystem->init();
2412 my $conf = new FS::Conf;
2413 my $queue = $p->{'queue'}
2414 || $conf->config('ticket_system-selfservice_queueid')
2415 || $conf->config('ticket_system-default_queueid');
2417 warn "$me create_ticket: creating ticket\n" if $DEBUG;
2418 my $err_or_ticket = FS::TicketSystem->create_ticket(
2419 '', #create RT session based on FS CurrentUser (fs_selfservice)
2421 'custnum' => $custnum,
2422 'svcnum' => $session->{'svcnum'},
2423 map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
2426 if ( ref($err_or_ticket) ) {
2427 warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
2429 return { 'error' => '',
2430 'ticket_id' => $err_or_ticket->id,
2433 warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
2435 return { 'error' => $err_or_ticket };
2443 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2444 return { 'error' => $session } if $context eq 'error';
2446 return { error => 'requested format not implemented' }
2447 unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
2449 my $conf = new FS::Conf;
2450 my $age_threshold = 0;
2451 $age_threshold = time() - $conf->config('selfservice-recent-did-age')
2452 if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
2454 my $search = { 'custnum' => $custnum };
2455 $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2456 my $cust_main = qsearchs('cust_main', $search )
2457 or return { 'error' => "unknown custnum $custnum" };
2459 # does it make more sense to just run one sql query for this instead of all the
2460 # insanity below? would increase performance greately for large data sets?
2462 foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
2463 my @part_svc = $cust_pkg->part_svc;
2464 foreach my $part_svc ( @part_svc ) {
2465 if($part_svc->svcdb eq 'svc_phone'){
2466 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
2467 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
2468 push @svc_phone, $cust_pkg_svc->svc_x
2469 if $cust_pkg_svc->date_inserted >= $age_threshold;
2477 my($xls_r,$xls_c) = (0,0);
2480 my @fields = qw( countrycode phonenum pin sip_password phone_name );
2481 if($p->{'format'} eq 'csv') {
2482 $csv = new Text::CSV_XS { 'always_quote' => 1,
2485 return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2486 $content .= $csv->string;
2488 elsif($p->{'format'} eq 'xls') {
2489 my $XLS1 = new IO::Scalar \$content;
2490 $xls_workbook = Spreadsheet::WriteExcel->new($XLS1)
2491 or return { 'error' => "Error opening .xls file: $!" };
2492 $xls = $xls_workbook->add_worksheet('DIDs');
2493 foreach ( @fields ) {
2494 $xls->write(0,$xls_c++,$_);
2499 foreach my $svc_phone ( @svc_phone ) {
2500 my @cols = map { $svc_phone->$_ } @fields;
2501 if($p->{'format'} eq 'csv') {
2502 return { 'error' => 'Unable to create CSV' }
2503 unless $csv->combine(@cols);
2504 $content .= $csv->string;
2506 elsif($p->{'format'} eq 'xls') {
2509 $xls->write($xls_r,$xls_c++,$_);
2515 $xls_workbook->close() if $p->{'format'} eq 'xls';
2517 { content => $content, format => $p->{'format'}, };
2522 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2523 return { 'error' => $session } if $context eq 'error';
2525 warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2526 FS::TicketSystem->init();
2527 return { 'error' => 'get_ticket configuration error' }
2528 if $FS::TicketSystem::system ne 'RT_Internal';
2530 # check existence and ownership as part of this
2531 warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2532 my $rt_session = FS::TicketSystem->session('');
2533 my $Ticket = FS::TicketSystem->get_ticket_object(
2535 ticket_id => $p->{'ticket_id'},
2538 return { 'error' => 'ticket not found' } if !$Ticket;
2540 if ( length( $p->{'subject'} || '' ) ) {
2542 if ( $p->{'subject'} ne $Ticket->Subject ) {
2543 my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
2544 return { 'error' => "unable to set subject: $msg" } if !$val;
2548 if(length($p->{'reply'})) {
2549 my @err_or_res = FS::TicketSystem->correspond_ticket(
2551 'ticket_id' => $p->{'ticket_id'},
2552 'content' => $p->{'reply'},
2555 return { 'error' => 'unable to reply to ticket' }
2556 unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2559 warn "$me get_ticket: getting ticket history\n" if $DEBUG;
2560 my $err_or_ticket = FS::TicketSystem->get_ticket(
2562 'ticket_id' => $p->{'ticket_id'},
2565 if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
2566 warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
2568 return { 'error' => $err_or_ticket };
2571 my @custs = @{$err_or_ticket->{'custs'}};
2572 my @txns = @{$err_or_ticket->{'txns'}};
2575 # superseded by check in get_ticket_object
2576 #return { 'error' => 'invalid ticket requested' }
2577 #unless grep($_ eq $custnum, @custs);
2579 foreach my $txn ( @txns ) {
2580 push @filtered_txns, $txn
2581 if ($txn->{'type'} eq 'EmailRecord'
2582 || $txn->{'type'} eq 'Correspond'
2583 || $txn->{'type'} eq 'Create');
2586 warn "$me get_ticket: successful: \n"
2588 return { 'error' => '',
2589 'transactions' => \@filtered_txns,
2590 'ticket_fields' => $err_or_ticket->{'fields'},
2591 'ticket_id' => $p->{'ticket_id'},
2595 sub adjust_ticket_priority {
2597 my($context, $session, $custnum) = _custoragent_session_custnum($p);
2598 return { 'error' => $session } if $context eq 'error';
2600 warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
2601 FS::TicketSystem->init;
2602 my $ss_priority = FS::TicketSystem->selfservice_priority;
2604 return { 'error' => 'adjust_ticket_priority configuration error' }
2605 if $FS::TicketSystem::system ne 'RT_Internal'
2608 my $values = $p->{'values'}; #hashref, id => priority value
2611 foreach my $id (keys %$values) {
2612 warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
2613 my $Ticket = FS::TicketSystem->get_ticket_object('',
2615 'custnum' => $custnum,
2618 $ticket_error{$id} = 'ticket not found';
2622 # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
2623 # We're not going to implement it for RT_External.
2624 my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
2625 my $new_value = $values->{$id};
2626 next if $old_value eq $new_value;
2628 warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
2630 # AddCustomFieldValue works fine (replacing any existing value) if it's
2631 # a single-valued custom field, which it should be. If it's not, you're
2632 # doing something wrong.
2634 if ( length($new_value) ) {
2635 ($val, $msg) = $Ticket->AddCustomFieldValue(
2636 Field => $ss_priority,
2637 Value => $new_value,
2641 ($val, $msg) = $Ticket->DeleteCustomFieldValue(
2642 Field => $ss_priority,
2643 Value => $old_value,
2647 $ticket_error{$id} = $msg if !$val;
2648 warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
2650 return { 'error' => '',
2651 'ticket_error' => \%ticket_error,
2652 %{ customer_info($p) } # send updated customer info back
2658 sub _custoragent_session_custnum {
2661 my($context, $session, $custnum);
2662 if ( $p->{'session_id'} ) {
2664 $context = 'customer';
2665 $session = _cache->get($p->{'session_id'})
2666 or return ( 'error' => "Can't resume session" ); #better error message
2667 $custnum = $session->{'custnum'};
2669 } elsif ( $p->{'agent_session_id'} ) {
2672 my $agent_cache = new FS::ClientAPI_SessionCache( {
2673 'namespace' => 'FS::ClientAPI::Agent',
2675 $session = $agent_cache->get($p->{'agent_session_id'})
2676 or return ( 'error' => "Can't resume session" ); #better error message
2677 $custnum = $p->{'custnum'};
2681 return ( 'error' => "Can't resume session" ); #better error message
2684 ($context, $session, $custnum);