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