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