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