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