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