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