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