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