fix svc_pbx selfservice title?
[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 Data::Dumper;
8 use Digest::MD5 qw(md5_hex);
9 use Date::Format;
10 use Business::CreditCard;
11 use Time::Duration;
12 use Time::Local qw(timelocal_nocheck);
13 use FS::UI::Web::small_custview qw(small_custview); #less doh
14 use FS::UI::Web;
15 use FS::UI::bytecount qw( display_bytecount );
16 use FS::Conf;
17 #use FS::UID qw(dbh);
18 use FS::Record qw(qsearch qsearchs dbh);
19 use FS::Msgcat qw(gettext);
20 use FS::Misc qw(card_types);
21 use FS::Misc::DateTime qw(parse_datetime);
22 use FS::ClientAPI_SessionCache;
23 use FS::svc_acct;
24 use FS::svc_domain;
25 use FS::svc_phone;
26 use FS::svc_external;
27 use FS::part_svc;
28 use FS::cust_main;
29 use FS::cust_bill;
30 use FS::cust_main_county;
31 use FS::cust_pkg;
32 use FS::payby;
33 use FS::acct_rt_transaction;
34 use HTML::Entities;
35 use FS::TicketSystem;
36 use Text::CSV_XS;
37 use IO::Scalar;
38 use Spreadsheet::WriteExcel;
39
40 $DEBUG = 0;
41 $me = '[FS::ClientAPI::MyAccount]';
42
43 use vars qw( @cust_main_editable_fields );
44 @cust_main_editable_fields = qw(
45   first last company address1 address2 city
46     county state zip country daytime night fax
47   ship_first ship_last ship_company ship_address1 ship_address2 ship_city
48     ship_state ship_zip ship_country ship_daytime ship_night ship_fax
49   payby payinfo payname paystart_month paystart_year payissue payip
50   ss paytype paystate stateid stateid_state
51 );
52
53 sub _cache {
54   $cache ||= new FS::ClientAPI_SessionCache( {
55                'namespace' => 'FS::ClientAPI::MyAccount',
56              } );
57 }
58
59 sub skin_info {
60   my $p = shift;
61
62   my($context, $session, $custnum) = _custoragent_session_custnum($p);
63   #return { 'error' => $session } if $context eq 'error';
64
65   my $agentnum = '';
66   if ( $context eq 'customer' ) {
67
68     my $sth = dbh->prepare('SELECT agentnum FROM cust_main WHERE custnum = ?')
69       or die dbh->errstr;
70
71     $sth->execute($custnum) or die $sth->errstr;
72
73     $agentnum = $sth->fetchrow_arrayref->[0]
74       or die "no agentnum for custnum $custnum";
75
76   #} elsif ( $context eq 'agent' ) {
77   } elsif ( defined($p->{'agentnum'}) and $p->{'agentnum'} =~ /^(\d+)$/ ) {
78     $agentnum = $1;
79   }
80
81   my $conf = new FS::Conf;
82
83   #false laziness w/Signup.pm
84
85   my $skin_info_cache_agent = _cache->get("skin_info_cache_agent$agentnum");
86
87   if ( $skin_info_cache_agent ) {
88
89     warn "$me loading cached skin info for agentnum $agentnum\n"
90       if $DEBUG > 1;
91
92   } else {
93
94     warn "$me populating skin info cache for agentnum $agentnum\n"
95       if $DEBUG > 1;
96
97     $skin_info_cache_agent = {
98       'agentnum' => $agentnum,
99       ( map { $_ => scalar( $conf->config($_, $agentnum) ) }
100         qw( company_name date_format ) ),
101       ( map { $_ => scalar( $conf->config("selfservice-$_", $agentnum ) ) }
102         qw( body_bgcolor box_bgcolor
103             text_color link_color vlink_color hlink_color alink_color
104             font title_color title_align title_size menu_bgcolor menu_fontsize
105           )
106       ),
107       ( map { $_ => $conf->exists("selfservice-$_", $agentnum ) }
108         qw( menu_skipblanks menu_skipheadings menu_nounderline )
109       ),
110       ( map { $_ => scalar($conf->config_binary("selfservice-$_", $agentnum)) }
111         qw( title_left_image title_right_image
112             menu_top_image menu_body_image menu_bottom_image
113           )
114       ),
115       'logo' => scalar($conf->config_binary('logo.png', $agentnum )),
116       ( map { $_ => join("\n", $conf->config("selfservice-$_", $agentnum ) ) }
117         qw( head body_header body_footer company_address ) ),
118     };
119
120     _cache->set("skin_info_cache_agent$agentnum", $skin_info_cache_agent);
121
122   }
123
124   #{ %$skin_info_cache_agent };
125   $skin_info_cache_agent;
126
127 }
128
129 sub login_info {
130   my $p = shift;
131
132   my $conf = new FS::Conf;
133
134   my %info = (
135     %{ skin_info($p) },
136     'phone_login'  => $conf->exists('selfservice_server-phone_login'),
137     'single_domain'=> scalar($conf->config('selfservice_server-single_domain')),
138   );
139
140   return \%info;
141
142 }
143
144 #false laziness w/FS::ClientAPI::passwd::passwd
145 sub login {
146   my $p = shift;
147
148   my $conf = new FS::Conf;
149
150   my $svc_x = '';
151   if ( $p->{'domain'} eq 'svc_phone'
152        && $conf->exists('selfservice_server-phone_login') ) { 
153
154     my $svc_phone = qsearchs( 'svc_phone', { 'phonenum' => $p->{'username'} } );
155     return { error => 'Number not found.' } unless $svc_phone;
156
157     #XXX?
158     #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
159     #return { error => 'Only primary user may log in.' } 
160     #  if $conf->exists('selfservice_server-primary_only')
161     #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
162
163     return { error => 'Incorrect PIN.' }
164       unless $svc_phone->check_pin($p->{'password'});
165
166     $svc_x = $svc_phone;
167
168   } else {
169
170     my $svc_domain = qsearchs('svc_domain', { 'domain' => $p->{'domain'} } )
171       or return { error => 'Domain '. $p->{'domain'}. ' not found' };
172
173     my $svc_acct = qsearchs( 'svc_acct', { 'username'  => $p->{'username'},
174                                            'domsvc'    => $svc_domain->svcnum, }
175                            );
176     return { error => 'User not found.' } unless $svc_acct;
177
178     if($conf->exists('selfservice_server-login_svcpart')) {
179         my @svcpart = $conf->config('selfservice_server-login_svcpart');
180         my $svcpart = $svc_acct->cust_svc->svcpart;
181         return { error => 'Invalid user.' } 
182             unless grep($_ eq $svcpart, @svcpart);
183     }
184
185     return { error => 'Incorrect password.' }
186       unless $svc_acct->check_password($p->{'password'});
187
188     $svc_x = $svc_acct;
189
190   }
191
192   my $session = {
193     'svcnum' => $svc_x->svcnum,
194   };
195
196   my $cust_svc = $svc_x->cust_svc;
197   my $cust_pkg = $cust_svc->cust_pkg;
198   if ( $cust_pkg ) {
199     my $cust_main = $cust_pkg->cust_main;
200     $session->{'custnum'} = $cust_main->custnum;
201     if ( $conf->exists('pkg-balances') ) {
202       my @cust_pkg = grep { $_->part_pkg->freq !~ /^(0|$)/ }
203                           $cust_main->ncancelled_pkgs;
204       $session->{'pkgnum'} = $cust_pkg->pkgnum
205         if scalar(@cust_pkg) > 1;
206     }
207   }
208
209   #my $pkg_svc = $svc_acct->cust_svc->pkg_svc;
210   #return { error => 'Only primary user may log in.' } 
211   #  if $conf->exists('selfservice_server-primary_only')
212   #    && ( ! $pkg_svc || $pkg_svc->primary_svc ne 'Y' );
213   my $part_pkg = $cust_pkg->part_pkg;
214   return { error => 'Only primary user may log in.' }
215     if $conf->exists('selfservice_server-primary_only')
216        && $cust_svc->svcpart != $part_pkg->svcpart([qw( svc_acct svc_phone )]);
217
218   my $session_id;
219   do {
220     $session_id = md5_hex(md5_hex(time(). {}. rand(). $$))
221   } until ( ! defined _cache->get($session_id) ); #just in case
222
223   my $timeout = $conf->config('selfservice-session_timeout') || '1 hour';
224   _cache->set( $session_id, $session, $timeout );
225
226   return { 'error'      => '',
227            'session_id' => $session_id,
228          };
229 }
230
231 sub logout {
232   my $p = shift;
233   if ( $p->{'session_id'} ) {
234     _cache->remove($p->{'session_id'});
235     return { %{ skin_info($p) }, 'error' => '' };
236   } else {
237     return { %{ skin_info($p) }, 'error' => "Can't resume session" }; #better error message
238   }
239 }
240
241 sub payment_gateway {
242   # internal use only
243   # takes a cust_main and a cust_payby entry, returns the payment_gateway
244   my $conf = new FS::Conf;
245   my $cust_main = shift;
246   my $cust_payby = shift;
247   my $gatewaynum = $conf->config('selfservice-payment_gateway');
248   if ( $gatewaynum ) {
249     my $pg = qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
250     die "configured gatewaynum $gatewaynum not found!" if !$pg;
251     return $pg;
252   }
253   else {
254     return '' if ! FS::payby->realtime($cust_payby);
255     my $pg = $cust_main->agent->payment_gateway(
256       'method'  => FS::payby->payby2bop($cust_payby),
257       'nofatal' => 1
258     );
259     return $pg;
260   }
261 }
262
263 sub access_info {
264   my $p = shift;
265
266   my $conf = new FS::Conf;
267
268   my $info = skin_info($p);
269
270   use vars qw( $cust_paybys ); #cache for performance
271   unless ( $cust_paybys ) {
272
273     my %cust_paybys = map { $_ => 1 }
274                       map { FS::payby->payby2payment($_) }
275                           $conf->config('signup_server-payby');
276
277     $cust_paybys = [ keys %cust_paybys ];
278
279   }
280   $info->{'cust_paybys'} = $cust_paybys;
281
282   my($context, $session, $custnum) = _custoragent_session_custnum($p);
283   return { 'error' => $session } if $context eq 'error';
284
285   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
286     or return { 'error' => "unknown custnum $custnum" };
287
288   $info->{'hide_payment_fields'} = [ 
289     map { 
290       my $pg = payment_gateway($cust_main, $_);
291       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
292     } @{ $info->{cust_paybys} }
293   ];
294
295   $info->{'self_suspend_reason'} = 
296       $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum);
297
298   $info->{'edit_ticket_subject'} =
299       $conf->exists('ticket_system-selfservice_edit_subject') && 
300       $cust_main->edit_subject;
301
302   return { %$info,
303            'custnum'       => $custnum,
304            'access_pkgnum' => $session->{'pkgnum'},
305            'access_svcnum' => $session->{'svcnum'},
306          };
307 }
308
309 sub customer_info {
310   my $p = shift;
311
312   my($context, $session, $custnum) = _custoragent_session_custnum($p);
313   return { 'error' => $session } if $context eq 'error';
314
315   my %return;
316
317   my $conf = new FS::Conf;
318   if ($conf->exists('cust_main-require_address2')) {
319     $return{'require_address2'} = '1';
320   }else{
321     $return{'require_address2'} = '';
322   }
323
324   if ( $FS::TicketSystem::system ) {
325     warn "$me customer_info: initializing ticket system\n" if $DEBUG;
326     FS::TicketSystem->init();
327   }
328  
329   if ( $custnum ) { #customer record
330
331     my $search = { 'custnum' => $custnum };
332     $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
333     my $cust_main = qsearchs('cust_main', $search )
334       or return { 'error' => "unknown custnum $custnum" };
335
336     if ( $session->{'pkgnum'} ) { 
337       $return{balance} = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
338     } else {
339       $return{balance} = $cust_main->balance;
340     }
341
342     $return{tickets} = [ ($cust_main->tickets) ];
343
344     unless ( $session->{'pkgnum'} ) {
345       my @open = map {
346                        {
347                          invnum => $_->invnum,
348                          date   => time2str("%b %o, %Y", $_->_date),
349                          owed   => $_->owed,
350                        };
351                      } $cust_main->open_cust_bill;
352       $return{open_invoices} = \@open;
353     }
354
355     $return{small_custview} =
356       small_custview( $cust_main,
357                       scalar($conf->config('countrydefault')),
358                       ( $session->{'pkgnum'} ? 1 : 0 ), #nobalance
359                     );
360
361     $return{name} = $cust_main->first. ' '. $cust_main->get('last');
362
363     for (@cust_main_editable_fields) {
364       $return{$_} = $cust_main->get($_);
365     }
366
367     if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
368       $return{payinfo} = $cust_main->paymask;
369       @return{'month', 'year'} = $cust_main->paydate_monthyear;
370     }
371
372     $return{'invoicing_list'} =
373       join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
374     $return{'postal_invoicing'} =
375       0 < ( grep { $_ eq 'POST' } $cust_main->invoicing_list );
376
377     if (scalar($conf->config('support_packages'))) {
378       my @support_services = ();
379       foreach ($cust_main->support_services) {
380         my $seconds = $_->svc_x->seconds;
381         my $time_remaining = (($seconds < 0) ? '-' : '' ).
382                              int(abs($seconds)/3600)."h".
383                              sprintf("%02d",(abs($seconds)%3600)/60)."m";
384         my $cust_pkg = $_->cust_pkg;
385         my $pkgnum = '';
386         my $pkg = '';
387         $pkgnum = $cust_pkg->pkgnum if $cust_pkg;
388         $pkg = $cust_pkg->part_pkg->pkg if $cust_pkg;
389         push @support_services, { svcnum => $_->svcnum,
390                                   time => $time_remaining,
391                                   pkgnum => $pkgnum,
392                                   pkg => $pkg,
393                                 };
394       }
395       $return{support_services} = \@support_services;
396     }
397
398     if ( $conf->config('prepayment_discounts-credit_type') ) {
399       #need to eval?
400       $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
401     }
402
403   } elsif ( $session->{'svcnum'} ) { #no customer record
404
405     my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $session->{'svcnum'} } )
406       or die "unknown svcnum";
407     $return{name} = $svc_acct->email;
408
409   } else {
410
411     return { 'error' => 'Expired session' }; #XXX redirect to login w/this err!
412
413   }
414
415   return { 'error'          => '',
416            'custnum'        => $custnum,
417            %return,
418          };
419
420 }
421
422 sub edit_info {
423   my $p = shift;
424   my $session = _cache->get($p->{'session_id'})
425     or return { 'error' => "Can't resume session" }; #better error message
426
427   my $custnum = $session->{'custnum'}
428     or return { 'error' => "no customer record" };
429
430   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
431     or return { 'error' => "unknown custnum $custnum" };
432
433   my $new = new FS::cust_main { $cust_main->hash };
434   $new->set( $_ => $p->{$_} )
435     foreach grep { exists $p->{$_} } @cust_main_editable_fields;
436
437   my $payby = '';
438   if (exists($p->{'payby'})) {
439     $p->{'payby'} =~ /^([A-Z]{4})$/
440       or return { 'error' => "illegal_payby " . $p->{'payby'} };
441     $payby = $1;
442   }
443
444   if ( $payby =~ /^(CARD|DCRD)$/ ) {
445
446     $new->paydate($p->{'year'}. '-'. $p->{'month'}. '-01');
447
448     if ( $new->payinfo eq $cust_main->paymask ) {
449       $new->payinfo($cust_main->payinfo);
450     } else {
451       $new->payinfo($p->{'payinfo'});
452     }
453
454     $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
455
456   } elsif ( $payby =~ /^(CHEK|DCHK)$/ ) {
457
458     my $payinfo;
459     $p->{'payinfo1'} =~ /^([\dx]+)$/
460       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
461     my $payinfo1 = $1;
462      $p->{'payinfo2'} =~ /^([\dx]+)$/
463       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
464     my $payinfo2 = $1;
465     $payinfo = $payinfo1. '@'. $payinfo2;
466
467     $new->payinfo( ($payinfo eq $cust_main->paymask)
468                      ? $cust_main->payinfo
469                      : $payinfo
470                  );
471
472     $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
473
474   } elsif ( $payby =~ /^(BILL)$/ ) {
475     #no-op
476   } elsif ( $payby ) {  #notyet ready
477     return { 'error' => "unknown payby $payby" };
478   }
479
480   my @invoicing_list;
481   if ( exists $p->{'invoicing_list'} || exists $p->{'postal_invoicing'} ) {
482     #false laziness with httemplate/edit/process/cust_main.cgi
483     @invoicing_list = split( /\s*\,\s*/, $p->{'invoicing_list'} );
484     push @invoicing_list, 'POST' if $p->{'postal_invoicing'};
485   } else {
486     @invoicing_list = $cust_main->invoicing_list;
487   }
488
489   my $error = $new->replace($cust_main, \@invoicing_list);
490   return { 'error' => $error } if $error;
491   #$cust_main = $new;
492   
493   return { 'error' => '' };
494 }
495
496 sub payment_info {
497   my $p = shift;
498   my $session = _cache->get($p->{'session_id'})
499     or return { 'error' => "Can't resume session" }; #better error message
500
501   ##
502   #generic
503   ##
504
505   my $conf = new FS::Conf;
506   use vars qw($payment_info); #cache for performance
507   unless ( $payment_info ) {
508
509     my %states = map { $_->state => 1 }
510                    qsearch('cust_main_county', {
511                      'country' => $conf->config('countrydefault') || 'US'
512                    } );
513
514     my %cust_paybys = map { $_ => 1 }
515                       map { FS::payby->payby2payment($_) }
516                           $conf->config('signup_server-payby');
517
518     my @cust_paybys = keys %cust_paybys;
519
520     $payment_info = {
521
522       #list all counties/states/countries
523       'cust_main_county' => 
524         [ map { $_->hashref } qsearch('cust_main_county', {}) ],
525
526       #shortcut for one-country folks
527       'states' =>
528         [ sort { $a cmp $b } keys %states ],
529
530       'card_types' => card_types(),
531
532       'paytypes' => [ @FS::cust_main::paytypes ],
533
534       'paybys' => [ $conf->config('signup_server-payby') ],
535       'cust_paybys' => \@cust_paybys,
536
537       'stateid_label' => FS::Msgcat::_gettext('stateid'),
538       'stateid_state_label' => FS::Msgcat::_gettext('stateid_state'),
539
540       'show_ss'  => $conf->exists('show_ss'),
541       'show_stateid' => $conf->exists('show_stateid'),
542       'show_paystate' => $conf->exists('show_bankstate'),
543
544       'save_unchecked' => $conf->exists('selfservice-save_unchecked'),
545
546       'credit_card_surcharge_percentage' => $conf->config('credit-card-surcharge-percentage'),
547     };
548
549   }
550
551   ##
552   #customer-specific
553   ##
554
555   my %return = %$payment_info;
556
557   my $custnum = $session->{'custnum'};
558
559   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
560     or return { 'error' => "unknown custnum $custnum" };
561
562   $return{'hide_payment_fields'} = [
563     map { 
564       my $pg = payment_gateway($cust_main, $_);
565       $pg && $pg->gateway_namespace eq 'Business::OnlineThirdPartyPayment';
566     } @{ $return{cust_paybys} }
567   ];
568
569   $return{balance} = $cust_main->balance; #XXX pkg-balances?
570
571   $return{payname} = $cust_main->payname
572                      || ( $cust_main->first. ' '. $cust_main->get('last') );
573
574   $return{$_} = $cust_main->get($_) for qw(address1 address2 city state zip);
575
576   $return{payby} = $cust_main->payby;
577   $return{stateid_state} = $cust_main->stateid_state;
578
579   if ( $cust_main->payby =~ /^(CARD|DCRD)$/ ) {
580     $return{card_type} = cardtype($cust_main->payinfo);
581     $return{payinfo} = $cust_main->paymask;
582
583     @return{'month', 'year'} = $cust_main->paydate_monthyear;
584
585   }
586
587   if ( $cust_main->payby =~ /^(CHEK|DCHK)$/ ) {
588     my ($payinfo1, $payinfo2) = split '@', $cust_main->paymask;
589     $return{payinfo1} = $payinfo1;
590     $return{payinfo2} = $payinfo2;
591     $return{paytype}  = $cust_main->paytype;
592     $return{paystate} = $cust_main->paystate;
593
594   }
595
596   if ( $conf->config('prepayment_discounts-credit_type') ) {
597     #need to eval?
598     $return{discount_terms_hash} = { $cust_main->discount_terms_hash };
599   }
600
601   #doubleclick protection
602   my $_date = time;
603   $return{paybatch} = "webui-MyAccount-$_date-$$-". rand() * 2**32;
604
605   return { 'error' => '',
606            %return,
607          };
608
609 };
610
611 #some false laziness with httemplate/process/payment.cgi - look there for
612 #ACH and CVV support stuff
613 sub process_payment {
614
615   my $p = shift;
616
617   my $session = _cache->get($p->{'session_id'})
618     or return { 'error' => "Can't resume session" }; #better error message
619
620   my %return;
621
622   my $custnum = $session->{'custnum'};
623
624   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
625     or return { 'error' => "unknown custnum $custnum" };
626
627   $p->{'amount'} =~ /^\s*(\d+(\.\d{2})?)\s*$/
628     or return { 'error' => gettext('illegal_amount') };
629   my $amount = $1;
630   return { error => 'Amount must be greater than 0' } unless $amount > 0;
631
632   $p->{'discount_term'} =~ /^\s*(\d*)\s*$/
633     or return { 'error' => gettext('illegal_discount_term'). ': '. $p->{'discount_term'} };
634   my $discount_term = $1;
635
636   $p->{'payname'} =~ /^([\w \,\.\-\']+)$/
637     or return { 'error' => gettext('illegal_name'). " payname: ". $p->{'payname'} };
638   my $payname = $1;
639
640   $p->{'paybatch'} =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
641     or return { 'error' => gettext('illegal_text'). " paybatch: ". $p->{'paybatch'} };
642   my $paybatch = $1;
643
644   $p->{'payby'} ||= 'CARD';
645   $p->{'payby'} =~ /^([A-Z]{4})$/
646     or return { 'error' => "illegal_payby " . $p->{'payby'} };
647   my $payby = $1;
648
649   #false laziness w/process/payment.cgi
650   my $payinfo;
651   my $paycvv = '';
652   my $paynum = '';
653   if ( $payby eq 'CHEK' || $payby eq 'DCHK' ) {
654   
655     $p->{'payinfo1'} =~ /^([\dx]+)$/
656       or return { 'error' => "illegal account number ". $p->{'payinfo1'} };
657     my $payinfo1 = $1;
658      $p->{'payinfo2'} =~ /^([\dx]+)$/
659       or return { 'error' => "illegal ABA/routing number ". $p->{'payinfo2'} };
660     my $payinfo2 = $1;
661     $payinfo = $payinfo1. '@'. $payinfo2;
662
663     $payinfo = $cust_main->payinfo
664       if $cust_main->paymask eq $payinfo;
665    
666   } elsif ( $payby eq 'CARD' || $payby eq 'DCRD' ) {
667    
668     $payinfo = $p->{'payinfo'};
669
670     #more intelligent mathing will be needed here if you change
671     #card_masking_method and don't remove existing paymasks
672     $payinfo = $cust_main->payinfo
673       if $cust_main->paymask eq $payinfo;
674
675     $payinfo =~ s/\D//g;
676     $payinfo =~ /^(\d{13,16})$/
677       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
678     $payinfo = $1;
679
680     validate($payinfo)
681       or return { 'error' => gettext('invalid_card') }; # . ": ". $self->payinfo
682     return { 'error' => gettext('unknown_card_type') }
683       if $payinfo !~ /^99\d{14}$/ && cardtype($payinfo) eq "Unknown";
684
685     if ( length($p->{'paycvv'}) && $p->{'paycvv'} !~ /^\s*$/ ) {
686       if ( cardtype($payinfo) eq 'American Express card' ) {
687         $p->{'paycvv'} =~ /^\s*(\d{4})\s*$/
688           or return { 'error' => "CVV2 (CID) for American Express cards is four digits." };
689         $paycvv = $1;
690       } else {
691         $p->{'paycvv'} =~ /^\s*(\d{3})\s*$/
692           or return { 'error' => "CVV2 (CVC2/CID) is three digits." };
693         $paycvv = $1;
694       }
695     }
696   
697   } else {
698     die "unknown payby $payby";
699   }
700
701   my %payby2fields = (
702     'CARD' => [ qw( paystart_month paystart_year payissue payip
703                     address1 address2 city state zip country    ) ],
704     'CHEK' => [ qw( ss paytype paystate stateid stateid_state payip ) ],
705   );
706
707   my $error = $cust_main->realtime_bop( $FS::payby::payby2bop{$payby}, $amount,
708     'quiet'    => 1,
709     'payinfo'  => $payinfo,
710     'paydate'  => $p->{'year'}. '-'. $p->{'month'}. '-01',
711     'payname'  => $payname,
712     'paybatch' => $paybatch, #this doesn't actually do anything
713     'paycvv'   => $paycvv,
714     'paynum_ref' => \$paynum,
715     'pkgnum'   => $session->{'pkgnum'},
716     'discount_term' => $discount_term,
717     'selfservice' => 1,
718     map { $_ => $p->{$_} } @{ $payby2fields{$payby} }
719   );
720   return { 'error' => $error } if $error;
721
722   $cust_main->apply_payments;
723
724   if ( $p->{'save'} ) {
725     my $new = new FS::cust_main { $cust_main->hash };
726     if ($payby eq 'CARD' || $payby eq 'DCRD') {
727       $new->set( $_ => $p->{$_} )
728         foreach qw( payname paystart_month paystart_year payissue payip
729                     address1 address2 city state zip country );
730       $new->set( 'payby' => $p->{'auto'} ? 'CARD' : 'DCRD' );
731     } elsif ($payby eq 'CHEK' || $payby eq 'DCHK') {
732       $new->set( $_ => $p->{$_} )
733         foreach qw( payname payip paytype paystate
734                     stateid stateid_state );
735       $new->set( 'payby' => $p->{'auto'} ? 'CHEK' : 'DCHK' );
736     }
737     $new->set( 'payinfo' => $cust_main->card_token || $payinfo );
738     $new->set( 'paydate' => $p->{'year'}. '-'. $p->{'month'}. '-01' );
739     my $error = $new->replace($cust_main);
740     if ( $error ) {
741       #no, this causes customers to process their payments again
742       #return { 'error' => $error };
743       #XXX just warn verosely for now so i can figure out how these happen in
744       # the first place, eventually should redirect them to the "change
745       #address" page but indicate the payment did process??
746       delete($p->{'payinfo'}); #don't want to log this!
747       warn "WARNING: error changing customer info when processing payment (not returning to customer as a processing error): $error\n".
748            "NEW: ". Dumper($new)."\n".
749            "OLD: ". Dumper($cust_main)."\n".
750            "PACKET: ". Dumper($p)."\n";
751     #} else {
752       #not needed...
753       #$cust_main = $new;
754     }
755   }
756
757   my $receipt_html = '';
758   if($paynum) { 
759       # currently supported for realtime CC only; send receipt data to SS
760       my $cust_pay = qsearchs('cust_pay', { 'paynum' => $paynum } );
761       if($cust_pay) {
762         $receipt_html = qq!
763 <TABLE BGCOLOR="#cccccc" BORDER=0 CELLSPACING=2>
764
765 <TR>
766   <TD ALIGN="right">Payment#</TD>
767   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paynum . qq!</B></TD>
768 </TR>
769
770 <TR>
771   <TD ALIGN="right">Date</TD>
772
773   <TD BGCOLOR="#FFFFFF"><B>! . 
774         time2str("%a&nbsp;%b&nbsp;%o,&nbsp;%Y&nbsp;%r", $cust_pay->_date)
775                                                             . qq!</B></TD>
776 </TR>
777
778
779 <TR>
780   <TD ALIGN="right">Amount</TD>
781   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->paid . qq!</B></TD>
782
783 </TR>
784
785 <TR>
786   <TD ALIGN="right">Payment method</TD>
787   <TD BGCOLOR="#FFFFFF"><B>! . $cust_pay->payby_name .' #'. $cust_pay->paymask
788                                                                 . qq!</B></TD>
789 </TR>
790
791 </TABLE>
792 !;
793       }
794   }
795
796   return { 'error' => '', 'receipt_html' => $receipt_html, };
797
798 }
799
800 sub realtime_collect {
801   my $p = shift;
802
803   my $session = _cache->get($p->{'session_id'})
804     or return { 'error' => "Can't resume session" }; #better error message
805
806   my $custnum = $session->{'custnum'};
807
808   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
809     or return { 'error' => "unknown custnum $custnum" };
810
811   my $amount;
812   if ( $p->{'amount'} ) {
813     $amount = $p->{'amount'};
814   }
815   elsif ( $session->{'pkgnum'} ) {
816     $amount = $cust_main->balance_pkgnum( $session->{'pkgnum'} );
817   }
818   else {
819     $amount = $cust_main->balance;
820   }
821
822   my $error = $cust_main->realtime_collect(
823     'method'     => $p->{'method'},
824     'amount'     => $amount,
825     'pkgnum'     => $session->{'pkgnum'},
826     'session_id' => $p->{'session_id'},
827     'apply'      => 1,
828     'selfservice'=> 1,
829   );
830   return { 'error' => $error } unless ref( $error );
831
832   return { 'error' => '', amount => $amount, %$error };
833 }
834
835 sub process_payment_order_pkg {
836   my $p = shift;
837
838   my $hr = process_payment($p);
839   return $hr if $hr->{'error'};
840
841   order_pkg($p);
842 }
843
844 sub process_payment_order_renew {
845   my $p = shift;
846
847   my $hr = process_payment($p);
848   return $hr if $hr->{'error'};
849
850   order_renew($p);
851 }
852
853 sub process_prepay {
854
855   my $p = shift;
856
857   my $session = _cache->get($p->{'session_id'})
858     or return { 'error' => "Can't resume session" }; #better error message
859
860   my %return;
861
862   my $custnum = $session->{'custnum'};
863
864   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
865     or return { 'error' => "unknown custnum $custnum" };
866
867   my( $amount, $seconds, $upbytes, $downbytes, $totalbytes ) = ( 0, 0, 0, 0, 0 );
868   my $error = $cust_main->recharge_prepay( $p->{'prepaid_cardnum'},
869                                            \$amount,
870                                            \$seconds,
871                                            \$upbytes,
872                                            \$downbytes,
873                                            \$totalbytes,
874                                          );
875
876   return { 'error' => $error } if $error;
877
878   return { 'error'     => '',
879            'amount'    => $amount,
880            'seconds'   => $seconds,
881            'duration'  => duration_exact($seconds),
882            'upbytes'   => $upbytes,
883            'upload'    => FS::UI::bytecount::bytecount_unexact($upbytes),
884            'downbytes' => $downbytes,
885            'download'  => FS::UI::bytecount::bytecount_unexact($downbytes),
886            'totalbytes'=> $totalbytes,
887            'totalload' => FS::UI::bytecount::bytecount_unexact($totalbytes),
888          };
889
890 }
891
892 sub invoice {
893   my $p = shift;
894   my $session = _cache->get($p->{'session_id'})
895     or return { 'error' => "Can't resume session" }; #better error message
896
897   my $custnum = $session->{'custnum'};
898
899   my $invnum = $p->{'invnum'};
900
901   my $cust_bill = qsearchs('cust_bill', { 'invnum'  => $invnum,
902                                           'custnum' => $custnum } )
903     or return { 'error' => "Can't find invnum" };
904
905   #my %return;
906
907   return { 'error'        => '',
908            'invnum'       => $invnum,
909            'invoice_text' => join('', $cust_bill->print_text ),
910            'invoice_html' => $cust_bill->print_html( { unsquelch_cdr => 1 } ),
911          };
912
913 }
914
915 sub invoice_logo {
916   my $p = shift;
917
918   #sessioning for this?  how do we get the session id to the backend invoice
919   # template so it can add it to the link, blah
920
921   my $agentnum = '';
922   if ( $p->{'invnum'} ) {
923     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $p->{'invnum'} } )
924       or return { 'error' => 'unknown invnum' };
925     $agentnum = $cust_bill->cust_main->agentnum;
926   }
927
928   my $templatename = $p->{'template'} || $p->{'templatename'};
929
930   #false laziness-ish w/view/cust_bill-logo.cgi
931
932   my $conf = new FS::Conf;
933   if ( $templatename =~ /^([^\.\/]*)$/ && $conf->exists("logo_$1.png") ) {
934     $templatename = "_$1";
935   } else {
936     $templatename = '';
937   }
938
939   my $filename = "logo$templatename.png";
940
941   return { 'error'        => '',
942            'logo'         => $conf->config_binary($filename, $agentnum),
943            'content_type' => 'image/png', #should allow gif, jpg too
944          };
945 }
946
947
948 sub list_invoices {
949   my $p = shift;
950   my $session = _cache->get($p->{'session_id'})
951     or return { 'error' => "Can't resume session" }; #better error message
952
953   my $custnum = $session->{'custnum'};
954
955   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
956     or return { 'error' => "unknown custnum $custnum" };
957
958   my @cust_bill = $cust_main->cust_bill;
959
960   return  { 'error'       => '',
961             'invoices'    =>  [ map { { 'invnum' => $_->invnum,
962                                         '_date'  => $_->_date,
963                                         'date'   => time2str("%b %o, %Y", $_->_date),
964                                       }
965                                     } @cust_bill
966                               ]
967           };
968 }
969
970 sub cancel {
971   my $p = shift;
972   my $session = _cache->get($p->{'session_id'})
973     or return { 'error' => "Can't resume session" }; #better error message
974
975   my $custnum = $session->{'custnum'};
976
977   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
978     or return { 'error' => "unknown custnum $custnum" };
979
980   my @errors = $cust_main->cancel( 'quiet'=>1 );
981
982   my $error = scalar(@errors) ? join(' / ', @errors) : '';
983
984   return { 'error' => $error };
985
986 }
987
988 sub list_pkgs {
989   my $p = shift;
990
991   my($context, $session, $custnum) = _custoragent_session_custnum($p);
992   return { 'error' => $session } if $context eq 'error';
993
994   my $search = { 'custnum' => $custnum };
995   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
996   my $cust_main = qsearchs('cust_main', $search )
997     or return { 'error' => "unknown custnum $custnum" };
998
999   my $conf = new FS::Conf;
1000   
1001 # the duplication below is necessary:
1002 # 1. to maintain the current buggy behaviour wrt the cust_pkg and part_pkg
1003 # hashes overwriting each other (setup and no_auto fields). Fixing that is a
1004 # non-backwards-compatible change breaking the software of anyone using the API
1005 # instead of the stock selfservice
1006 # 2. to return cancelled packages as well - for wholesale and non-wholesale
1007   if( $conf->exists('selfservice_server-view-wholesale') ) {
1008     return { 'svcnum'   => $session->{'svcnum'},
1009             'custnum'  => $custnum,
1010             'cust_pkg' => [ map {
1011                           { $_->hash,
1012                             part_pkg => [ map $_->hashref, $_->part_pkg ],
1013                             part_svc =>
1014                               [ map $_->hashref, $_->available_part_svc ],
1015                             cust_svc => 
1016                               [ map { my $ref = { $_->hash,
1017                                                   label => [ $_->label ],
1018                                                 };
1019                                       $ref->{_password} = $_->svc_x->_password
1020                                         if $context eq 'agent'
1021                                         && $conf->exists('agent-showpasswords')
1022                                         && $_->part_svc->svcdb eq 'svc_acct';
1023                                       $ref;
1024                                     } $_->cust_svc
1025                               ],
1026                           };
1027                         } $cust_main->cust_pkg
1028                   ],
1029     'small_custview' =>
1030       small_custview( $cust_main, $conf->config('countrydefault') ),
1031     'wholesale_view' => 1,
1032     'login_svcpart' => [ $conf->config('selfservice_server-login_svcpart') ],
1033     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1034     'lnp' => $conf->exists('svc_phone-lnp'),
1035       };
1036   }
1037
1038   { 'svcnum'   => $session->{'svcnum'},
1039     'custnum'  => $custnum,
1040     'cust_pkg' => [ map {
1041                           { $_->hash,
1042                             $_->part_pkg->hash,
1043                             part_svc =>
1044                               [ map $_->hashref, $_->available_part_svc ],
1045                             cust_svc => 
1046                               [ map { my $ref = { $_->hash,
1047                                                   label => [ $_->label ],
1048                                                 };
1049                                       $ref->{_password} = $_->svc_x->_password
1050                                         if $context eq 'agent'
1051                                         && $conf->exists('agent-showpasswords')
1052                                         && $_->part_svc->svcdb eq 'svc_acct';
1053                                       $ref->{svchash} = { $_->svc_x->hash } if 
1054                                         $_->part_svc->svcdb eq 'svc_phone';
1055                                       $ref->{svchash}->{svcpart} =  $_->part_svc->svcpart
1056                                         if $_->part_svc->svcdb eq 'svc_phone'; # hack
1057                                       $ref;
1058                                     } $_->cust_svc
1059                               ],
1060                           };
1061                         } $cust_main->ncancelled_pkgs
1062                   ],
1063     'small_custview' =>
1064       small_custview( $cust_main, $conf->config('countrydefault') ),
1065   };
1066
1067 }
1068
1069 sub list_svcs {
1070   my $p = shift;
1071
1072   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1073   return { 'error' => $session } if $context eq 'error';
1074
1075   my $search = { 'custnum' => $custnum };
1076   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1077   my $cust_main = qsearchs('cust_main', $search )
1078     or return { 'error' => "unknown custnum $custnum" };
1079
1080   my @cust_svc = ();
1081   #foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1082   foreach my $cust_pkg ( $p->{'ncancelled'} 
1083                          ? $cust_main->ncancelled_pkgs
1084                          : $cust_main->unsuspended_pkgs ) {
1085     next if $session->{'pkgnum'} && $cust_pkg->pkgnum != $session->{'pkgnum'};
1086     push @cust_svc, @{[ $cust_pkg->cust_svc ]}; #@{[ ]} to force array context
1087   }
1088   if ( $p->{'svcdb'} ) {
1089     my $svcdb = ref($p->{'svcdb'}) eq 'HASH'
1090                   ? $p->{'svcdb'}
1091                   : ref($p->{'svcdb'}) eq 'ARRAY'
1092                     ? { map { $_=>1 } @{ $p->{'svcdb'} } }
1093                     : { $p->{'svcdb'} => 1 };
1094     @cust_svc = grep $svcdb->{ $_->part_svc->svcdb }, @cust_svc
1095   }
1096
1097   #@svc_x = sort { $a->domain cmp $b->domain || $a->username cmp $b->username }
1098   #              @svc_x;
1099
1100     my $conf = new FS::Conf;
1101
1102   { 
1103     'svcnum'   => $session->{'svcnum'},
1104     'custnum'  => $custnum,
1105     'date_format' => $conf->config('date_format') || '%m/%d/%Y',
1106     'view_usage_nodomain' => $conf->exists('selfservice-view_usage_nodomain'),
1107     'svcs'     => [
1108       map { 
1109             my $svc_x = $_->svc_x;
1110             my($label, $value) = $_->label;
1111             my $svcdb = $_->part_svc->svcdb;
1112             my $part_pkg = $_->cust_pkg->part_pkg;
1113
1114             my %hash = (
1115               'svcnum' => $_->svcnum,
1116               'svcdb'  => $svcdb,
1117               'label'  => $label,
1118               'value'  => $value,
1119             );
1120
1121             if ( $svcdb eq 'svc_acct' ) {
1122               %hash = (
1123                 %hash,
1124                 'username'   => $svc_x->username,
1125                 'email'      => $svc_x->email,
1126                 'seconds'    => $svc_x->seconds,
1127                 'upbytes'    => display_bytecount($svc_x->upbytes),
1128                 'downbytes'  => display_bytecount($svc_x->downbytes),
1129                 'totalbytes' => display_bytecount($svc_x->totalbytes),
1130
1131                 'recharge_amount'  => $part_pkg->option('recharge_amount',1),
1132                 'recharge_seconds' => $part_pkg->option('recharge_seconds',1),
1133                 'recharge_upbytes'    =>
1134                   display_bytecount($part_pkg->option('recharge_upbytes',1)),
1135                 'recharge_downbytes'  =>
1136                   display_bytecount($part_pkg->option('recharge_downbytes',1)),
1137                 'recharge_totalbytes' =>
1138                   display_bytecount($part_pkg->option('recharge_totalbytes',1)),
1139                 # more...
1140               );
1141
1142             } elsif ( $svcdb eq 'svc_phone' || $svcdb eq 'svc_port' ) {
1143               %hash = (
1144                 %hash,
1145               );
1146             }
1147
1148             \%hash;
1149           }
1150           @cust_svc
1151     ],
1152   };
1153
1154 }
1155
1156 sub port_graph {
1157   my $p = shift;
1158   _usage_details( \&_port_graph, $p,
1159                   'svcdb' => 'svc_port',
1160                 );
1161 }
1162
1163 sub _port_graph {
1164   my($svc_port, $begin, $end) = @_;
1165   my @usage = ();
1166   my $pngOrError = $svc_port->graph_png( start=>$begin, end=> $end );
1167   push @usage, { 'png' => $pngOrError };
1168   (@usage);
1169 }
1170
1171 sub _list_svc_usage {
1172   my($svc_acct, $begin, $end) = @_;
1173   my @usage = ();
1174   foreach my $part_export ( 
1175     map { qsearch ( 'part_export', { 'exporttype' => $_ } ) }
1176     qw( sqlradius sqlradius_withdomain )
1177   ) {
1178     push @usage, @ { $part_export->usage_sessions($begin, $end, $svc_acct) };
1179   }
1180   (@usage);
1181 }
1182
1183 sub list_svc_usage {
1184   _usage_details(\&_list_svc_usage, @_);
1185 }
1186
1187 sub _list_support_usage {
1188   my($svc_acct, $begin, $end) = @_;
1189   my @usage = ();
1190   foreach ( grep { $begin <= $_->_date && $_->_date <= $end }
1191             qsearch('acct_rt_transaction', { 'svcnum' => $svc_acct->svcnum })
1192           ) {
1193     push @usage, { 'seconds'  => $_->seconds,
1194                    'support'  => $_->support,
1195                    '_date'    => $_->_date,
1196                    'id'       => $_->transaction_id,
1197                    'creator'  => $_->creator,
1198                    'subject'  => $_->subject,
1199                    'status'   => $_->status,
1200                    'ticketid' => $_->ticketid,
1201                  };
1202   }
1203   (@usage);
1204 }
1205
1206 sub list_support_usage {
1207   _usage_details(\&_list_support_usage, @_);
1208 }
1209
1210 sub _list_cdr_usage {
1211   my($svc_phone, $begin, $end) = @_;
1212   map [ $_->downstream_csv('format' => 'default', 'keeparray' => 1) ], #XXX config for format
1213                        $svc_phone->get_cdrs( 'begin'=>$begin, 'end'=>$end, );
1214 }
1215
1216 sub list_cdr_usage {
1217   my $p = shift;
1218   _usage_details( \&_list_cdr_usage, $p,
1219                   'svcdb' => 'svc_phone',
1220                 );
1221 }
1222
1223 sub _usage_details {
1224   my($callback, $p, %opt) = @_;
1225
1226   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1227   return { 'error' => $session } if $context eq 'error';
1228
1229   my $search = { 'svcnum' => $p->{'svcnum'} };
1230   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1231
1232   my $svcdb = $opt{'svcdb'} || 'svc_acct';
1233
1234   my $svc_x = qsearchs( $svcdb, $search );
1235   return { 'error' => 'No service selected in list_svc_usage' } 
1236     unless $svc_x;
1237
1238   my $header = $svcdb eq 'svc_phone'
1239                  ? [ split(',', FS::cdr::invoice_header('default') ) ]  #XXX
1240                  : [];
1241
1242   my $cust_pkg = $svc_x->cust_svc->cust_pkg;
1243   my $freq     = $cust_pkg->part_pkg->freq;
1244   my $start    = $cust_pkg->setup;
1245   #my $end      = $cust_pkg->bill; # or time?
1246   my $end      = time;
1247
1248   unless ( $p->{beginning} ) {
1249     $p->{beginning} = $cust_pkg->last_bill;
1250     $p->{ending}    = $end;
1251   }
1252
1253   my (@usage) = &$callback($svc_x, $p->{beginning}, $p->{ending});
1254
1255   #kinda false laziness with FS::cust_main::bill, but perhaps
1256   #we should really change this bit to DateTime and DateTime::Duration
1257   #
1258   #change this bit to use Date::Manip? CAREFUL with timezones (see
1259   # mailing list archive)
1260   my ($nsec,$nmin,$nhour,$nmday,$nmon,$nyear) =
1261     (localtime($p->{ending}) )[0,1,2,3,4,5];
1262   my ($psec,$pmin,$phour,$pmday,$pmon,$pyear) =
1263     (localtime($p->{beginning}) )[0,1,2,3,4,5];
1264
1265   if ( $freq =~ /^\d+$/ ) {
1266     $nmon += $freq;
1267     until ( $nmon < 12 ) { $nmon -= 12; $nyear++; }
1268     $pmon -= $freq;
1269     until ( $pmon >= 0 ) { $pmon += 12; $pyear--; }
1270   } elsif ( $freq =~ /^(\d+)w$/ ) {
1271     my $weeks = $1;
1272     $nmday += $weeks * 7;
1273     $pmday -= $weeks * 7;
1274   } elsif ( $freq =~ /^(\d+)d$/ ) {
1275     my $days = $1;
1276     $nmday += $days;
1277     $pmday -= $days;
1278   } elsif ( $freq =~ /^(\d+)h$/ ) {
1279     my $hours = $1;
1280     $nhour += $hours;
1281     $phour -= $hours;
1282   } else {
1283     return { 'error' => "unparsable frequency: ". $freq };
1284   }
1285   
1286   my $previous  = timelocal_nocheck($psec,$pmin,$phour,$pmday,$pmon,$pyear);
1287   my $next      = timelocal_nocheck($nsec,$nmin,$nhour,$nmday,$nmon,$nyear);
1288
1289   { 
1290     'error'     => '',
1291     'svcnum'    => $p->{svcnum},
1292     'beginning' => $p->{beginning},
1293     'ending'    => $p->{ending},
1294     'previous'  => ($previous > $start) ? $previous : $start,
1295     'next'      => ($next < $end) ? $next : $end,
1296     'header'    => $header,
1297     'usage'     => \@usage,
1298   };
1299 }
1300
1301 sub order_pkg {
1302   my $p = shift;
1303
1304   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1305   return { 'error' => $session } if $context eq 'error';
1306
1307   my $search = { 'custnum' => $custnum };
1308   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1309   my $cust_main = qsearchs('cust_main', $search )
1310     or return { 'error' => "unknown custnum $custnum" };
1311
1312   my $status = $cust_main->status;
1313   #false laziness w/ClientAPI/Signup.pm
1314
1315   my $cust_pkg = new FS::cust_pkg ( {
1316     'custnum' => $custnum,
1317     'pkgpart' => $p->{'pkgpart'},
1318   } );
1319   my $error = $cust_pkg->check;
1320   return { 'error' => $error } if $error;
1321
1322   my @svc = ();
1323   unless ( $p->{'svcpart'} eq 'none' ) {
1324
1325     my $svcdb;
1326     my $svcpart = '';
1327     if ( $p->{'svcpart'} =~ /^(\d+)$/ ) {
1328       $svcpart = $1;
1329       my $part_svc = qsearchs('part_svc', { 'svcpart' => $svcpart } );
1330       return { 'error' => "Unknown svcpart $svcpart" } unless $part_svc;
1331       $svcdb = $part_svc->svcdb;
1332     } else {
1333       $svcdb = 'svc_acct';
1334     }
1335     $svcpart ||= $cust_pkg->part_pkg->svcpart($svcdb);
1336
1337     my %fields = (
1338       'svc_acct'     => [ qw( username domsvc _password sec_phrase popnum ) ],
1339       'svc_domain'   => [ qw( domain ) ],
1340       'svc_phone'    => [ qw( phonenum pin sip_password phone_name ) ],
1341       'svc_external' => [ qw( id title ) ],
1342       'svc_pbx'      => [ qw( id title ) ],
1343     );
1344   
1345     my $svc_x = "FS::$svcdb"->new( {
1346       'svcpart'   => $svcpart,
1347       map { $_ => $p->{$_} } @{$fields{$svcdb}}
1348     } );
1349     
1350     if ( $svcdb eq 'svc_acct' && exists($p->{"snarf_machine1"}) ) {
1351       my @acct_snarf;
1352       my $snarfnum = 1;
1353       while ( length($p->{"snarf_machine$snarfnum"}) ) {
1354         my $acct_snarf = new FS::acct_snarf ( {
1355           'machine'   => $p->{"snarf_machine$snarfnum"},
1356           'protocol'  => $p->{"snarf_protocol$snarfnum"},
1357           'username'  => $p->{"snarf_username$snarfnum"},
1358           '_password' => $p->{"snarf_password$snarfnum"},
1359         } );
1360         $snarfnum++;
1361         push @acct_snarf, $acct_snarf;
1362       }
1363       $svc_x->child_objects( \@acct_snarf );
1364     }
1365     
1366     my $y = $svc_x->setdefault; # arguably should be in new method
1367     return { 'error' => $y } if $y && !ref($y);
1368   
1369     $error = $svc_x->check;
1370     return { 'error' => $error } if $error;
1371
1372     push @svc, $svc_x;
1373
1374   }
1375
1376   use Tie::RefHash;
1377   tie my %hash, 'Tie::RefHash';
1378   %hash = ( $cust_pkg => \@svc );
1379   #msgcat
1380   $error = $cust_main->order_pkgs( \%hash, 'noexport' => 1 );
1381   return { 'error' => $error } if $error;
1382
1383   my $conf = new FS::Conf;
1384   if ( $conf->exists('signup_server-realtime') ) {
1385
1386     my $bill_error = _do_bop_realtime( $cust_main, $status );
1387
1388     if ($bill_error) {
1389       $cust_pkg->cancel('quiet'=>1);
1390       return $bill_error;
1391     } else {
1392       $cust_pkg->reexport;
1393     }
1394
1395   } else {
1396     $cust_pkg->reexport;
1397   }
1398
1399   my $svcnum = $svc[0] ? $svc[0]->svcnum : '';
1400
1401   return { error=>'', pkgnum=>$cust_pkg->pkgnum, svcnum=>$svcnum };
1402
1403 }
1404
1405 sub change_pkg {
1406   my $p = shift;
1407
1408   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1409   return { 'error' => $session } if $context eq 'error';
1410
1411   my $search = { 'custnum' => $custnum };
1412   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1413   my $cust_main = qsearchs('cust_main', $search )
1414     or return { 'error' => "unknown custnum $custnum" };
1415
1416   my $status = $cust_main->status;
1417   my $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $p->{pkgnum} } )
1418     or return { 'error' => "unknown package $p->{pkgnum}" };
1419
1420   my @newpkg;
1421   my $error = FS::cust_pkg::order( $custnum,
1422                                    [$p->{pkgpart}],
1423                                    [$p->{pkgnum}],
1424                                    \@newpkg,
1425                                  );
1426
1427   my $conf = new FS::Conf;
1428   if ( $conf->exists('signup_server-realtime') ) {
1429
1430     my $bill_error = _do_bop_realtime( $cust_main, $status );
1431
1432     if ($bill_error) {
1433       $newpkg[0]->suspend;
1434       return $bill_error;
1435     } else {
1436       $newpkg[0]->reexport;
1437     }
1438
1439   } else {  
1440     $newpkg[0]->reexport;
1441   }
1442
1443   return { error => '', pkgnum => $cust_pkg->pkgnum };
1444
1445 }
1446
1447 sub order_recharge {
1448   my $p = shift;
1449
1450   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1451   return { 'error' => $session } if $context eq 'error';
1452
1453   my $search = { 'custnum' => $custnum };
1454   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1455   my $cust_main = qsearchs('cust_main', $search )
1456     or return { 'error' => "unknown custnum $custnum" };
1457
1458   my $status = $cust_main->status;
1459   my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $p->{'svcnum'} } )
1460     or return { 'error' => "unknown service " . $p->{'svcnum'} };
1461
1462   my $svc_x = $cust_svc->svc_x;
1463   my $part_pkg = $cust_svc->cust_pkg->part_pkg;
1464
1465   my %vhash =
1466     map { $_ =~ /^recharge_(.*)$/; $1, $part_pkg->option($_, 1) } 
1467     qw ( recharge_seconds recharge_upbytes recharge_downbytes
1468          recharge_totalbytes );
1469   my $amount = $part_pkg->option('recharge_amount', 1); 
1470   
1471   my ($l, $v, $d) = $cust_svc->label;  # blah
1472   my $pkg = "Recharge $v"; 
1473
1474   my $bill_error = $cust_main->charge($amount, $pkg,
1475      "time: $vhash{seconds}, up: $vhash{upbytes}," . 
1476      "down: $vhash{downbytes}, total: $vhash{totalbytes}",
1477      $part_pkg->taxclass); #meh
1478
1479   my $conf = new FS::Conf;
1480   if ( $conf->exists('signup_server-realtime') && !$bill_error ) {
1481
1482     $bill_error = _do_bop_realtime( $cust_main, $status );
1483
1484     if ($bill_error) {
1485       return $bill_error;
1486     } else {
1487       my $error = $svc_x->recharge (\%vhash);
1488       return { 'error' => $error } if $error;
1489     }
1490
1491   } else {  
1492     my $error = $bill_error;
1493     $error ||= $svc_x->recharge (\%vhash);
1494     return { 'error' => $error } if $error;
1495   }
1496
1497   return { error => '', svc => $cust_svc->part_svc->svc };
1498
1499 }
1500
1501 sub _do_bop_realtime {
1502   my ($cust_main, $status) = (shift, shift);
1503
1504     my $old_balance = $cust_main->balance;
1505
1506     my $bill_error =    $cust_main->bill
1507                      || $cust_main->apply_payments_and_credits
1508                      || $cust_main->realtime_collect('selfservice' => 1);
1509
1510     if (    $cust_main->balance > $old_balance
1511          && $cust_main->balance > 0
1512          && ( $cust_main->payby !~ /^(BILL|DCRD|DCHK)$/ ?
1513               1 : $status eq 'suspended' ) ) {
1514       #this makes sense.  credit is "un-doing" the invoice
1515       my $conf = new FS::Conf;
1516       $cust_main->credit( sprintf("%.2f", $cust_main->balance - $old_balance ),
1517                           'self-service decline',
1518                           'reason_type' => $conf->config('signup_credit_type'),
1519                         );
1520       $cust_main->apply_credits( 'order' => 'newest' );
1521
1522       return { 'error' => '_decline', 'bill_error' => $bill_error };
1523     }
1524
1525     '';
1526 }
1527
1528 sub renew_info {
1529   my $p = shift;
1530
1531   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1532   return { 'error' => $session } if $context eq 'error';
1533
1534   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1535     or return { 'error' => "unknown custnum $custnum" };
1536
1537   my @cust_pkg = sort { $a->bill <=> $b->bill }
1538                  grep { $_->part_pkg->freq ne '0' }
1539                  $cust_main->ncancelled_pkgs;
1540
1541   #return { 'error' => 'No active packages to renew.' } unless @cust_pkg;
1542
1543   my $total = $cust_main->balance;
1544
1545   my @array = map {
1546                     my $bill = $_->bill;
1547                     $total += $_->part_pkg->base_recur($_, \$bill);
1548                     my $renew_date = $_->part_pkg->add_freq($_->bill);
1549                     {
1550                       'pkgnum'             => $_->pkgnum,
1551                       'amount'             => sprintf('%.2f', $total),
1552                       'bill_date'          => $_->bill,
1553                       'bill_date_pretty'   => time2str('%x', $_->bill),
1554                       'renew_date'         => $renew_date,
1555                       'renew_date_pretty'  => time2str('%x', $renew_date),
1556                       'expire_date'        => $_->expire,
1557                       'expire_date_pretty' => time2str('%x', $_->expire),
1558                     };
1559                   }
1560                   @cust_pkg;
1561
1562   return { 'dates' => \@array };
1563
1564 }
1565
1566 sub payment_info_renew_info {
1567   my $p = shift;
1568   my $renew_info   = renew_info($p);
1569   my $payment_info = payment_info($p);
1570   return { %$renew_info,
1571            %$payment_info,
1572          };
1573 }
1574
1575 sub order_renew {
1576   my $p = shift;
1577
1578   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1579   return { 'error' => $session } if $context eq 'error';
1580
1581   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1582     or return { 'error' => "unknown custnum $custnum" };
1583
1584   my $date = $p->{'date'};
1585
1586   my $now = time;
1587
1588   #freeside-daily -n -d $date fs_daily $custnum
1589   $cust_main->bill_and_collect( 'time'         => $date,
1590                                 'invoice_time' => $now,
1591                                 'actual_time'  => $now,
1592                                 'check_freq'   => '1d',
1593                               );
1594
1595   return { 'error' => '' };
1596
1597 }
1598
1599 sub suspend_pkg {
1600   my $p = shift;
1601   my $session = _cache->get($p->{'session_id'})
1602     or return { 'error' => "Can't resume session" }; #better error message
1603
1604   my $custnum = $session->{'custnum'};
1605
1606   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1607     or return { 'error' => "unknown custnum $custnum" };
1608
1609   my $conf = new FS::Conf;
1610   my $reasonnum = 
1611     $conf->config('selfservice-self_suspend_reason', $cust_main->agentnum)
1612       or return { 'error' => 'Permission denied' };
1613
1614   my $pkgnum = $p->{'pkgnum'};
1615
1616   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1617                                         'pkgnum'  => $pkgnum,   } )
1618     or return { 'error' => "unknown pkgnum $pkgnum" };
1619
1620   my $error = $cust_pkg->suspend(reason => $reasonnum);
1621   return { 'error' => $error };
1622
1623 }
1624
1625 sub cancel_pkg {
1626   my $p = shift;
1627   my $session = _cache->get($p->{'session_id'})
1628     or return { 'error' => "Can't resume session" }; #better error message
1629
1630   my $custnum = $session->{'custnum'};
1631
1632   my $cust_main = qsearchs('cust_main', { 'custnum' => $custnum } )
1633     or return { 'error' => "unknown custnum $custnum" };
1634
1635   my $pkgnum = $p->{'pkgnum'};
1636
1637   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1638                                         'pkgnum'  => $pkgnum,   } )
1639     or return { 'error' => "unknown pkgnum $pkgnum" };
1640
1641   my $error = $cust_pkg->cancel('quiet' => 1);
1642   return { 'error' => $error };
1643
1644 }
1645
1646 sub provision_phone {
1647  my $p = shift;
1648  my @bulkdid;
1649  @bulkdid = @{$p->{'bulkdid'}} if $p->{'bulkdid'};
1650
1651  if($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/){
1652       my($context, $session, $custnum) = _custoragent_session_custnum($p);
1653       return { 'error' => $session } if $context eq 'error';
1654     
1655       my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
1656       return { 'error' => 'service not found' } unless $svc_phone;
1657       return { 'error' => 'invalid svcnum' } 
1658         if $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum != $custnum;
1659
1660       $svc_phone->email($p->{'email'}) 
1661         if $svc_phone->email ne $p->{'email'} && $p->{'email'} =~ /^([\w\.\d@]+|)$/;
1662       $svc_phone->forwarddst($p->{'forwarddst'}) 
1663         if $svc_phone->forwarddst ne $p->{'forwarddst'} 
1664             && $p->{'forwarddst'} =~ /^(\d+|)$/;
1665       return { 'error' => $svc_phone->replace };
1666  }
1667
1668 # single DID LNP
1669  unless($p->{'lnp'}) {
1670     $p->{'lnp_desired_due_date'} = parse_datetime($p->{'lnp_desired_due_date'});
1671     $p->{'lnp_status'} = "portingin";
1672     return _provision( 'FS::svc_phone',
1673                   [qw(lnp_desired_due_date lnp_other_provider 
1674                     lnp_other_provider_account phonenum countrycode lnp_status)],
1675                   [qw(phonenum countrycode)],
1676                   $p,
1677                   @_
1678                 );
1679  }
1680
1681 # single DID order
1682  unless (scalar(@bulkdid)) {
1683     return _provision( 'FS::svc_phone',
1684                   [qw(phonenum countrycode)],
1685                   [qw(phonenum countrycode)],
1686                   $p,
1687                   @_
1688                 );
1689  }
1690
1691 # bulk DID order case
1692   my $error;
1693   foreach my $did ( @bulkdid ) {
1694     $did =~ s/[^0-9]//g;
1695     $error = _provision( 'FS::svc_phone',
1696               [qw(phonenum countrycode)],
1697               [qw(phonenum countrycode)],
1698               {
1699                 'pkgnum' => $p->{'pkgnum'},
1700                 'svcpart' => $p->{'svcpart'},
1701                 'phonenum' => $did,
1702                 'countrycode' => $p->{'countrycode'},
1703                 'session_id' => $p->{'session_id'},
1704               }
1705             );
1706     return $error if ($error->{'error'} && length($error->{'error'}) > 1);
1707   }
1708   { 'bulkdid' => [ @bulkdid ], 'svc' => $error->{'svc'} }
1709 }
1710
1711 sub provision_acct {
1712   my $p = shift;
1713   warn "provision_acct called\n"
1714     if $DEBUG;
1715
1716   return { 'error' => gettext('passwords_dont_match') }
1717     if $p->{'_password'} ne $p->{'_password2'};
1718   return { 'error' => gettext('empty_password') }
1719     unless length($p->{'_password'});
1720  
1721   if ($p->{'domsvc'}) {
1722     my %domains = domain_select_hash FS::svc_acct(map { $_ => $p->{$_} }
1723                                                   qw ( svcpart pkgnum ) );
1724     return { 'error' => gettext('invalid_domain') }
1725       unless ($domains{$p->{'domsvc'}});
1726   }
1727
1728   warn "provision_acct calling _provision\n"
1729     if $DEBUG;
1730   _provision( 'FS::svc_acct',
1731               [qw(username _password domsvc)],
1732               [qw(username _password domsvc)],
1733               $p,
1734               @_
1735             );
1736 }
1737
1738 sub provision_external {
1739   my $p = shift;
1740   #_provision( 'FS::svc_external', [qw(id title)], [qw(id title)], $p, @_ );
1741   _provision( 'FS::svc_external',
1742               [],
1743               [qw(id title)],
1744               $p,
1745               @_
1746             );
1747 }
1748
1749 sub _provision {
1750   my( $class, $fields, $return_fields, $p ) = splice(@_, 0, 4);
1751   warn "_provision called for $class\n"
1752     if $DEBUG;
1753
1754   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1755   return { 'error' => $session } if $context eq 'error';
1756
1757   my $search = { 'custnum' => $custnum };
1758   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1759   my $cust_main = qsearchs('cust_main', $search )
1760     or return { 'error' => "unknown custnum $custnum" };
1761
1762   my $pkgnum = $p->{'pkgnum'};
1763
1764   warn "searching for custnum $custnum pkgnum $pkgnum\n"
1765     if $DEBUG;
1766   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1767                                         'pkgnum'  => $pkgnum,
1768                                                                } )
1769     or return { 'error' => "unknown pkgnum $pkgnum" };
1770
1771   warn "searching for svcpart ". $p->{'svcpart'}. "\n"
1772     if $DEBUG;
1773   my $part_svc = qsearchs('part_svc', { 'svcpart' => $p->{'svcpart'} } )
1774     or return { 'error' => "unknown svcpart $p->{'svcpart'}" };
1775
1776   warn "creating $class record\n"
1777     if $DEBUG;
1778   my $svc_x = $class->new( {
1779     'pkgnum'  => $p->{'pkgnum'},
1780     'svcpart' => $p->{'svcpart'},
1781     map { $_ => $p->{$_} } @$fields
1782   } );
1783   warn "inserting $class record\n"
1784     if $DEBUG;
1785   my $error = $svc_x->insert;
1786
1787   unless ( $error ) {
1788     warn "finding inserted record for svcnum ". $svc_x->svcnum. "\n"
1789       if $DEBUG;
1790     $svc_x = qsearchs($svc_x->table, { 'svcnum' => $svc_x->svcnum })
1791   }
1792
1793   my $return = { 'svc'   => $part_svc->svc,
1794                  'error' => $error,
1795                  map { $_ => $svc_x->get($_) } @$return_fields
1796                };
1797   warn "_provision returning ". Dumper($return). "\n"
1798     if $DEBUG;
1799   return $return;
1800
1801 }
1802
1803 sub part_svc_info {
1804   my $p = shift;
1805
1806   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1807   return { 'error' => $session } if $context eq 'error';
1808
1809   my $search = { 'custnum' => $custnum };
1810   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1811   my $cust_main = qsearchs('cust_main', $search )
1812     or return { 'error' => "unknown custnum $custnum" };
1813
1814   my $pkgnum = $p->{'pkgnum'};
1815
1816   my $cust_pkg = qsearchs('cust_pkg', { 'custnum' => $custnum,
1817                                         'pkgnum'  => $pkgnum,
1818                                                                } )
1819     or return { 'error' => "unknown pkgnum $pkgnum" };
1820
1821   my $svcpart = $p->{'svcpart'};
1822
1823   my $pkg_svc = qsearchs('pkg_svc', { 'pkgpart' => $cust_pkg->pkgpart,
1824                                       'svcpart' => $svcpart,           } )
1825     or return { 'error' => "unknown svcpart $svcpart for pkgnum $pkgnum" };
1826   my $part_svc = $pkg_svc->part_svc;
1827
1828   my $conf = new FS::Conf;
1829
1830   my $ret = {
1831     'svc'     => $part_svc->svc,
1832     'svcdb'   => $part_svc->svcdb,
1833     'pkgnum'  => $pkgnum,
1834     'svcpart' => $svcpart,
1835     'custnum' => $custnum,
1836
1837     'security_phrase' => 0, #XXX !
1838     'svc_acct_pop'    => [], #XXX !
1839     'popnum'          => '',
1840     'init_popstate'   => '',
1841     'popac'           => '',
1842     'acstate'         => '',
1843
1844     'small_custview' =>
1845       small_custview( $cust_main, $conf->config('countrydefault') ),
1846
1847   };
1848
1849   if ($p->{'svcnum'} && $p->{'svcnum'} =~ /^\d+$/ 
1850                      && $ret->{'svcdb'} eq 'svc_phone') {
1851         $ret->{'svcnum'} = $p->{'svcnum'};
1852         my $svc_phone = qsearchs('svc_phone', { svcnum => $p->{'svcnum'} });
1853         if ( $svc_phone && $svc_phone->cust_svc->cust_pkg->custnum == $custnum ) {
1854             $ret->{'email'} = $svc_phone->email;
1855             $ret->{'forwarddst'} = $svc_phone->forwarddst;
1856         }
1857   }
1858
1859   $ret;
1860 }
1861
1862 sub unprovision_svc {
1863   my $p = shift;
1864
1865   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1866   return { 'error' => $session } if $context eq 'error';
1867
1868   my $search = { 'custnum' => $custnum };
1869   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1870   my $cust_main = qsearchs('cust_main', $search )
1871     or return { 'error' => "unknown custnum $custnum" };
1872
1873   my $svcnum = $p->{'svcnum'};
1874
1875   my $cust_svc = qsearchs('cust_svc', { 'svcnum'  => $svcnum, } )
1876     or return { 'error' => "unknown svcnum $svcnum" };
1877
1878   return { 'error' => "Service $svcnum does not belong to customer $custnum" }
1879     unless $cust_svc->cust_pkg->custnum == $custnum;
1880
1881   my $conf = new FS::Conf;
1882
1883   return { 'svc'   => $cust_svc->part_svc->svc,
1884            'error' => $cust_svc->cancel,
1885            'small_custview' =>
1886              small_custview( $cust_main, $conf->config('countrydefault') ),
1887          };
1888
1889 }
1890
1891 sub myaccount_passwd {
1892   my $p = shift;
1893   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1894   return { 'error' => $session } if $context eq 'error';
1895
1896   return { 'error' => "New passwords don't match." }
1897     if $p->{'new_password'} ne $p->{'new_password2'};
1898
1899   return { 'error' => 'Enter new password' }
1900     unless length($p->{'new_password'});
1901
1902   #my $search = { 'custnum' => $custnum };
1903   #$search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1904   $custnum =~ /^(\d+)$/ or die "illegal custnum";
1905   my $search = " AND custnum = $1";
1906   $search .= " AND agentnum = ". $session->{'agentnum'} if $context eq 'agent';
1907
1908   my $svc_acct = qsearchs( {
1909     'table'     => 'svc_acct',
1910     'addl_from' => 'LEFT JOIN cust_svc  USING ( svcnum  ) '.
1911                    'LEFT JOIN cust_pkg  USING ( pkgnum  ) '.
1912                    'LEFT JOIN cust_main USING ( custnum ) ',
1913     'hashref'   => { 'svcnum' => $p->{'svcnum'}, },
1914     'extra_sql' => $search, #important
1915   } )
1916     or return { 'error' => "Service not found" };
1917
1918   $svc_acct->_password($p->{'new_password'});
1919   my $error = $svc_acct->replace();
1920
1921   my($label, $value) = $svc_acct->cust_svc->label;
1922
1923   return { 'error' => $error,
1924            'label' => $label,
1925            'value' => $value,
1926          };
1927
1928 }
1929
1930 sub create_ticket {
1931   my $p = shift;
1932   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1933   return { 'error' => $session } if $context eq 'error';
1934
1935   warn "$me create_ticket: initializing ticket system\n" if $DEBUG;
1936   FS::TicketSystem->init();
1937
1938   my $conf = new FS::Conf;
1939   my $queue = $p->{'queue'}
1940               || $conf->config('ticket_system-selfservice_queueid')
1941               || $conf->config('ticket_system-default_queueid');
1942
1943   warn "$me create_ticket: creating ticket\n" if $DEBUG;
1944   my $err_or_ticket = FS::TicketSystem->create_ticket(
1945     '', #create RT session based on FS CurrentUser (fs_selfservice)
1946     'queue'   => $queue,
1947     'custnum' => $custnum,
1948     'svcnum'  => $session->{'svcnum'},
1949     map { $_ => $p->{$_} } qw( requestor cc subject message mime_type )
1950   );
1951
1952   if ( ref($err_or_ticket) ) {
1953     warn "$me create_ticket: successful: ". $err_or_ticket->id. "\n"
1954       if $DEBUG;
1955     return { 'error'     => '',
1956              'ticket_id' => $err_or_ticket->id,
1957            };
1958   } else {
1959     warn "$me create_ticket: unsuccessful: $err_or_ticket\n"
1960       if $DEBUG;
1961     return { 'error' => $err_or_ticket };
1962   }
1963
1964
1965 }
1966
1967 sub did_report {
1968   my $p = shift;
1969   my($context, $session, $custnum) = _custoragent_session_custnum($p);
1970   return { 'error' => $session } if $context eq 'error';
1971  
1972   return { error => 'requested format not implemented' } 
1973     unless ($p->{'format'} eq 'csv' || $p->{'format'} eq 'xls');
1974
1975   my $conf = new FS::Conf;
1976   my $age_threshold = 0;
1977   $age_threshold = time() - $conf->config('selfservice-recent-did-age')
1978     if ($p->{'recentonly'} && $conf->exists('selfservice-recent-did-age'));
1979
1980   my $search = { 'custnum' => $custnum };
1981   $search->{'agentnum'} = $session->{'agentnum'} if $context eq 'agent';
1982   my $cust_main = qsearchs('cust_main', $search )
1983     or return { 'error' => "unknown custnum $custnum" };
1984
1985 # does it make more sense to just run one sql query for this instead of all the
1986 # insanity below? would increase performance greately for large data sets?
1987   my @svc_phone = ();
1988   foreach my $cust_pkg ( $cust_main->ncancelled_pkgs ) {
1989         my @part_svc = $cust_pkg->part_svc;
1990         foreach my $part_svc ( @part_svc ) {
1991             if($part_svc->svcdb eq 'svc_phone'){
1992                 my @cust_pkg_svc = @{$part_svc->cust_pkg_svc};
1993                 foreach my $cust_pkg_svc ( @cust_pkg_svc ) {
1994                     push @svc_phone, $cust_pkg_svc->svc_x
1995                         if $cust_pkg_svc->date_inserted >= $age_threshold;
1996                 }
1997             }
1998         }
1999   }
2000
2001   my $csv;
2002   my $xls;
2003   my($xls_r,$xls_c) = (0,0);
2004   my $xls_workbook;
2005   my $content = '';
2006   my @fields = qw( countrycode phonenum pin sip_password phone_name );
2007   if($p->{'format'} eq 'csv') {
2008     $csv = new Text::CSV_XS { 'always_quote' => 1,
2009                                  'eol'          => "\n",
2010                                 };
2011     return { 'error' => 'Unable to create CSV' } unless $csv->combine(@fields);
2012     $content .= $csv->string;
2013   }
2014   elsif($p->{'format'} eq 'xls') {
2015     my $XLS1 = new IO::Scalar \$content;
2016     $xls_workbook = Spreadsheet::WriteExcel->new($XLS1) 
2017         or return { 'error' => "Error opening .xls file: $!" };
2018     $xls = $xls_workbook->add_worksheet('DIDs');
2019     foreach ( @fields ) {
2020         $xls->write(0,$xls_c++,$_);
2021     }
2022     $xls_r++;
2023   }
2024
2025   foreach my $svc_phone ( @svc_phone ) {
2026     my @cols = map { $svc_phone->$_ } @fields;
2027     if($p->{'format'} eq 'csv') {
2028         return { 'error' => 'Unable to create CSV' } 
2029             unless $csv->combine(@cols);
2030         $content .= $csv->string;
2031     }
2032     elsif($p->{'format'} eq 'xls') {
2033         $xls_c = 0;
2034         foreach ( @cols ) {
2035             $xls->write($xls_r,$xls_c++,$_);
2036         }
2037         $xls_r++;
2038     }
2039   }
2040
2041   $xls_workbook->close() if $p->{'format'} eq 'xls';
2042   
2043   { content => $content, format => $p->{'format'}, };
2044 }
2045
2046 sub get_ticket {
2047   my $p = shift;
2048   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2049   return { 'error' => $session } if $context eq 'error';
2050
2051   warn "$me get_ticket: initializing ticket system\n" if $DEBUG;
2052   FS::TicketSystem->init();
2053   return { 'error' => 'get_ticket configuration error' }
2054     if $FS::TicketSystem::system ne 'RT_Internal';
2055
2056   # check existence and ownership as part of this
2057   warn "$me get_ticket: fetching ticket\n" if $DEBUG;
2058   my $rt_session = FS::TicketSystem->session('');
2059   my $Ticket = FS::TicketSystem->get_ticket_object(
2060     $rt_session, 
2061     ticket_id => $p->{'ticket_id'},
2062     custnum => $custnum
2063   );
2064   return { 'error' => 'ticket not found' } if !$Ticket;
2065
2066   if ( length( $p->{'subject'} || '' ) ) {
2067     # subject change
2068     if ( $p->{'subject'} ne $Ticket->Subject ) {
2069       my ($val, $msg) = $Ticket->SetSubject($p->{'subject'});
2070       return { 'error' => "unable to set subject: $msg" } if !$val;
2071     }
2072   }
2073
2074   if(length($p->{'reply'})) {
2075     my @err_or_res = FS::TicketSystem->correspond_ticket(
2076       $rt_session,
2077       'ticket_id' => $p->{'ticket_id'},
2078       'content' => $p->{'reply'},
2079     );
2080
2081     return { 'error' => 'unable to reply to ticket' } 
2082     unless ( $err_or_res[0] != 0 && defined $err_or_res[2] );
2083   }
2084
2085   warn "$me get_ticket: getting ticket history\n" if $DEBUG;
2086   my $err_or_ticket = FS::TicketSystem->get_ticket(
2087     $rt_session,
2088     'ticket_id' => $p->{'ticket_id'},
2089   );
2090
2091   if ( !ref($err_or_ticket) ) { # there is no way this should ever happen
2092     warn "$me get_ticket: unsuccessful: $err_or_ticket\n"
2093       if $DEBUG;
2094     return { 'error' => $err_or_ticket };
2095   }
2096
2097   my @custs = @{$err_or_ticket->{'custs'}};
2098   my @txns = @{$err_or_ticket->{'txns'}};
2099   my @filtered_txns;
2100
2101   # superseded by check in get_ticket_object
2102   #return { 'error' => 'invalid ticket requested' } 
2103   #unless grep($_ eq $custnum, @custs);
2104
2105   foreach my $txn ( @txns ) {
2106     push @filtered_txns, $txn 
2107     if ($txn->{'type'} eq 'EmailRecord' 
2108       || $txn->{'type'} eq 'Correspond'
2109       || $txn->{'type'} eq 'Create');
2110   }
2111
2112   warn "$me get_ticket: successful: \n"
2113   if $DEBUG;
2114   return { 'error'     => '',
2115     'transactions' => \@filtered_txns,
2116     'ticket_fields' => $err_or_ticket->{'fields'},
2117     'ticket_id' => $p->{'ticket_id'},
2118   };
2119 }
2120
2121 sub adjust_ticket_priority {
2122   my $p = shift;
2123   my($context, $session, $custnum) = _custoragent_session_custnum($p);
2124   return { 'error' => $session } if $context eq 'error';
2125
2126   warn "$me adjust_ticket_priority: initializing ticket system\n" if $DEBUG;
2127   FS::TicketSystem->init;
2128   my $ss_priority = FS::TicketSystem->selfservice_priority;
2129
2130   return { 'error' => 'adjust_ticket_priority configuration error' }
2131     if $FS::TicketSystem::system ne 'RT_Internal'
2132       or !$ss_priority;
2133
2134   my $values = $p->{'values'}; #hashref, id => priority value
2135   my %ticket_error;
2136
2137   foreach my $id (keys %$values) {
2138     warn "$me adjust_ticket_priority: fetching ticket $id\n" if $DEBUG;
2139     my $Ticket = FS::TicketSystem->get_ticket_object('',
2140       'ticket_id' => $id,
2141       'custnum'   => $custnum,
2142     );
2143     if ( !$Ticket ) {
2144       $ticket_error{$id} = 'ticket not found';
2145       next;
2146     }
2147     
2148   # RT API stuff--would we gain anything by wrapping this in FS::TicketSystem?
2149   # We're not going to implement it for RT_External.
2150     my $old_value = $Ticket->FirstCustomFieldValue($ss_priority);
2151     my $new_value = $values->{$id};
2152     next if $old_value eq $new_value;
2153
2154     warn "$me adjust_ticket_priority: updating ticket $id\n" if $DEBUG;
2155
2156     # AddCustomFieldValue works fine (replacing any existing value) if it's 
2157     # a single-valued custom field, which it should be.  If it's not, you're 
2158     # doing something wrong.
2159     my ($val, $msg);
2160     if ( length($new_value) ) {
2161       ($val, $msg) = $Ticket->AddCustomFieldValue( 
2162         Field => $ss_priority,
2163         Value => $new_value,
2164       );
2165     }
2166     else {
2167       ($val, $msg) = $Ticket->DeleteCustomFieldValue(
2168         Field => $ss_priority,
2169         Value => $old_value,
2170       );
2171     }
2172
2173     $ticket_error{$id} = $msg if !$val;
2174     warn "$me adjust_ticket_priority: $id: $msg\n" if $DEBUG and !$val;
2175   }
2176   return { 'error' => '',
2177            'ticket_error' => \%ticket_error,
2178            %{ customer_info($p) } # send updated customer info back
2179          }
2180 }
2181
2182 #--
2183
2184 sub _custoragent_session_custnum {
2185   my $p = shift;
2186
2187   my($context, $session, $custnum);
2188   if ( $p->{'session_id'} ) {
2189
2190     $context = 'customer';
2191     $session = _cache->get($p->{'session_id'})
2192       or return ( 'error' => "Can't resume session" ); #better error message
2193     $custnum = $session->{'custnum'};
2194
2195   } elsif ( $p->{'agent_session_id'} ) {
2196
2197     $context = 'agent';
2198     my $agent_cache = new FS::ClientAPI_SessionCache( {
2199       'namespace' => 'FS::ClientAPI::Agent',
2200     } );
2201     $session = $agent_cache->get($p->{'agent_session_id'})
2202       or return ( 'error' => "Can't resume session" ); #better error message
2203     $custnum = $p->{'custnum'};
2204
2205   } else {
2206     $context = 'error';
2207     return ( 'error' => "Can't resume session" ); #better error message
2208   }
2209
2210   ($context, $session, $custnum);
2211
2212 }
2213
2214 1;
2215