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