fix customer_info name, RT#13656
[freeside.git] / FS / FS / ClientAPI / MyAccount.pm
1 package FS::ClientAPI::MyAccount;
2
3 use 5.008; #require 5.8+ for Time::Local 1.05+
4 use strict;
5 use vars qw( $cache $DEBUG $me );
6 use subs qw( _cache _provision );
7 use Data::Dumper;
8 use Digest::MD5 qw(md5_hex);
9 use Date::Format;
10 use Business::CreditCard;
11 use Time::Duration;
12 use Time::Local qw(timelocal_nocheck);
13 use FS::UI::Web::small_custview qw(small_custview); #less doh
14 use FS::UI::Web;
15 use FS::UI::bytecount qw( display_bytecount );
16 use FS::Conf;
17 #use FS::UID qw(dbh);
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;
23 use FS::cust_svc;
24 use FS::svc_acct;
25 use FS::svc_domain;
26 use FS::svc_phone;
27 use FS::svc_external;
28 use FS::part_svc;
29 use FS::cust_main;
30 use FS::cust_bill;
31 use FS::cust_main_county;
32 use FS::cust_pkg;
33 use FS::payby;
34 use FS::acct_rt_transaction;
35 use HTML::Entities;
36 use FS::TicketSystem;
37 use Text::CSV_XS;
38 use IO::Scalar;
39 use Spreadsheet::WriteExcel;
40
41 $DEBUG = 0;
42 $me = '[FS::ClientAPI::MyAccount]';
43
44 use vars qw( @cust_main_editable_fields );
45 @cust_main_editable_fields = qw(
46   first last company address1 address2 city
47     county state zip country
48     daytime night fax mobile
49   ship_first ship_last ship_company ship_address1 ship_address2 ship_city
50     ship_state ship_zip ship_country
51     ship_daytime ship_night ship_fax ship_mobile
52   locale
53   payby payinfo payname paystart_month paystart_year payissue payip
54   ss paytype paystate stateid stateid_state
55 );
56
57 BEGIN { #preload to reduce time customer_info takes
58   if ( $FS::TicketSystem::system ) {
59     warn "$me: initializing ticket system\n" if $DEBUG;
60     FS::TicketSystem->init();
61   }
62 }
63
64 sub _cache {
65   $cache ||= new FS::ClientAPI_SessionCache( {
66                'namespace' => 'FS::ClientAPI::MyAccount',
67              } );
68 }
69
70 sub skin_info {
71   my $p = shift;
72
73   my($context, $session, $custnum) = _custoragent_session_custnum($p);
74   #return { 'error' => $session } if $context eq 'error';
75
76   my $agentnum = '';
77   if ( $context eq 'customer' ) {
78
79     my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
80       or die dbh->errstr;
81
82     $sth->execute($custnum) or die $sth->errstr;
83
84     $agentnum = $sth->fetchrow_arrayref->[0]
85       or die "no agentnum for custnum $custnum";
86
87   #} elsif ( $context eq 'agent' ) {
88   } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
89     $agentnum = $1;
90   }
91
92   my $conf = new FS::Conf;
93
94   #false laziness w/Signup.pm
95
96   my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
97
98   if ( $skin_info_cache_agent ) {
99
100     warn "$me loading cached skin info for agentnum $agentnum\n"
101       if $DEBUG > 1;
102
103   } else {
104
105     warn "$me populating skin info cache for agentnum $agentnum\n"
106       if $DEBUG > 1;
107
108     $skin_info_cache_agent = {
109       'agentnum' => $agentnum,
110       ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
111         qw( company_name date_format ) ),
112       ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
113         qw( body_bgcolor box_bgcolor
114             text_color link_color vlink_color hlink_color alink_color
115             font title_color title_align title_size menu_bgcolor menu_fontsize
116           )
117       ),
118       ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
119         qw( menu_skipblanks menu_skipheadings menu_nounderline )
120       ),
121       ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
122         qw( title_left_image title_right_image
123             menu_top_image menu_body_image menu_bottom_image
124           )
125       ),
126       'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
127       ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
128         qw( head body_header body_footer company_address ) ),
129     };
130
131     _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
132
133   }
134
135   #{ %$skin_info_cache_agent };
136   $skin_info_cache_agent;
137
138 }
139
140 sub login_info {
141   my $p = shift;
142
143   my $conf = new FS::Conf;
144
145   my %info = (
146     %{ skin_info($p) },
147     'phone_login'  => $conf->exists('selfservice_server-phone_login'),
148     'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
149   );
150
151   return \%info;
152
153 }
154
155 #false laziness w/FS::ClientAPI::passwd::passwd
156 sub login {
157   my $p = shift;
158
159   my $conf = new FS::Conf;
160
161   my $svc_x = '';
162   if ( $p->{'domain'} eq 'svc_phone'
163        && $conf->exists('selfservice_server-phone_login') ) { 
164
165     my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
166     return { error => 'Number not found.' } unless $svc_phone;
167
168     #XXX?
169     #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
170     #return { error => 'Only primary user may log in.' } 
171     #  if $conf->exists('selfservice_server-primary_only')
172     #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
173
174     return { error => 'Incorrect PIN.' }
175       unless $svc_phone->check_pin($p->{'password'});
176
177     $svc_x = $svc_phone;
178
179   } else {
180
181     my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
182       or return { error => 'Domain '. $p->{'domain'}. ' not found' };
183
184     my $svc_acct = qsearchs( 'svc_acct', { 'username'  => $p->{'username'},
185                                            'domsvc'    => $svc_domain->svcnum, }
186                            );
187     return { error => 'User not found.' } unless $svc_acct;
188
189     if($conf->exists('selfservice_server-login_svcpart')) {
190         my @svcpart = $conf->config('selfservice_server-login_svcpart');
191         my $svcpart = $svc_acct->cust_svc->svcpart;
192         return { error => 'Invalid user.' } 
193             unless grep($_ eq $svcpart, @svcpart);
194     }
195
196     return { error => 'Incorrect password.' }
197       unless $svc_acct->check_password($p->{'password'});
198
199     $svc_x = $svc_acct;
200
201   }
202
203   my $session = {
204     'svcnum' => $svc_x->svcnum,
205   };
206
207   my $cust_svc = $svc_x->cust_svc;
208   my $cust_pkg = $cust_svc->cust_pkg;
209   if ( $cust_pkg ) {
210     my $cust_main = $cust_pkg->cust_main;
211     $session->{'custnum'} = $cust_main->custnum;
212     if ( $conf->exists('pkg-balances') ) {
213       my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
214                           $cust_main->ncancelled_pkgs;
215       $session->{'pkgnum'} = $cust_pkg->pkgnum
216         if scalar(@cust_pkg) > 1;
217     }
218   }
219
220   #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
221   #return { error => 'Only primary user may log in.' } 
222   #  if $conf->exists('selfservice_server-primary_only')
223   #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
224   my $part_pkg = $cust_pkg->part_pkg;
225   return { error => 'Only primary user may log in.' }
226     if $conf->exists('selfservice_server-primary_only')
227        && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
228
229   my $session_id;
230   do {
231     $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
232   } until ( ! defined _cache->get($session_id) ); #just in case
233
234   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
235   _cache->set( $session_id, $session, $timeout );
236
237   return { 'error'      => '',
238            'session_id' => $session_id,
239          };
240 }
241
242 sub logout {
243   my $p = shift;
244   if ( $p->{'session_id'} ) {
245     _cache->remove($p->{'session_id'});
246     return { %{ skin_info($p) }, 'error' => '' };
247   } else {
248     return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
249   }
250 }
251
252 sub payment_gateway {
253   # internal use only
254   # takes a cust_main and a cust_payby entry, returns the payment_gateway
255   my $conf = new FS::Conf;
256   my $cust_main = shift;
257   my $cust_payby = shift;
258   my $gatewaynum = $conf->config('selfservice-payment_gateway');
259   if ( $gatewaynum ) {
260     my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
261     die "configured gatewaynum $gatewaynum not found!" if !$pg;
262     return $pg;
263   }
264   else {
265     return '' if ! FS::payby->realtime($cust_payby);
266     my $pg = $cust_main->agent->payment_gateway(
267       'method'  => FS::payby->payby2bop($cust_payby),
268       'nofatal' => 1
269     );
270     return $pg;
271   }
272 }
273
274 sub access_info {
275   my $p = shift;
276
277   my $conf = new FS::Conf;
278
279   my $info = skin_info($p);
280
281   use vars qw( $cust_paybys ); #cache for performance
282   unless ( $cust_paybys ) {
283
284     my %cust_paybys = map { $_ => 1 }
285                       map { FS::payby->payby2payment($_) }
286                           $conf->config('signup_server-payby');
287
288     $cust_paybys = [ keys %cust_paybys ];
289
290   }
291   $info->{'cust_paybys'} = $cust_paybys;
292
293   my($context, $session, $custnum) = _custoragent_session_custnum($p);
294   return { 'error' => $session } if $context eq 'error';
295
296   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
297     or return { 'error' => "unknown custnum $custnum" };
298
299   $info->{'hide_payment_fields'} = [ 
300     map { 
301       my $pg = payment_gateway($cust_main, $_);
302       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
303     } @{ $info->{cust_paybys} }
304   ];
305
306   $info->{'self_suspend_reason'} = 
307       $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
308
309   $info->{'edit_ticket_subject'} =
310       $conf->exists('ticket_system-selfservice_edit_subject') && 
311       $cust_main->edit_subject;
312
313   return { %$info,
314            'custnum'       => $custnum,
315            'access_pkgnum' => $session->{'pkgnum'},
316            'access_svcnum' => $session->{'svcnum'},
317          };
318 }
319
320 sub customer_info {
321   my $p = shift;
322
323   my($context, $session, $custnum) = _custoragent_session_custnum($p);
324   return { 'error' => $session } if $context eq 'error';
325
326   my %return;
327
328   my $conf = new FS::Conf;
329   if ($conf->exists('cust_main-require_address2')) {
330     $return{'require_address2'} = '1';
331   }else{
332     $return{'require_address2'} = '';
333   }
334
335   if ( $FS::TicketSystem::system ) {
336     warn "$me customer_info: initializing ticket system\n" if $DEBUG;
337     FS::TicketSystem->init();
338   }
339  
340   if ( $custnum ) { #customer record
341
342     my $search = { 'custnum' => $custnum };
343     $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
344     my $cust_main = qsearchs('cust_main', $search )
345       or return { 'error' => "unknown custnum $custnum" };
346
347     if ( $session->{'pkgnum'} ) { 
348       $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
349     } else {
350       $return{balance} = $cust_main->balance;
351     }
352
353     my @tickets = $cust_main->tickets;
354     # unavoidable false laziness w/ httemplate/view/cust_main/tickets.html
355     if ( FS::TicketSystem->selfservice_priority ) {
356       my $dir = $conf->exists('ticket_system-priority_reverse') ? -1 : 1;
357       $return{tickets} = [ 
358         sort { 
359           (
360             ($a->{'_selfservice_priority'} eq '') <=>
361             ($b->{'_selfservice_priority'} eq '')
362           ) ||
363           ( $dir * 
364             ($b->{'_selfservice_priority'} <=> $a->{'_selfservice_priority'}) 
365           )
366         } @tickets
367       ];
368     }
369     else {
370       $return{tickets} = \@tickets;
371     }
372
373     unless ( $session->{'pkgnum'} ) {
374       my @open = map {
375                        {
376                          invnum => $_->invnum,
377                          date   => time2str("%b %o, %Y", $_->_date),
378                          owed   => $_->owed,
379                        };
380                      } $cust_main->open_cust_bill;
381       $return{open_invoices} = \@open;
382     }
383
384     $return{small_custview} =
385       small_custview( $cust_main,
386                       scalar($conf->config('countrydefault')),
387                       ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
388                     );
389
390     $return{name} = $cust_main->first. ' '. $cust_main->get('last');
391     $return{ship_name} = $cust_main->ship_first. ' '. $cust_main->get('ship_last');
392
393     for (@cust_main_editable_fields) {
394       $return{$_} = $cust_main->get($_);
395     }
396
397     if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
398       $return{payinfo} = $cust_main->paymask;
399       @return{'month', 'year'} = $cust_main->paydate_monthyear;
400     }
401
402     $return{'invoicing_list'} =
403       join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
404     $return{'postal_invoicing'} =
405       0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
406
407     if (scalar($conf->config('support_packages'))) {
408       my @support_services = ();
409       foreach ($cust_main->support_services) {
410         my $seconds = $_->svc_x->seconds;
411         my $time_remaining = (($seconds < 0) ? '-' : '' ).
412                              int(abs($seconds)/3600)."h".
413                              sprintf("%02d",(abs($seconds)%3600)/60)."m";
414         my $cust_pkg = $_->cust_pkg;
415         my $pkgnum = '';
416         my $pkg = '';
417         $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
418         $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
419         push @support_services, { svcnum => $_->svcnum,
420                                   time => $time_remaining,
421                                   pkgnum => $pkgnum,
422                                   pkg => $pkg,
423                                 };
424       }
425       $return{support_services} = \@support_services;
426     }
427
428     if ( $conf->config('prepayment_discounts-credit_type') ) {
429       #need to eval?
430       $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
431     }
432
433     if ( $session->{'svcnum'} ) {
434       my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
435       $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
436     }
437
438   } elsif ( $session->{'svcnum'} ) { #no customer record
439
440     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
441       or die "unknown svcnum";
442     $return{name} = $svc_acct->email;
443
444   } else {
445
446     return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
447
448   }
449
450   return { 'error'          => '',
451            'custnum'        => $custnum,
452            %return,
453          };
454
455 }
456
457 sub customer_info_short {
458   my $p = shift;
459
460   my($context, $session, $custnum) = _custoragent_session_custnum($p);
461   return { 'error' => $session } if $context eq 'error';
462
463   my %return;
464
465   my $conf = new FS::Conf;
466
467   if ( $custnum ) { #customer record
468
469     my $search = { 'custnum' => $custnum };
470     $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
471     my $cust_main = qsearchs('cust_main', $search )
472       or return { 'error' => "unknown custnum $custnum" };
473
474     $return{small_custview} =
475       small_custview( $cust_main,
476                       scalar($conf->config('countrydefault')),
477                       1, ##nobalance
478                     );
479
480     $return{name} = $cust_main->first. ' '. $cust_main->get('last');
481     $return{ship_name} = $cust_main->ship_first. ' '. $cust_main->get('ship_last');
482
483     $return{payby} = $cust_main->payby;
484
485     #none of these are terribly expensive if we want 'em...
486     for (@cust_main_editable_fields) {
487       $return{$_} = $cust_main->get($_);
488     }
489     
490     if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
491       $return{payinfo} = $cust_main->paymask;
492       @return{'month', 'year'} = $cust_main->paydate_monthyear;
493     }
494     
495     $return{'invoicing_list'} =
496       join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
497     #$return{'postal_invoicing'} =
498     #  0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
499
500     if ( $session->{'svcnum'} ) {
501       my $cust_svc = qsearchs('cust_svc', { 'svcnum' => $session->{'svcnum'} });
502       $return{'svc_label'} = ($cust_svc->label)[1] if $cust_svc;
503     }
504
505   } elsif ( $session->{'svcnum'} ) { #no customer record
506
507     #uuh, not supproted yet... die?
508     return { 'error' => 'customer_info_short not yet supported as agent' };
509
510   } else {
511
512     return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
513
514   }
515
516   return { 'error'          => '',
517            'custnum'        => $custnum,
518            %return,
519          };
520 }
521
522 sub edit_info {
523   my $p = shift;
524   my $session = _cache->get($p->{'session_id'})
525     or return { 'error' => "Can't resume session" }; #better error message
526
527   my $custnum = $session->{'custnum'}
528     or return { 'error' => "no customer record" };
529
530   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
531     or return { 'error' => "unknown custnum $custnum" };
532
533   my $new = new FS::cust_main { $cust_main->hash };
534   $new->set( $_ => $p->{$_} )
535     foreach grep { exists $p->{$_} } @cust_main_editable_fields;
536
537   my $payby = '';
538   if (exists($p->{'payby'})) {
539     $p->{'payby'} =~ /^([A-Z]{4})$/
540       or return { 'error' => "illegal_payby " . $p->{'payby'} };
541     $payby = $1;
542   }
543
544   if ( $payby =~ /^(CARD|DCRD)$/ ) {
545
546     $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
547
548     if ( $new->payinfo eq $cust_main->paymask ) {
549       $new->payinfo($cust_main->payinfo);
550     } else {
551       $new->payinfo($p->{'payinfo'});
552     }
553
554     $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
555
556   } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
557
558     my $payinfo;
559     $p->{'payinfo1'} =~ /^([\dx]+)$/
560       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
561     my $payinfo1 = $1;
562      $p->{'payinfo2'} =~ /^([\dx\.]+)$/ # . turned on by -require-bank-branch?
563       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
564     my $payinfo2 = $1;
565     $payinfo = $payinfo1. '@'. $payinfo2;
566
567     $new->payinfo( ($payinfo eq $cust_main->paymask)
568                      ? $cust_main->payinfo
569                      : $payinfo
570                  );
571
572     $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
573
574   } elsif ( $payby =~ /^(BILL)$/ ) {
575     #no-op
576   } elsif ( $payby ) {  #notyet ready
577     return { 'error' => "unknown payby $payby" };
578   }
579
580   my @invoicing_list;
581   if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
582     #false laziness with httemplate/edit/process/cust_main.cgi
583     @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
584     push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
585   } else {
586     @invoicing_list = $cust_main->invoicing_list;
587   }
588
589   my $error = $new->replace($cust_main, \@invoicing_list);
590   return { 'error' => $error } if $error;
591   #$cust_main = $new;
592   
593   return { 'error' => '' };
594 }
595
596 sub payment_info {
597   my $p = shift;
598   my $session = _cache->get($p->{'session_id'})
599     or return { 'error' => "Can't resume session" }; #better error message
600
601   ##
602   #generic
603   ##
604
605   my $conf = new FS::Conf;
606   use vars qw($payment_info); #cache for performance
607   unless ( $payment_info ) {
608
609     my %states = map { $_->state => 1 }
610                    qsearch('cust_main_county', {
611                      'country' => $conf->config('countrydefault') || 'US'
612                    } );
613
614     my %cust_paybys = map { $_ => 1 }
615                       map { FS::payby->payby2payment($_) }
616                           $conf->config('signup_server-payby');
617
618     my @cust_paybys = keys %cust_paybys;
619
620     $payment_info = {
621
622       #list all counties/states/countries
623       'cust_main_county' => 
624         [ map { $_->hashref } qsearch('cust_main_county', {}) ],
625
626       #shortcut for one-country folks
627       'states' =>
628         [ sort { $a cmp $b } keys %states ],
629
630       'card_types' => card_types(),
631
632       'paytypes' => [ @FS::cust_main::paytypes ],
633
634       'paybys' => [ $conf->config('signup_server-payby') ],
635       'cust_paybys' => \@cust_paybys,
636
637       'stateid_label' => FS::Msgcat::_gettext('stateid'),
638       'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
639
640       'show_ss'  => $conf->exists('show_ss'),
641       'show_stateid' => $conf->exists('show_stateid'),
642       'show_paystate' => $conf->exists('show_bankstate'),
643
644       'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
645
646       'credit_card_surcharge_percentage' => $conf->config('credit-card-surcharge-percentage'),
647     };
648
649   }
650
651   ##
652   #customer-specific
653   ##
654
655   my %return = %$payment_info;
656
657   my $custnum = $session->{'custnum'};
658
659   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
660     or return { 'error' => "unknown custnum $custnum" };
661
662   $return{'hide_payment_fields'} = [
663     map { 
664       my $pg = payment_gateway($cust_main, $_);
665       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
666     } @{ $return{cust_paybys} }
667   ];
668
669   $return{balance} = $cust_main->balance; #XXX pkg-balances?
670
671   $return{payname} = $cust_main->payname
672                      || ( $cust_main->first. ' '. $cust_main->get('last') );
673
674   $return{$_} = $cust_main->get($_) for qw(address1 address2 city state zip);
675
676   $return{payby} = $cust_main->payby;
677   $return{stateid_state} = $cust_main->stateid_state;
678
679   if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
680     $return{card_type} = cardtype($cust_main->payinfo);
681     $return{payinfo} = $cust_main->paymask;
682
683     @return{'month', 'year'} = $cust_main->paydate_monthyear;
684
685   }
686
687   if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
688     my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
689     $return{payinfo1} = $payinfo1;
690     $return{payinfo2} = $payinfo2;
691     $return{paytype}  = $cust_main->paytype;
692     $return{paystate} = $cust_main->paystate;
693
694   }
695
696   if ( $conf->config('prepayment_discounts-credit_type') ) {
697     #need to eval?
698     $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
699   }
700
701   #doubleclick protection
702   my $_date = time;
703   $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
704
705   return { 'error' => '',
706            %return,
707          };
708
709 }
710
711 #some false laziness with httemplate/process/payment.cgi - look there for
712 #ACH and CVV support stuff
713
714 sub validate_payment {
715   my $p = shift;
716
717   my $session = _cache->get($p->{'session_id'})
718     or return { 'error' => "Can't resume session" }; #better error message
719
720   my $custnum = $session->{'custnum'};
721
722   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
723     or return { 'error' => "unknown custnum $custnum" };
724
725   $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
726     or return { 'error' => gettext('illegal_amount') };
727   my $amount = $1;
728   return { error => 'Amount must be greater than 0' } unless $amount > 0;
729
730   $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
731     or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
732   my $discount_term = $1;
733
734   $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
735     or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
736   my $payname = $1;
737
738   $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
739     or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
740   my $paybatch = $1;
741
742   $p->{'payby'} ||= 'CARD';
743   $p->{'payby'} =~ /^([A-Z]{4})$/
744     or return { 'error' => "illegal_payby " . $p->{'payby'} };
745   my $payby = $1;
746
747   #false laziness w/process/payment.cgi
748   my $payinfo;
749   my $paycvv = '';
750   if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
751   
752     $p->{'payinfo1'} =~ /^([\dx]+)$/
753       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
754     my $payinfo1 = $1;
755      $p->{'payinfo2'} =~ /^([\dx]+)$/
756       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
757     my $payinfo2 = $1;
758     $payinfo = $payinfo1. '@'. $payinfo2;
759
760     $payinfo = $cust_main->payinfo
761       if $cust_main->paymask eq $payinfo;
762    
763   } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
764    
765     $payinfo = $p->{'payinfo'};
766
767     #more intelligent mathing will be needed here if you change
768     #card_masking_method and don't remove existing paymasks
769     $payinfo = $cust_main->payinfo
770       if $cust_main->paymask eq $payinfo;
771
772     $payinfo =~ s/\D//g;
773     $payinfo =~ /^(\d{13,16}|\d{8,9})$/
774       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
775     $payinfo = $1;
776
777     validate($payinfo)
778       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
779     return { 'error' => gettext('unknown_card_type') }
780       if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
781
782     if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
783       if ( cardtype($payinfo) eq 'American Express card' ) {
784         $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
785           or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
786         $paycvv = $1;
787       } else {
788         $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
789           or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
790         $paycvv = $1;
791       }
792     }
793   
794   } else {
795     die "unknown payby $payby";
796   }
797
798   my %payby2fields = (
799     'CARD' => [ qw( paystart_month paystart_year payissue payip
800                     address1 address2 city state zip country    ) ],
801     'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
802   );
803
804   my $card_type = '';
805   $card_type = cardtype($payinfo) if $payby eq 'CARD';
806
807   { 
808     'cust_main'      => $cust_main, #XXX or just custnum??
809     'amount'         => $amount,
810     'payby'          => $payby,
811     'payinfo'        => $payinfo,
812     'paymask'        => $cust_main->mask_payinfo( $payby, $payinfo ),
813     'card_type'      => $card_type,
814     'paydate'        => $p->{'year'}. '-'. $p->{'month'}. '-01',
815     'paydate_pretty' => $p->{'month'}. ' / '. $p->{'year'},
816     'payname'        => $payname,
817     'paybatch'       => $paybatch, #this doesn't actually do anything
818     'paycvv'         => $paycvv,
819     'payname'        => $payname,
820     'discount_term'  => $discount_term,
821     'pkgnum'         => $session->{'pkgnum'},
822     map { $_ => $p->{$_} } ( @{ $payby2fields{$payby} },
823                              qw( save auto ),
824                            )
825   };
826
827 }
828
829 sub store_payment {
830   my $p = shift;
831
832   my $validate = validate_payment($p);
833   return $validate if $validate->{'error'};
834
835   my $conf = new FS::Conf;
836   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour'; #?
837   _cache->set( 'payment_'.$p->{'session_id'}, $validate, $timeout );
838
839   +{ map { $_=>$validate->{$_} }
840       qw( card_type paymask payname paydate_pretty amount )
841   };
842
843 }
844
845 sub process_stored_payment {
846   my $p = shift;
847
848   my $session_id = $p->{'session_id'};
849
850   my $payment_info = _cache->get( "payment_$session_id" )
851     or return { 'error' => "Can't resume session" }; #better error message
852
853   do_process_payment($payment_info);
854
855 }
856
857 sub process_payment {
858   my $p = shift;
859
860   my $payment_info = validate_payment($p);
861   return $payment_info if $payment_info->{'error'};
862
863   do_process_payment($payment_info);
864
865 }
866
867 sub do_process_payment {
868   my $validate = shift;
869
870   my $cust_main = $validate->{'cust_main'};
871
872   my $amount = delete $validate->{'amount'};
873   my $paynum = '';
874
875   my $payby = delete $validate->{'payby'};
876
877   my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
878     'quiet'       => 1,
879     'selfservice' => 1,
880     'paynum_ref'  => \$paynum,
881     %$validate,
882   );
883   return { 'error' => $error } if $error;
884
885   $cust_main->apply_payments;
886
887   if ( $validate->{'save'} ) {
888     my $new = new FS::cust_main { $cust_main->hash };
889     if ($validate->{'payby'} eq 'CARD' || $validate->{'payby'} eq 'DCRD') {
890       $new->set( $_ => $validate->{$_} )
891         foreach qw( payname paystart_month paystart_year payissue payip
892                     address1 address2 city state zip country );
893       $new->set( 'payby' => $validate->{'auto'} ? 'CARD' : 'DCRD' );
894     } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
895       $new->set( $_ => $validate->{$_} )
896         foreach qw( payname payip paytype paystate
897                     stateid stateid_state );
898       $new->set( 'payby' => $validate->{'auto'} ? 'CHEK' : 'DCHK' );
899     }
900     $new->set( 'payinfo' => $cust_main->card_token || $validate->{'payinfo'} );
901     $new->set( 'paydate' => $validate->{'paydate'} );
902     my $error = $new->replace($cust_main);
903     if ( $error ) {
904       #no, this causes customers to process their payments again
905       #return { 'error' => $error };
906       #XXX just warn verosely for now so i can figure out how these happen in
907       # the first place, eventually should redirect them to the "change
908       #address" page but indicate the payment did process??
909       delete($validate->{'payinfo'}); #don't want to log this!
910       warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
911            "NEW: ". Dumper($new)."\n".
912            "OLD: ". Dumper($cust_main)."\n".
913            "PACKET: ". Dumper($validate)."\n";
914     #} else {
915       #not needed...
916       #$cust_main = $new;
917     }
918   }
919
920   my $cust_pay = '';
921   my $receipt_html = '';
922   if ($paynum) {
923       # currently supported for realtime CC only; send receipt data to SS
924       $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
925       if($cust_pay) {
926         $receipt_html = qq!
927 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
928
929 <TR>
930   <TD ALIGN="right">Payment#</TD>
931   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
932 </TR>
933
934 <TR>
935   <TD ALIGN="right">Date</TD>
936
937   <TD BGCOLOR="#FFFFFF"><B>! . 
938         time2str("%a&nbsp;%b&nbsp;%o,&nbsp;%Y&nbsp;%r", $cust_pay->_date)
939                                                             . qq!</B></TD>
940 </TR>
941
942
943 <TR>
944   <TD ALIGN="right">Amount</TD>
945   <TD BGCOLOR="#FFFFFF"><B>! . sprintf('%.2f', $cust_pay->paid) . qq!</B></TD>
946
947 </TR>
948
949 <TR>
950   <TD ALIGN="right">Payment method</TD>
951   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
952                                                                 . qq!</B></TD>
953 </TR>
954
955 </TABLE>
956 !;
957       }
958   }
959
960   if ( $cust_pay ) {
961
962     my($gw, $auth, $order) = split(':', $cust_pay->paybatch);
963
964     return {
965       'error'        => '',
966       'amount'       => sprintf('%.2f', $cust_pay->paid),
967       'date'         => $cust_pay->_date,
968       'date_pretty'  => time2str('%Y-%m-%d', $cust_pay->_date),
969       'time_pretty'  => time2str('%T', $cust_pay->_date),
970       'auth_num'     => $auth,
971       'order_num'    => $order,
972       'receipt_html' => $receipt_html,
973     };
974
975   } else {
976
977     return {
978       'error'        => '',
979       'receipt_html' => '',
980     };
981
982   }
983
984 }
985
986 sub realtime_collect {
987   my $p = shift;
988
989   my $session = _cache->get($p->{'session_id'})
990     or return { 'error' => "Can't resume session" }; #better error message
991
992   my $custnum = $session->{'custnum'};
993
994   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
995     or return { 'error' => "unknown custnum $custnum" };
996
997   my $amount;
998   if ( $p->{'amount'} ) {
999     $amount = $p->{'amount'};
1000   }
1001   elsif ( $session->{'pkgnum'} ) {
1002     $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
1003   }
1004   else {
1005     $amount = $cust_main->balance;
1006   }
1007
1008   my $error = $cust_main->realtime_collect(
1009     'method'     => $p->{'method'},
1010     'amount'     => $amount,
1011     'pkgnum'     => $session->{'pkgnum'},
1012     'session_id' => $p->{'session_id'},
1013     'apply'      => 1,
1014     'selfservice'=> 1,
1015   );
1016   return { 'error' => $error } unless ref( $error );
1017
1018   return { 'error' => '', amount => $amount, %$error };
1019 }
1020
1021 sub process_payment_order_pkg {
1022   my $p = shift;
1023
1024   my $hr = process_payment($p);
1025   return $hr if $hr->{'error'};
1026
1027   order_pkg($p);
1028 }
1029
1030 sub process_payment_order_renew {
1031   my $p = shift;
1032
1033   my $hr = process_payment($p);
1034   return $hr if $hr->{'error'};
1035
1036   order_renew($p);
1037 }
1038
1039 sub process_prepay {
1040
1041   my $p = shift;
1042
1043   my $session = _cache->get($p->{'session_id'})
1044     or return { 'error' => "Can't resume session" }; #better error message
1045
1046   my %return;
1047
1048   my $custnum = $session->{'custnum'};
1049
1050   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1051     or return { 'error' => "unknown custnum $custnum" };
1052
1053   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
1054   my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
1055                                            \$amount,
1056                                            \$seconds,
1057                                            \$upbytes,
1058                                            \$downbytes,
1059                                            \$totalbytes,
1060                                          );
1061
1062   return { 'error' => $error } if $error;
1063
1064   return { 'error'     => '',
1065            'amount'    => $amount,
1066            'seconds'   => $seconds,
1067            'duration'  => duration_exact($seconds),
1068            'upbytes'   => $upbytes,
1069            'upload'    => FS::UI::bytecount::bytecount_unexact($upbytes),
1070            'downbytes' => $downbytes,
1071            'download'  => FS::UI::bytecount::bytecount_unexact($downbytes),
1072            'totalbytes'=> $totalbytes,
1073            'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
1074          };
1075
1076 }
1077
1078 sub invoice {
1079   my $p = shift;
1080   my $session = _cache->get($p->{'session_id'})
1081     or return { 'error' => "Can't resume session" }; #better error message
1082
1083   my $custnum = $session->{'custnum'};
1084
1085   my $invnum = $p->{'invnum'};
1086
1087   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1088                                           'custnum' => $custnum } )
1089     or return { 'error' => "Can't find invnum" };
1090
1091   #my %return;
1092
1093   return { 'error'        => '',
1094            'invnum'       => $invnum,
1095            'invoice_text' => join('', $cust_bill->print_text ),
1096            'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
1097          };
1098
1099 }
1100
1101 sub invoice_pdf {
1102   my $p = shift;
1103   my $session = _cache->get($p->{'session_id'})
1104     or return { 'error' => "Can't resume session" }; #better error message
1105
1106   my $custnum = $session->{'custnum'};
1107
1108   my $invnum = $p->{'invnum'};
1109
1110   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
1111                                           'custnum' => $custnum } )
1112     or return { 'error' => "Can't find invnum" };
1113
1114   #my %return;
1115
1116   return { 'error'       => '',
1117            'invnum'      => $invnum,
1118            'invoice_pdf' => $cust_bill->print_pdf( { unsquelch_cdr => 1 } ),
1119          };
1120
1121 }
1122
1123 sub invoice_logo {
1124   my $p = shift;
1125
1126   #sessioning for this?  how do we get the session id to the backend invoice
1127   # template so it can add it to the link, blah
1128
1129   my $agentnum = '';
1130   if ( $p->{'invnum'} ) {
1131     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
1132       or return { 'error' => 'unknown invnum' };
1133     $agentnum = $cust_bill->cust_main->agentnum;
1134   }
1135
1136   my $templatename = $p->{'template'} || $p->{'templatename'};
1137
1138   #false laziness-ish w/view/cust_bill-logo.cgi
1139
1140   my $conf = new FS::Conf;
1141   if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
1142     $templatename = "_$1";
1143   } else {
1144     $templatename = '';
1145   }
1146
1147   my $filename = "logo$templatename.png";
1148
1149   return { 'error'        => '',
1150            'logo'         => $conf->config_binary($filename, $agentnum),
1151            'content_type' => 'image/png', #should allow gif, jpg too
1152          };
1153 }
1154
1155
1156 sub list_invoices {
1157   my $p = shift;
1158   my $session = _cache->get($p->{'session_id'})
1159     or return { 'error' => "Can't resume session" }; #better error message
1160
1161   my $custnum = $session->{'custnum'};
1162
1163   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1164     or return { 'error' => "unknown custnum $custnum" };
1165
1166   my @cust_bill = $cust_main->cust_bill;
1167
1168   my $balance = 0;
1169
1170   return  { 'error'       => '',
1171             'balance'     => $cust_main->balance,
1172             'invoices'    => [
1173               map {
1174                     my $owed = $_->owed;
1175                     $balance += $owed;
1176                     +{ 'invnum'     => $_->invnum,
1177                        '_date'      => $_->_date,
1178                        'date'       => time2str("%b %o, %Y", $_->_date),
1179                        'date_short' => time2str("%m-%d-%Y",  $_->_date),
1180                        'previous'   => sprintf('%.2f', ($_->previous)[0]),
1181                        'charged'    => sprintf('%.2f', $_->charged),
1182                        'owed'       => sprintf('%.2f', $owed),
1183                        'balance'    => sprintf('%.2f', $balance),
1184                      }
1185                   }
1186                   @cust_bill
1187             ]
1188           };
1189 }
1190
1191 sub cancel {
1192   my $p = shift;
1193   my $session = _cache->get($p->{'session_id'})
1194     or return { 'error' => "Can't resume session" }; #better error message
1195
1196   my $custnum = $session->{'custnum'};
1197
1198   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1199     or return { 'error' => "unknown custnum $custnum" };
1200
1201   my @errors = $cust_main->cancel( 'quiet'=>1 );
1202
1203   my $error = scalar(@errors) ? join(' / ', @errors) : '';
1204
1205   return { 'error' => $error };
1206
1207 }
1208
1209 sub list_pkgs {
1210   my $p = shift;
1211
1212   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1213   return { 'error' => $session } if $context eq 'error';
1214
1215   my $search = { 'custnum' => $custnum };
1216   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1217   my $cust_main = qsearchs('cust_main', $search )
1218     or return { 'error' => "unknown custnum $custnum" };
1219
1220   my $conf = new FS::Conf;
1221   
1222 # the duplication below is necessary:
1223 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1224 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1225 # non-backwards-compatible change breaking the software of anyone using the API
1226 # instead of the stock selfservice
1227 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1228   if( $conf->exists('selfservice_server-view-wholesale') ) {
1229     return { 'svcnum'   => $session->{'svcnum'},
1230             'custnum'  => $custnum,
1231             'cust_pkg' => [ map {
1232                           { $_->hash,
1233                             part_pkg => [ map $_->hashref, $_->part_pkg ],
1234                             part_svc =>
1235                               [ map $_->hashref, $_->available_part_svc ],
1236                             cust_svc => 
1237                               [ map { my $ref = { $_->hash,
1238                                                   label => [ $_->label ],
1239                                                 };
1240                                       $ref->{_password} = $_->svc_x->_password
1241                                         if $context eq 'agent'
1242                                         && $conf->exists('agent-showpasswords')
1243                                         && $_->part_svc->svcdb eq 'svc_acct';
1244                                       $ref;
1245                                     } $_->cust_svc
1246                               ],
1247                           };
1248                         } $cust_main->cust_pkg
1249                   ],
1250     'small_custview' =>
1251       small_custview( $cust_main, $conf->config('countrydefault') ),
1252     'wholesale_view' => 1,
1253     'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1254     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1255     'lnp' => $conf->exists('svc_phone-lnp'),
1256       };
1257   }
1258
1259   { 'svcnum'   => $session->{'svcnum'},
1260     'custnum'  => $custnum,
1261     'cust_pkg' => [ map {
1262                           my $primary_cust_svc = $_->primary_cust_svc;
1263                           +{ $_->hash,
1264                             $_->part_pkg->hash,
1265                             status => $_->status,
1266                             part_svc =>
1267                               [ map $_->hashref, $_->available_part_svc ],
1268                             cust_svc => 
1269                               [ map { my $ref = { $_->hash,
1270                                                   label => [ $_->label ],
1271                                                 };
1272                                       $ref->{_password} = $_->svc_x->_password
1273                                         if $context eq 'agent'
1274                                         && $conf->exists('agent-showpasswords')
1275                                         && $_->part_svc->svcdb eq 'svc_acct';
1276                                       $ref->{svchash} = { $_->svc_x->hash } if 
1277                                         $_->part_svc->svcdb eq 'svc_phone';
1278                                       $ref->{svchash}->{svcpart} =  $_->part_svc->svcpart
1279                                         if $_->part_svc->svcdb eq 'svc_phone'; # hack
1280                                       $ref;
1281                                     } $_->cust_svc
1282                               ],
1283                             primary_cust_svc =>
1284                               $primary_cust_svc
1285                                 ? { $primary_cust_svc->hash,
1286                                     label => [ $primary_cust_svc->label ],
1287                                     finger => $primary_cust_svc->svc_x->finger, #uuh
1288                                     $primary_cust_svc->part_svc->hash,
1289                                   }
1290                                 : {}, #'' ?
1291                           };
1292                         } $cust_main->ncancelled_pkgs
1293                   ],
1294     'small_custview' =>
1295       small_custview( $cust_main, $conf->config('countrydefault') ),
1296   };
1297
1298 }
1299
1300 sub list_svcs {
1301   my $p = shift;
1302
1303   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1304   return { 'error' => $session } if $context eq 'error';
1305
1306   my $search = { 'custnum' => $custnum };
1307   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1308   my $cust_main = qsearchs('cust_main', $search )
1309     or return { 'error' => "unknown custnum $custnum" };
1310
1311   my @cust_svc = ();
1312   #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1313   foreach my $cust_pkg ( $p->{'ncancelled'} 
1314                          ? $cust_main->ncancelled_pkgs
1315                          : $cust_main->unsuspended_pkgs ) {
1316     next if $session->{'pkgnum'} && $cust_pkg->pkgnum != $session->{'pkgnum'};
1317     push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1318   }
1319   if ( $p->{'svcdb'} ) {
1320     my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1321                   ? $p->{'svcdb'}
1322                   : ref($p->{'svcdb'}) eq 'ARRAY'
1323                     ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1324                     : { $p->{'svcdb'} => 1 };
1325     @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1326   }
1327
1328   #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1329   #              @svc_x;
1330
1331     my $conf = new FS::Conf;
1332
1333   { 
1334     'svcnum'   => $session->{'svcnum'},
1335     'custnum'  => $custnum,
1336     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1337     'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1338     'svcs'     => [
1339       map { 
1340             my $svc_x = $_->svc_x;
1341             my($label, $value) = $_->label;
1342             my $svcdb = $_->part_svc->svcdb;
1343             my $part_pkg = $_->cust_pkg->part_pkg;
1344
1345             my %hash = (
1346               'svcnum' => $_->svcnum,
1347               'svcdb'  => $svcdb,
1348               'label'  => $label,
1349               'value'  => $value,
1350             );
1351
1352             if ( $svcdb eq 'svc_acct' ) {
1353               %hash = (
1354                 %hash,
1355                 'username'   => $svc_x->username,
1356                 'email'      => $svc_x->email,
1357                 'seconds'    => $svc_x->seconds,
1358                 'upbytes'    => display_bytecount($svc_x->upbytes),
1359                 'downbytes'  => display_bytecount($svc_x->downbytes),
1360                 'totalbytes' => display_bytecount($svc_x->totalbytes),
1361
1362                 'recharge_amount'  => $part_pkg->option('recharge_amount',1),
1363                 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1364                 'recharge_upbytes'    =>
1365                   display_bytecount($part_pkg->option('recharge_upbytes',1)),
1366                 'recharge_downbytes'  =>
1367                   display_bytecount($part_pkg->option('recharge_downbytes',1)),
1368                 'recharge_totalbytes' =>
1369                   display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1370                 # more...
1371               );
1372
1373             } elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1374               %hash = (
1375                 %hash,
1376               );
1377             }
1378
1379             \%hash;
1380           }
1381           @cust_svc
1382     ],
1383   };
1384
1385 }
1386
1387 sub port_graph {
1388   my $p = shift;
1389   _usage_details( \&_port_graph, $p,
1390                   'svcdb' => 'svc_port',
1391                 );
1392 }
1393
1394 sub _port_graph {
1395   my($svc_port, $begin, $end) = @_;
1396   my @usage = ();
1397   my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
1398   push @usage, { 'png' => $pngOrError };
1399   (@usage);
1400 }
1401
1402 sub _list_svc_usage {
1403   my($svc_acct, $begin, $end) = @_;
1404   my @usage = ();
1405   foreach my $part_export ( 
1406     map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1407     qw( sqlradius sqlradius_withdomain )
1408   ) {
1409     push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1410   }
1411   (@usage);
1412 }
1413
1414 sub list_svc_usage {
1415   _usage_details(\&_list_svc_usage, @_);
1416 }
1417
1418 sub _list_support_usage {
1419   my($svc_acct, $begin, $end) = @_;
1420   my @usage = ();
1421   foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1422             qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1423           ) {
1424     push @usage, { 'seconds'  => $_->seconds,
1425                    'support'  => $_->support,
1426                    '_date'    => $_->_date,
1427                    'id'       => $_->transaction_id,
1428                    'creator'  => $_->creator,
1429                    'subject'  => $_->subject,
1430                    'status'   => $_->status,
1431                    'ticketid' => $_->ticketid,
1432                  };
1433   }
1434   (@usage);
1435 }
1436
1437 sub list_support_usage {
1438   _usage_details(\&_list_support_usage, @_);
1439 }
1440
1441 sub _list_cdr_usage {
1442   my($svc_phone, $begin, $end) = @_;
1443   map [ $_->downstream_csv('format' => 'default', 'keeparray' => 1) ], #XXX config for format
1444                        $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1445 }
1446
1447 sub list_cdr_usage {
1448   my $p = shift;
1449   _usage_details( \&_list_cdr_usage, $p,
1450                   'svcdb' => 'svc_phone',
1451                 );
1452 }
1453
1454 sub _usage_details {
1455   my($callback, $p, %opt) = @_;
1456
1457   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1458   return { 'error' => $session } if $context eq 'error';
1459
1460   my $search = { 'svcnum' => $p->{'svcnum'} };
1461   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1462
1463   my $svcdb = $opt{'svcdb'} || 'svc_acct';
1464
1465   my $svc_x = qsearchs( $svcdb, $search );
1466   return { 'error' => 'No service selected in list_svc_usage' } 
1467     unless $svc_x;
1468
1469   my $header = $svcdb eq 'svc_phone'
1470                  ? [ split(',', FS::cdr::invoice_header('default') ) ]  #XXX
1471                  : [];
1472
1473   my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1474   my $freq     = $cust_pkg->part_pkg->freq;
1475   my $start    = $cust_pkg->setup;
1476   #my $end      = $cust_pkg->bill; # or time?
1477   my $end      = time;
1478
1479   unless ( $p->{beginning} ) {
1480     $p->{beginning} = $cust_pkg->last_bill;
1481     $p->{ending}    = $end;
1482   }
1483
1484   my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending});
1485
1486   #kinda false laziness with FS::cust_main::bill, but perhaps
1487   #we should really change this bit to DateTime and DateTime::Duration
1488   #
1489   #change this bit to use Date::Manip? CAREFUL with timezones (see
1490   # mailing list archive)
1491   my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
1492     (localtime($p->{ending}) )[0,1,2,3,4,5];
1493   my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
1494     (localtime($p->{beginning}) )[0,1,2,3,4,5];
1495
1496   if ( $freq =~ /^\d+$/ ) {
1497     $nmon += $freq;
1498     until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
1499     $pmon -= $freq;
1500     until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
1501   } elsif ( $freq =~ /^(\d+)w$/ ) {
1502     my $weeks = $1;
1503     $nmday += $weeks * 7;
1504     $pmday -= $weeks * 7;
1505   } elsif ( $freq =~ /^(\d+)d$/ ) {
1506     my $days = $1;
1507     $nmday += $days;
1508     $pmday -= $days;
1509   } elsif ( $freq =~ /^(\d+)h$/ ) {
1510     my $hours = $1;
1511     $nhour += $hours;
1512     $phour -= $hours;
1513   } else {
1514     return { 'error' => "unparsable frequency: ". $freq };
1515   }
1516   
1517   my $previous  = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
1518   my $next      = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
1519
1520   { 
1521     'error'     => '',
1522     'svcnum'    => $p->{svcnum},
1523     'beginning' => $p->{beginning},
1524     'ending'    => $p->{ending},
1525     'previous'  => ($previous > $start) ? $previous : $start,
1526     'next'      => ($next < $end) ? $next : $end,
1527     'header'    => $header,
1528     'usage'     => \@usage,
1529   };
1530 }
1531
1532 sub order_pkg {
1533   my $p = shift;
1534
1535   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1536   return { 'error' => $session } if $context eq 'error';
1537
1538   my $search = { 'custnum' => $custnum };
1539   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1540   my $cust_main = qsearchs('cust_main', $search )
1541     or return { 'error' => "unknown custnum $custnum" };
1542
1543   my $status = $cust_main->status;
1544   #false laziness w/ClientAPI/Signup.pm
1545
1546   my $cust_pkg = new FS::cust_pkg ( {
1547     'custnum' => $custnum,
1548     'pkgpart' => $p->{'pkgpart'},
1549   } );
1550   my $error = $cust_pkg->check;
1551   return { 'error' => $error } if $error;
1552
1553   my @svc = ();
1554   unless ( $p->{'svcpart'} eq 'none' ) {
1555
1556     my $svcdb;
1557     my $svcpart = '';
1558     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
1559       $svcpart = $1;
1560       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
1561       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
1562       $svcdb = $part_svc->svcdb;
1563     } else {
1564       $svcdb = 'svc_acct';
1565     }
1566     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
1567
1568     my %fields = (
1569       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
1570       'svc_domain'   => [ qw( domain ) ],
1571       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
1572       'svc_external' => [ qw( id title ) ],
1573       'svc_pbx'      => [ qw( id title ) ],
1574     );
1575   
1576     my $svc_x = "FS::$svcdb"->new( {
1577       'svcpart'   => $svcpart,
1578       map { $_ => $p->{$_} } @{$fields{$svcdb}}
1579     } );
1580     
1581     if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
1582       my @acct_snarf;
1583       my $snarfnum = 1;
1584       while ( length($p->{"snarf_machine$snarfnum"}) ) {
1585         my $acct_snarf = new FS::acct_snarf ( {
1586           'machine'   => $p->{"snarf_machine$snarfnum"},
1587           'protocol'  => $p->{"snarf_protocol$snarfnum"},
1588           'username'  => $p->{"snarf_username$snarfnum"},
1589           '_password' => $p->{"snarf_password$snarfnum"},
1590         } );
1591         $snarfnum++;
1592         push @acct_snarf, $acct_snarf;
1593       }
1594       $svc_x->child_objects( \@acct_snarf );
1595     }
1596     
1597     my $y = $svc_x->setdefault; # arguably should be in new method
1598     return { 'error' => $y } if $y && !ref($y);
1599   
1600     $error = $svc_x->check;
1601     return { 'error' => $error } if $error;
1602
1603     push @svc, $svc_x;
1604
1605   }
1606
1607   use Tie::RefHash;
1608   tie my %hash, 'Tie::RefHash';
1609   %hash = ( $cust_pkg => \@svc );
1610   #msgcat
1611   $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
1612   return { 'error' => $error } if $error;
1613
1614   my $conf = new FS::Conf;
1615   if ( $conf->exists('signup_server-realtime') ) {
1616
1617     my $bill_error = _do_bop_realtime( $cust_main, $status );
1618
1619     if ($bill_error) {
1620       $cust_pkg->cancel('quiet'=>1);
1621       return $bill_error;
1622     } else {
1623       $cust_pkg->reexport;
1624     }
1625
1626   } else {
1627     $cust_pkg->reexport;
1628   }
1629
1630   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
1631
1632   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
1633
1634 }
1635
1636 sub change_pkg {
1637   my $p = shift;
1638
1639   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1640   return { 'error' => $session } if $context eq 'error';
1641
1642   my $search = { 'custnum' => $custnum };
1643   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1644   my $cust_main = qsearchs('cust_main', $search )
1645     or return { 'error' => "unknown custnum $custnum" };
1646
1647   my $status = $cust_main->status;
1648   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
1649     or return { 'error' => "unknown package $p->{pkgnum}" };
1650
1651   my @newpkg;
1652   my $error = FS::cust_pkg::order( $custnum,
1653                                    [$p->{pkgpart}],
1654                                    [$p->{pkgnum}],
1655                                    \@newpkg,
1656                                  );
1657
1658   my $conf = new FS::Conf;
1659   if ( $conf->exists('signup_server-realtime') ) {
1660
1661     my $bill_error = _do_bop_realtime( $cust_main, $status );
1662
1663     if ($bill_error) {
1664       $newpkg[0]->suspend;
1665       return $bill_error;
1666     } else {
1667       $newpkg[0]->reexport;
1668     }
1669
1670   } else {  
1671     $newpkg[0]->reexport;
1672   }
1673
1674   return { error => '', pkgnum => $cust_pkg->pkgnum };
1675
1676 }
1677
1678 sub order_recharge {
1679   my $p = shift;
1680
1681   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1682   return { 'error' => $session } if $context eq 'error';
1683
1684   my $search = { 'custnum' => $custnum };
1685   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1686   my $cust_main = qsearchs('cust_main', $search )
1687     or return { 'error' => "unknown custnum $custnum" };
1688
1689   my $status = $cust_main->status;
1690   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
1691     or return { 'error' => "unknown service " . $p->{'svcnum'} };
1692
1693   my $svc_x = $cust_svc->svc_x;
1694   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
1695
1696   my %vhash =
1697     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
1698     qw ( recharge_seconds recharge_upbytes recharge_downbytes
1699          recharge_totalbytes );
1700   my $amount = $part_pkg->option('recharge_amount', 1); 
1701   
1702   my ($l, $v, $d) = $cust_svc->label;  # blah
1703   my $pkg = "Recharge $v"; 
1704
1705   my $bill_error = $cust_main->charge($amount, $pkg,
1706      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
1707      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
1708      $part_pkg->taxclass); #meh
1709
1710   my $conf = new FS::Conf;
1711   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
1712
1713     $bill_error = _do_bop_realtime( $cust_main, $status );
1714
1715     if ($bill_error) {
1716       return $bill_error;
1717     } else {
1718       my $error = $svc_x->recharge (\%vhash);
1719       return { 'error' => $error } if $error;
1720     }
1721
1722   } else {  
1723     my $error = $bill_error;
1724     $error ||= $svc_x->recharge (\%vhash);
1725     return { 'error' => $error } if $error;
1726   }
1727
1728   return { error => '', svc => $cust_svc->part_svc->svc };
1729
1730 }
1731
1732 sub _do_bop_realtime {
1733   my ($cust_main, $status) = (shift, shift);
1734
1735     my $old_balance = $cust_main->balance;
1736
1737     my $bill_error =    $cust_main->bill
1738                      || $cust_main->apply_payments_and_credits
1739                      || $cust_main->realtime_collect('selfservice' => 1);
1740
1741     if (    $cust_main->balance > $old_balance
1742          && $cust_main->balance > 0
1743          && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
1744               1 : $status eq 'suspended' ) ) {
1745       #this makes sense.  credit is "un-doing" the invoice
1746       my $conf = new FS::Conf;
1747       $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
1748                           'self-service decline',
1749                           'reason_type' => $conf->config('signup_credit_type'),
1750                         );
1751       $cust_main->apply_credits( 'order' => 'newest' );
1752
1753       return { 'error' => '_decline', 'bill_error' => $bill_error };
1754     }
1755
1756     '';
1757 }
1758
1759 sub renew_info {
1760   my $p = shift;
1761
1762   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1763   return { 'error' => $session } if $context eq 'error';
1764
1765   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1766     or return { 'error' => "unknown custnum $custnum" };
1767
1768   my @cust_pkg = sort { $a->bill <=> $b->bill }
1769                  grep { $_->part_pkg->freq ne '0' }
1770                  $cust_main->ncancelled_pkgs;
1771
1772   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
1773
1774   my $total = $cust_main->balance;
1775
1776   my @array = map {
1777                     my $bill = $_->bill;
1778                     $total += $_->part_pkg->base_recur($_, \$bill);
1779                     my $renew_date = $_->part_pkg->add_freq($_->bill);
1780                     {
1781                       'pkgnum'             => $_->pkgnum,
1782                       'amount'             => sprintf('%.2f', $total),
1783                       'bill_date'          => $_->bill,
1784                       'bill_date_pretty'   => time2str('%x', $_->bill),
1785                       'renew_date'         => $renew_date,
1786                       'renew_date_pretty'  => time2str('%x', $renew_date),
1787                       'expire_date'        => $_->expire,
1788                       'expire_date_pretty' => time2str('%x', $_->expire),
1789                     };
1790                   }
1791                   @cust_pkg;
1792
1793   return { 'dates' => \@array };
1794
1795 }
1796
1797 sub payment_info_renew_info {
1798   my $p = shift;
1799   my $renew_info   = renew_info($p);
1800   my $payment_info = payment_info($p);
1801   return { %$renew_info,
1802            %$payment_info,
1803          };
1804 }
1805
1806 sub order_renew {
1807   my $p = shift;
1808
1809   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1810   return { 'error' => $session } if $context eq 'error';
1811
1812   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1813     or return { 'error' => "unknown custnum $custnum" };
1814
1815   my $date = $p->{'date'};
1816
1817   my $now = time;
1818
1819   #freeside-daily -n -d $date fs_daily $custnum
1820   $cust_main->bill_and_collect( 'time'         => $date,
1821                                 'invoice_time' => $now,
1822                                 'actual_time'  => $now,
1823                                 'check_freq'   => '1d',
1824                               );
1825
1826   return { 'error' => '' };
1827
1828 }
1829
1830 sub suspend_pkg {
1831   my $p = shift;
1832   my $session = _cache->get($p->{'session_id'})
1833     or return { 'error' => "Can't resume session" }; #better error message
1834
1835   my $custnum = $session->{'custnum'};
1836
1837   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1838     or return { 'error' => "unknown custnum $custnum" };
1839
1840   my $conf = new FS::Conf;
1841   my $reasonnum = 
1842     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
1843       or return { 'error' => 'Permission denied' };
1844
1845   my $pkgnum = $p->{'pkgnum'};
1846
1847   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1848                                         'pkgnum'  => $pkgnum,   } )
1849     or return { 'error' => "unknown pkgnum $pkgnum" };
1850
1851   my $error = $cust_pkg->suspend(reason => $reasonnum);
1852   return { 'error' => $error };
1853
1854 }
1855
1856 sub cancel_pkg {
1857   my $p = shift;
1858   my $session = _cache->get($p->{'session_id'})
1859     or return { 'error' => "Can't resume session" }; #better error message
1860
1861   my $custnum = $session->{'custnum'};
1862
1863   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1864     or return { 'error' => "unknown custnum $custnum" };
1865
1866   my $pkgnum = $p->{'pkgnum'};
1867
1868   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1869                                         'pkgnum'  => $pkgnum,   } )
1870     or return { 'error' => "unknown pkgnum $pkgnum" };
1871
1872   my $error = $cust_pkg->cancel('quiet' => 1);
1873   return { 'error' => $error };
1874
1875 }
1876
1877 sub provision_phone {
1878  my $p = shift;
1879  my @bulkdid;
1880  @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
1881
1882  if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
1883       my($context, $session, $custnum) = _custoragent_session_custnum($p);
1884       return { 'error' => $session } if $context eq 'error';
1885     
1886       my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
1887       return { 'error' => 'service not found' } unless $svc_phone;
1888       return { 'error' => 'invalid svcnum' } 
1889         if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
1890
1891       $svc_phone->email($p->{'email'}) 
1892         if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
1893       $svc_phone->forwarddst($p->{'forwarddst'}) 
1894         if $svc_phone->forwarddst ne $p->{'forwarddst'} 
1895             && $p->{'forwarddst'} =~ /^(\d+|)$/;
1896       return { 'error' => $svc_phone->replace };
1897  }
1898
1899 # single DID LNP
1900  unless($p->{'lnp'}) {
1901     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
1902     $p->{'lnp_status'} = "portingin";
1903     return _provision( 'FS::svc_phone',
1904                   [qw(lnp_desired_due_date lnp_other_provider 
1905                     lnp_other_provider_account phonenum countrycode lnp_status)],
1906                   [qw(phonenum countrycode)],
1907                   $p,
1908                   @_
1909                 );
1910  }
1911
1912 # single DID order
1913  unless (scalar(@bulkdid)) {
1914     return _provision( 'FS::svc_phone',
1915                   [qw(phonenum countrycode)],
1916                   [qw(phonenum countrycode)],
1917                   $p,
1918                   @_
1919                 );
1920  }
1921
1922 # bulk DID order case
1923   my $error;
1924   foreach my $did ( @bulkdid ) {
1925     $did =~ s/[^0-9]//g;
1926     $error = _provision( 'FS::svc_phone',
1927               [qw(phonenum countrycode)],
1928               [qw(phonenum countrycode)],
1929               {
1930                 'pkgnum' => $p->{'pkgnum'},
1931                 'svcpart' => $p->{'svcpart'},
1932                 'phonenum' => $did,
1933                 'countrycode' => $p->{'countrycode'},
1934                 'session_id' => $p->{'session_id'},
1935               }
1936             );
1937     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
1938   }
1939   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
1940 }
1941
1942 sub provision_acct {
1943   my $p = shift;
1944   warn "provision_acct called\n"
1945     if $DEBUG;
1946
1947   return { 'error' => gettext('passwords_dont_match') }
1948     if $p->{'_password'} ne $p->{'_password2'};
1949   return { 'error' => gettext('empty_password') }
1950     unless length($p->{'_password'});
1951  
1952   if ($p->{'domsvc'}) {
1953     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
1954                                                   qw ( svcpart pkgnum ) );
1955     return { 'error' => gettext('invalid_domain') }
1956       unless ($domains{$p->{'domsvc'}});
1957   }
1958
1959   warn "provision_acct calling _provision\n"
1960     if $DEBUG;
1961   _provision( 'FS::svc_acct',
1962               [qw(username _password domsvc)],
1963               [qw(username _password domsvc)],
1964               $p,
1965               @_
1966             );
1967 }
1968
1969 sub provision_external {
1970   my $p = shift;
1971   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
1972   _provision( 'FS::svc_external',
1973               [],
1974               [qw(id title)],
1975               $p,
1976               @_
1977             );
1978 }
1979
1980 sub _provision {
1981   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
1982   warn "_provision called for $class\n"
1983     if $DEBUG;
1984
1985   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1986   return { 'error' => $session } if $context eq 'error';
1987
1988   my $search = { 'custnum' => $custnum };
1989   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1990   my $cust_main = qsearchs('cust_main', $search )
1991     or return { 'error' => "unknown custnum $custnum" };
1992
1993   my $pkgnum = $p->{'pkgnum'};
1994
1995   warn "searching for custnum $custnum pkgnum $pkgnum\n"
1996     if $DEBUG;
1997   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1998                                         'pkgnum'  => $pkgnum,
1999                                                                } )
2000     or return { 'error' => "unknown pkgnum $pkgnum" };
2001
2002   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
2003     if $DEBUG;
2004   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
2005     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
2006
2007   warn "creating $class record\n"
2008     if $DEBUG;
2009   my $svc_x = $class->new( {
2010     'pkgnum'  => $p->{'pkgnum'},
2011     'svcpart' => $p->{'svcpart'},
2012     map { $_ => $p->{$_} } @$fields
2013   } );
2014   warn "inserting $class record\n"
2015     if $DEBUG;
2016   my $error = $svc_x->insert;
2017
2018   unless ( $error ) {
2019     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
2020       if $DEBUG;
2021     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
2022   }
2023
2024   my $return = { 'svc'   => $part_svc->svc,
2025                  'error' => $error,
2026                  map { $_ => $svc_x->get($_) } @$return_fields
2027                };
2028   warn "_provision returning ". Dumper($return). "\n"
2029     if $DEBUG;
2030   return $return;
2031
2032 }
2033
2034 sub part_svc_info {
2035   my $p = shift;
2036
2037   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2038   return { 'error' => $session } if $context eq 'error';
2039
2040   my $search = { 'custnum' => $custnum };
2041   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2042   my $cust_main = qsearchs('cust_main', $search )
2043     or return { 'error' => "unknown custnum $custnum" };
2044
2045   my $pkgnum = $p->{'pkgnum'};
2046
2047   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
2048                                         'pkgnum'  => $pkgnum,
2049                                                                } )
2050     or return { 'error' => "unknown pkgnum $pkgnum" };
2051
2052   my $svcpart = $p->{'svcpart'};
2053
2054   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
2055                                       'svcpart' => $svcpart,           } )
2056     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
2057   my $part_svc = $pkg_svc->part_svc;
2058
2059   my $conf = new FS::Conf;
2060
2061   my $ret = {
2062     'svc'     => $part_svc->svc,
2063     'svcdb'   => $part_svc->svcdb,
2064     'pkgnum'  => $pkgnum,
2065     'svcpart' => $svcpart,
2066     'custnum' => $custnum,
2067
2068     'security_phrase' => 0, #XXX !
2069     'svc_acct_pop'    => [], #XXX !
2070     'popnum'          => '',
2071     'init_popstate'   => '',
2072     'popac'           => '',
2073     'acstate'         => '',
2074
2075     'small_custview' =>
2076       small_custview( $cust_main, $conf->config('countrydefault') ),
2077
2078   };
2079
2080   if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ 
2081                      && $ret->{'svcdb'} eq 'svc_phone') {
2082         $ret->{'svcnum'} = $p->{'svcnum'};
2083         my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
2084         if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
2085             $ret->{'email'} = $svc_phone->email;
2086             $ret->{'forwarddst'} = $svc_phone->forwarddst;
2087         }
2088   }
2089
2090   $ret;
2091 }
2092
2093 sub unprovision_svc {
2094   my $p = shift;
2095
2096   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2097   return { 'error' => $session } if $context eq 'error';
2098
2099   my $search = { 'custnum' => $custnum };
2100   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2101   my $cust_main = qsearchs('cust_main', $search )
2102     or return { 'error' => "unknown custnum $custnum" };
2103
2104   my $svcnum = $p->{'svcnum'};
2105
2106   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
2107     or return { 'error' => "unknown svcnum $svcnum" };
2108
2109   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
2110     unless $cust_svc->cust_pkg->custnum == $custnum;
2111
2112   my $conf = new FS::Conf;
2113
2114   return { 'svc'   => $cust_svc->part_svc->svc,
2115            'error' => $cust_svc->cancel,
2116            'small_custview' =>
2117              small_custview( $cust_main, $conf->config('countrydefault') ),
2118          };
2119
2120 }
2121
2122 sub myaccount_passwd {
2123   my $p = shift;
2124   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2125   return { 'error' => $session } if $context eq 'error';
2126
2127   return { 'error' => "New passwords don't match." }
2128     if $p->{'new_password'} ne $p->{'new_password2'};
2129
2130   return { 'error' => 'Enter new password' }
2131     unless length($p->{'new_password'});
2132
2133   #my $search = { 'custnum' => $custnum };
2134   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2135   $custnum =~ /^(\d+)$/ or die "illegal custnum";
2136   my $search = " AND custnum = $1";
2137   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
2138
2139   my $svc_acct = qsearchs( {
2140     'table'     => 'svc_acct',
2141     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
2142                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
2143                    'LEFT JOIN cust_main USING ( custnum ) ',
2144     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
2145     'extra_sql' => $search, #important
2146   } )
2147     or return { 'error' => "Service not found" };
2148
2149   $svc_acct->_password($p->{'new_password'});
2150   my $error = $svc_acct->replace();
2151
2152   my($label, $value) = $svc_acct->cust_svc->label;
2153
2154   return { 'error' => $error,
2155            'label' => $label,
2156            'value' => $value,
2157          };
2158
2159 }
2160
2161 sub create_ticket {
2162   my $p = shift;
2163   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2164   return { 'error' => $session } if $context eq 'error';
2165
2166   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
2167   FS::TicketSystem->init();
2168
2169   my $conf = new FS::Conf;
2170   my $queue = $p->{'queue'}
2171               || $conf->config('ticket_system-selfservice_queueid')
2172               || $conf->config('ticket_system-default_queueid');
2173
2174   warn "$me create_ticket: creating ticket\n" if $DEBUG;
2175   my $err_or_ticket = FS::TicketSystem->create_ticket(
2176     '', #create RT session based on FS CurrentUser (fs_selfservice)
2177     'queue'   => $queue,
2178     'custnum' => $custnum,
2179     'svcnum'  => $session->{'svcnum'},
2180     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
2181   );
2182
2183   if ( ref($err_or_ticket) ) {
2184     warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
2185       if $DEBUG;
2186     return { 'error'     => '',
2187              'ticket_id' => $err_or_ticket->id,
2188            };
2189   } else {
2190     warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
2191       if $DEBUG;
2192     return { 'error' => $err_or_ticket };
2193   }
2194
2195
2196 }
2197
2198 sub did_report {
2199   my $p = shift;
2200   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2201   return { 'error' => $session } if $context eq 'error';
2202  
2203   return { error => 'requested format not implemented' } 
2204     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
2205
2206   my $conf = new FS::Conf;
2207   my $age_threshold = 0;
2208   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
2209     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
2210
2211   my $search = { 'custnum' => $custnum };
2212   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
2213   my $cust_main = qsearchs('cust_main', $search )
2214     or return { 'error' => "unknown custnum $custnum" };
2215
2216 # does it make more sense to just run one sql query for this instead of all the
2217 # insanity below? would increase performance greately for large data sets?
2218   my @svc_phone = ();
2219   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
2220         my @part_svc = $cust_pkg->part_svc;
2221         foreach my $part_svc ( @part_svc ) {
2222             if($part_svc->svcdb eq 'svc_phone'){
2223                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
2224                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
2225                     push @svc_phone, $cust_pkg_svc->svc_x
2226                         if $cust_pkg_svc->date_inserted >= $age_threshold;
2227                 }
2228             }
2229         }
2230   }
2231
2232   my $csv;
2233   my $xls;
2234   my($xls_r,$xls_c) = (0,0);
2235   my $xls_workbook;
2236   my $content = '';
2237   my @fields = qw( countrycode phonenum pin sip_password phone_name );
2238   if($p->{'format'} eq 'csv') {
2239     $csv = new Text::CSV_XS { 'always_quote' => 1,
2240                                  'eol'          => "\n",
2241                                 };
2242     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2243     $content .= $csv->string;
2244   }
2245   elsif($p->{'format'} eq 'xls') {
2246     my $XLS1 = new IO::Scalar \$content;
2247     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
2248         or return { 'error' => "Error opening .xls file: $!" };
2249     $xls = $xls_workbook->add_worksheet('DIDs');
2250     foreach ( @fields ) {
2251         $xls->write(0,$xls_c++,$_);
2252     }
2253     $xls_r++;
2254   }
2255
2256   foreach my $svc_phone ( @svc_phone ) {
2257     my @cols = map { $svc_phone->$_ } @fields;
2258     if($p->{'format'} eq 'csv') {
2259         return { 'error' => 'Unable to create CSV' } 
2260             unless $csv->combine(@cols);
2261         $content .= $csv->string;
2262     }
2263     elsif($p->{'format'} eq 'xls') {
2264         $xls_c = 0;
2265         foreach ( @cols ) {
2266             $xls->write($xls_r,$xls_c++,$_);
2267         }
2268         $xls_r++;
2269     }
2270   }
2271
2272   $xls_workbook->close() if $p->{'format'} eq 'xls';
2273   
2274   { content => $content, format => $p->{'format'}, };
2275 }
2276
2277 sub get_ticket {
2278   my $p = shift;
2279   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2280   return { 'error' => $session } if $context eq 'error';
2281
2282   warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2283   FS::TicketSystem->init();
2284   return { 'error' => 'get_ticket configuration error' }
2285     if $FS::TicketSystem::system ne 'RT_Internal';
2286
2287   # check existence and ownership as part of this
2288   warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2289   my $rt_session = FS::TicketSystem->session('');
2290   my $Ticket = FS::TicketSystem->get_ticket_object(
2291     $rt_session, 
2292     ticket_id => $p->{'ticket_id'},
2293     custnum => $custnum
2294   );
2295   return { 'error' => 'ticket not found' } if !$Ticket;
2296
2297   if ( length( $p->{'subject'} || '' ) ) {
2298     # subject change
2299     if ( $p->{'subject'} ne $Ticket->Subject ) {
2300       my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
2301       return { 'error' => "unable to set subject: $msg" } if !$val;
2302     }
2303   }
2304
2305   if(length($p->{'reply'})) {
2306     my @err_or_res = FS::TicketSystem->correspond_ticket(
2307       $rt_session,
2308       'ticket_id' => $p->{'ticket_id'},
2309       'content' => $p->{'reply'},
2310     );
2311
2312     return { 'error' => 'unable to reply to ticket' } 
2313     unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2314   }
2315
2316   warn "$me get_ticket: getting ticket history\n" if $DEBUG;
2317   my $err_or_ticket = FS::TicketSystem->get_ticket(
2318     $rt_session,
2319     'ticket_id' => $p->{'ticket_id'},
2320   );
2321
2322   if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
2323     warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
2324       if $DEBUG;
2325     return { 'error' => $err_or_ticket };
2326   }
2327
2328   my @custs = @{$err_or_ticket->{'custs'}};
2329   my @txns = @{$err_or_ticket->{'txns'}};
2330   my @filtered_txns;
2331
2332   # superseded by check in get_ticket_object
2333   #return { 'error' => 'invalid ticket requested' } 
2334   #unless grep($_ eq $custnum, @custs);
2335
2336   foreach my $txn ( @txns ) {
2337     push @filtered_txns, $txn 
2338     if ($txn->{'type'} eq 'EmailRecord' 
2339       || $txn->{'type'} eq 'Correspond'
2340       || $txn->{'type'} eq 'Create');
2341   }
2342
2343   warn "$me get_ticket: successful: \n"
2344   if $DEBUG;
2345   return { 'error'     => '',
2346     'transactions' => \@filtered_txns,
2347     'ticket_fields' => $err_or_ticket->{'fields'},
2348     'ticket_id' => $p->{'ticket_id'},
2349   };
2350 }
2351
2352 sub adjust_ticket_priority {
2353   my $p = shift;
2354   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2355   return { 'error' => $session } if $context eq 'error';
2356
2357   warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
2358   FS::TicketSystem->init;
2359   my $ss_priority = FS::TicketSystem->selfservice_priority;
2360
2361   return { 'error' => 'adjust_ticket_priority configuration error' }
2362     if $FS::TicketSystem::system ne 'RT_Internal'
2363       or !$ss_priority;
2364
2365   my $values = $p->{'values'}; #hashref, id => priority value
2366   my %ticket_error;
2367
2368   foreach my $id (keys %$values) {
2369     warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
2370     my $Ticket = FS::TicketSystem->get_ticket_object('',
2371       'ticket_id' => $id,
2372       'custnum'   => $custnum,
2373     );
2374     if ( !$Ticket ) {
2375       $ticket_error{$id} = 'ticket not found';
2376       next;
2377     }
2378     
2379   # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
2380   # We're not going to implement it for RT_External.
2381     my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
2382     my $new_value = $values->{$id};
2383     next if $old_value eq $new_value;
2384
2385     warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
2386
2387     # AddCustomFieldValue works fine (replacing any existing value) if it's 
2388     # a single-valued custom field, which it should be.  If it's not, you're 
2389     # doing something wrong.
2390     my ($val, $msg);
2391     if ( length($new_value) ) {
2392       ($val, $msg) = $Ticket->AddCustomFieldValue( 
2393         Field => $ss_priority,
2394         Value => $new_value,
2395       );
2396     }
2397     else {
2398       ($val, $msg) = $Ticket->DeleteCustomFieldValue(
2399         Field => $ss_priority,
2400         Value => $old_value,
2401       );
2402     }
2403
2404     $ticket_error{$id} = $msg if !$val;
2405     warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
2406   }
2407   return { 'error' => '',
2408            'ticket_error' => \%ticket_error,
2409            %{ customer_info($p) } # send updated customer info back
2410          }
2411 }
2412
2413 #--
2414
2415 sub _custoragent_session_custnum {
2416   my $p = shift;
2417
2418   my($context, $session, $custnum);
2419   if ( $p->{'session_id'} ) {
2420
2421     $context = 'customer';
2422     $session = _cache->get($p->{'session_id'})
2423       or return ( 'error' => "Can't resume session" ); #better error message
2424     $custnum = $session->{'custnum'};
2425
2426   } elsif ( $p->{'agent_session_id'} ) {
2427
2428     $context = 'agent';
2429     my $agent_cache = new FS::ClientAPI_SessionCache( {
2430       'namespace' => 'FS::ClientAPI::Agent',
2431     } );
2432     $session = $agent_cache->get($p->{'agent_session_id'})
2433       or return ( 'error' => "Can't resume session" ); #better error message
2434     $custnum = $p->{'custnum'};
2435
2436   } else {
2437     $context = 'error';
2438     return ( 'error' => "Can't resume session" ); #better error message
2439   }
2440
2441   ($context, $session, $custnum);
2442
2443 }
2444
2445 1;
2446