don't link to customer service view unless the user has the ACL to view the resulting...
[freeside.git] / FS / FS / UI / Web.pm
1 package FS::UI::Web;
2
3 use strict;
4 use vars qw($DEBUG @ISA @EXPORT_OK $me);
5 use Exporter;
6 use FS::Conf;
7 use FS::Record qw(dbdef);
8 use FS::cust_main;  # are sql_balance and sql_date_balance in the right module?
9
10 #use vars qw(@ISA);
11 #use FS::UI
12 #@ISA = qw( FS::UI );
13 @ISA = qw( Exporter );
14
15 @EXPORT_OK = qw( svc_url );
16
17 $DEBUG = 0;
18 $me = '[FS::UID::Web]';
19
20 ###
21 # date parsing
22 ###
23
24 use Date::Parse;
25 sub parse_beginning_ending {
26   my($cgi, $prefix) = @_;
27   $prefix .= '_' if $prefix;
28
29   my $beginning = 0;
30   if ( $cgi->param($prefix.'begin') =~ /^(\d+)$/ ) {
31     $beginning = $1;
32   } elsif ( $cgi->param($prefix.'beginning') =~ /^([ 0-9\-\/]{1,64})$/ ) {
33     $beginning = str2time($1) || 0;
34   }
35
36   my $ending = 4294967295; #2^32-1
37   if ( $cgi->param($prefix.'end') =~ /^(\d+)$/ ) {
38     $ending = $1 - 1;
39   } elsif ( $cgi->param($prefix.'ending') =~ /^([ 0-9\-\/]{1,64})$/ ) {
40     #probably need an option to turn off the + 86399
41     $ending = str2time($1) + 86399;
42   }
43
44   ( $beginning, $ending );
45 }
46
47 =item svc_url
48
49 Returns a service URL, first checking to see if there is a service-specific
50 page to link to, otherwise to a generic service handling page.  Options are
51 passed as a list of name-value pairs, and include:
52
53 =over 4
54
55 =item * m - Mason request object ($m)
56
57 =item * action - The action for which to construct "edit", "view", or "search"
58
59 =item ** part_svc - Service definition (see L<FS::part_svc>)
60
61 =item ** svcdb - Service table
62
63 =item *** query - Query string
64
65 =item *** svc   - FS::cust_svc or FS::svc_* object
66
67 =item ahref - Optional flag, if set true returns <A HREF="$url"> instead of just the URL.
68
69 =back 
70
71 * Required fields
72
73 ** part_svc OR svcdb is required
74
75 *** query OR svc is required
76
77 =cut
78
79   # ##
80   # #required
81   # ##
82   #  'm'        => $m, #mason request object
83   #  'action'   => 'edit', #or 'view'
84   #
85   #  'part_svc' => $part_svc, #usual
86   #   #OR
87   #  'svcdb'    => 'svc_table',
88   #
89   #  'query'    => #optional query string
90   #                # (pass a blank string if you want a "raw" URL to add your
91   #                #  own svcnum to)
92   #   #OR
93   #  'svc'      => $svc_x, #or $cust_svc, it just needs a svcnum
94   #
95   # ##
96   # #optional
97   # ##
98   #  'ahref'    => 1, # if set true, returns <A HREF="$url">
99
100 use FS::CGI qw(rooturl);
101 sub svc_url {
102   my %opt = @_;
103
104   #? return '' unless ref($opt{part_svc});
105
106   my $svcdb = $opt{svcdb} || $opt{part_svc}->svcdb;
107   my $query = exists($opt{query}) ? $opt{query} : $opt{svc}->svcnum;
108   my $url;
109   warn "$me [svc_url] checking for /$opt{action}/$svcdb.cgi component"
110     if $DEBUG;
111   if ( $opt{m}->interp->comp_exists("/$opt{action}/$svcdb.cgi") ) {
112     $url = "$svcdb.cgi?";
113   } else {
114
115     my $generic = $opt{action} eq 'search' ? 'cust_svc' : 'svc_Common';
116
117     $url = "$generic.html?svcdb=$svcdb;";
118     $url .= 'svcnum=' if $query =~ /^\d+(;|$)/ or $query eq '';
119   }
120
121   import FS::CGI 'rooturl'; #WTF!  why is this necessary
122   my $return = rooturl(). "$opt{action}/$url$query";
123
124   $return = qq!<A HREF="$return">! if $opt{ahref};
125
126   $return;
127 }
128
129 sub svc_link {
130   my($m, $part_svc, $cust_svc) = @_ or return '';
131   svc_X_link( $part_svc->svc, @_ );
132 }
133
134 sub svc_label_link {
135   my($m, $part_svc, $cust_svc) = @_ or return '';
136   svc_X_link( ($cust_svc->label)[1], @_ );
137 }
138
139 sub svc_X_link {
140   my ($x, $m, $part_svc, $cust_svc) = @_ or return '';
141
142   return $x
143    unless $FS::CurrentUser::CurrentUser->access_right('View customer services');
144
145   my $ahref = svc_url(
146     'ahref'    => 1,
147     'm'        => $m,
148     'action'   => 'view',
149     'part_svc' => $part_svc,
150     'svc'      => $cust_svc,
151   );
152
153   "$ahref$x</A>";
154 }
155
156 #this probably needs an ACL too...
157 sub svc_export_links {
158   my ($m, $part_svc, $cust_svc) = @_ or return '';
159
160   my $ahref = $cust_svc->export_links;
161
162   join('', @$ahref);
163 }
164
165 sub parse_lt_gt {
166   my($cgi, $field) = @_;
167
168   my @search = ();
169
170   my %op = ( 
171     'lt' => '<',
172     'gt' => '>',
173   );
174
175   foreach my $op (keys %op) {
176
177     warn "checking for ${field}_$op field\n"
178       if $DEBUG;
179
180     if ( $cgi->param($field."_$op") =~ /^\s*\$?\s*(-?[\d\,\s]+(\.\d\d)?)\s*$/ ) {
181
182       my $num = $1;
183       $num =~ s/[\,\s]+//g;
184       my $search = "$field $op{$op} $num";
185       push @search, $search;
186
187       warn "found ${field}_$op field; adding search element $search\n"
188         if $DEBUG;
189     }
190
191   }
192
193   @search;
194
195 }
196
197 ###
198 # cust_main report subroutines
199 ###
200
201
202 =item cust_header [ CUST_FIELDS_VALUE ]
203
204 Returns an array of customer information headers according to the supplied
205 customer fields value, or if no value is supplied, the B<cust-fields>
206 configuration value.
207
208 =cut
209
210 use vars qw( @cust_fields @cust_colors @cust_styles @cust_aligns );
211
212 sub cust_header {
213
214   warn "FS::UI:Web::cust_header called"
215     if $DEBUG;
216
217   my %header2method = (
218     'Customer'                 => 'name',
219     'Cust. Status'             => 'ucfirst_cust_status',
220     'Cust#'                    => 'custnum',
221     'Name'                     => 'contact',
222     'Company'                  => 'company',
223     '(bill) Customer'          => 'name',
224     '(service) Customer'       => 'ship_name',
225     '(bill) Name'              => 'contact',
226     '(service) Name'           => 'ship_contact',
227     '(bill) Company'           => 'company',
228     '(service) Company'        => 'ship_company',
229     'Address 1'                => 'address1',
230     'Address 2'                => 'address2',
231     'City'                     => 'city',
232     'State'                    => 'state',
233     'Zip'                      => 'zip',
234     'Country'                  => 'country_full',
235     'Day phone'                => 'daytime', # XXX should use msgcat, but how?
236     'Night phone'              => 'night',   # XXX should use msgcat, but how?
237     'Fax number'               => 'fax',
238     'Invoicing email(s)'       => 'invoicing_list_emailonly_scalar',
239     'Payment Type'             => 'payby',
240     'Current Balance'          => 'current_balance',
241   );
242
243   my %header2colormethod = (
244     'Cust. Status' => 'cust_statuscolor',
245   );
246   my %header2style = (
247     'Cust. Status' => 'b',
248   );
249   my %header2align = (
250     'Cust. Status' => 'c',
251   );
252
253   my $cust_fields;
254   my @cust_header;
255   if ( @_ && $_[0] ) {
256
257     warn "  using supplied cust-fields override".
258           " (ignoring cust-fields config file)"
259       if $DEBUG;
260     $cust_fields = shift;
261
262   } else {
263
264     my $conf = new FS::Conf;
265     if (    $conf->exists('cust-fields')
266          && $conf->config('cust-fields') =~ /^([\w\. \|\#\(\)]+):?/
267        )
268     {
269       warn "  found cust-fields configuration value"
270         if $DEBUG;
271       $cust_fields = $1;
272     } else { 
273       warn "  no cust-fields configuration value found; using default 'Cust. Status | Customer'"
274         if $DEBUG;
275       $cust_fields = 'Cust. Status | Customer';
276     }
277   
278   }
279
280   @cust_header = split(/ \| /, $cust_fields);
281   @cust_fields = map { $header2method{$_} } @cust_header;
282   @cust_colors = map { exists $header2colormethod{$_}
283                          ? $header2colormethod{$_}
284                          : ''
285                      }
286                      @cust_header;
287   @cust_styles = map { exists $header2style{$_} ? $header2style{$_} : '' }
288                      @cust_header;
289   @cust_aligns = map { exists $header2align{$_} ? $header2align{$_} : 'l' }
290                      @cust_header;
291
292   #my $svc_x = shift;
293   @cust_header;
294 }
295
296 =item cust_sql_fields [ CUST_FIELDS_VALUE ]
297
298 Returns a list of fields for the SELECT portion of an SQL query.
299
300 As with L<the cust_header subroutine|/cust_header>, the fields returned are
301 defined by the supplied customer fields setting, or if no customer fields
302 setting is supplied, the <B>cust-fields</B> configuration value. 
303
304 =cut
305
306 sub cust_sql_fields {
307
308   my @fields = qw( last first company );
309   push @fields, map "ship_$_", @fields;
310   push @fields, 'country';
311
312   cust_header(@_);
313   #inefficientish, but tiny lists and only run once per page
314   push @fields,
315     grep { my $field = $_; grep { $_ eq $field } @cust_fields }
316          qw( address1 address2 city state zip daytime night fax payby );
317
318   my @extra_fields = ();
319   if (grep { $_ eq 'current_balance' } @cust_fields) {
320     push @extra_fields, FS::cust_main->balance_sql . " AS current_balance";
321   }
322
323   map("cust_main.$_", @fields), @extra_fields;
324 }
325
326 =item cust_fields OBJECT [ CUST_FIELDS_VALUE ]
327
328 Given an object that contains fields from cust_main (say, from a
329 JOINed search.  See httemplate/search/svc_* for examples), returns an array
330 of customer information, or "(unlinked)" if this service is not linked to a
331 customer.
332
333 As with L<the cust_header subroutine|/cust_header>, the fields returned are
334 defined by the supplied customer fields setting, or if no customer fields
335 setting is supplied, the <B>cust-fields</B> configuration value. 
336
337 =cut
338
339 sub cust_fields {
340   my $record = shift;
341   warn "FS::UI::Web::cust_fields called for $record ".
342        "(cust_fields: @cust_fields)"
343     if $DEBUG > 1;
344
345   #cust_header(@_) unless @cust_fields; #now need to cache to keep cust_fields
346   #                                     #override incase we were passed as a sub
347
348   my $seen_unlinked = 0;
349   map { 
350     if ( $record->custnum ) {
351       warn "  $record -> $_"
352         if $DEBUG > 1;
353       $record->$_(@_);
354     } else {
355       warn "  ($record unlinked)"
356         if $DEBUG > 1;
357       $seen_unlinked++ ? '' : '(unlinked)';
358     }
359   } @cust_fields;
360 }
361
362 =item cust_colors
363
364 Returns an array of subroutine references (or empty strings) for returning
365 customer information colors.
366
367 As with L<the cust_header subroutine|/cust_header>, the fields returned are
368 defined by the supplied customer fields setting, or if no customer fields
369 setting is supplied, the <B>cust-fields</B> configuration value. 
370
371 =cut
372
373 sub cust_colors {
374   map { 
375     my $method = $_;
376     if ( $method ) {
377       sub { shift->$method(@_) };
378     } else {
379       '';
380     }
381   } @cust_colors;
382 }
383
384 =item cust_styles
385
386 Returns an array of customer information styles.
387
388 As with L<the cust_header subroutine|/cust_header>, the fields returned are
389 defined by the supplied customer fields setting, or if no customer fields
390 setting is supplied, the <B>cust-fields</B> configuration value. 
391
392 =cut
393
394 sub cust_styles {
395   map { 
396     if ( $_ ) {
397       $_;
398     } else {
399       '';
400     }
401   } @cust_styles;
402 }
403
404 =item cust_aligns
405
406 Returns an array or scalar (depending on context) of customer information
407 alignments.
408
409 As with L<the cust_header subroutine|/cust_header>, the fields returned are
410 defined by the supplied customer fields setting, or if no customer fields
411 setting is supplied, the <B>cust-fields</B> configuration value. 
412
413 =cut
414
415 sub cust_aligns {
416   if ( wantarray ) {
417     @cust_aligns;
418   } else {
419     join('', @cust_aligns);
420   }
421 }
422
423 ###
424 # begin JSRPC code...
425 ###
426
427 package FS::UI::Web::JSRPC;
428
429 use strict;
430 use vars qw($DEBUG);
431 use Carp;
432 use Storable qw(nfreeze);
433 use MIME::Base64;
434 use JSON;
435 use FS::UID qw(getotaker);
436 use FS::Record qw(qsearchs);
437 use FS::queue;
438
439 $DEBUG = 0;
440
441 sub new {
442         my $class = shift;
443         my $self  = {
444                 env => {},
445                 job => shift,
446                 cgi => shift,
447         };
448
449         bless $self, $class;
450
451         croak "CGI object required as second argument" unless $self->{'cgi'};
452
453         return $self;
454 }
455
456 sub process {
457
458   my $self = shift;
459
460   my $cgi = $self->{'cgi'};
461
462   # XXX this should parse JSON foo and build a proper data structure
463   my @args = $cgi->param('arg');
464
465   #work around konqueror bug!
466   @args = map { s/\x00$//; $_; } @args;
467
468   my $sub = $cgi->param('sub'); #????
469
470   warn "FS::UI::Web::JSRPC::process:\n".
471        "  cgi=$cgi\n".
472        "  sub=$sub\n".
473        "  args=".join(', ',@args)."\n"
474     if $DEBUG;
475
476   if ( $sub eq 'start_job' ) {
477
478     $self->start_job(@args);
479
480   } elsif ( $sub eq 'job_status' ) {
481
482     $self->job_status(@args);
483
484   } else {
485
486     die "unknown sub $sub";
487
488   }
489
490 }
491
492 sub start_job {
493   my $self = shift;
494
495   warn "FS::UI::Web::start_job: ". join(', ', @_) if $DEBUG;
496 #  my %param = @_;
497   my %param = ();
498   while ( @_ ) {
499     my( $field, $value ) = splice(@_, 0, 2);
500     unless ( exists( $param{$field} ) ) {
501       $param{$field} = $value;
502     } elsif ( ! ref($param{$field}) ) {
503       $param{$field} = [ $param{$field}, $value ];
504     } else {
505       push @{$param{$field}}, $value;
506     }
507   }
508   $param{CurrentUser} = getotaker();
509   warn "FS::UI::Web::start_job\n".
510        join('', map {
511                       if ( ref($param{$_}) ) {
512                         "  $_ => [ ". join(', ', @{$param{$_}}). " ]\n";
513                       } else {
514                         "  $_ => $param{$_}\n";
515                       }
516                     } keys %param )
517     if $DEBUG;
518
519   #first get the CGI params shipped off to a job ASAP so an id can be returned
520   #to the caller
521   
522   my $job = new FS::queue { 'job' => $self->{'job'} };
523   
524   #too slow to insert all the cgi params as individual args..,?
525   #my $error = $queue->insert('_JOB', $cgi->Vars);
526   
527   #warn 'froze string of size '. length(nfreeze(\%param)). " for job args\n"
528   #  if $DEBUG;
529
530   my $error = $job->insert( '_JOB', encode_base64(nfreeze(\%param)) );
531
532   if ( $error ) {
533
534     warn "job not inserted: $error\n"
535       if $DEBUG;
536
537     $error;  #this doesn't seem to be handled well,
538              # will trigger "illegal jobnum" below?
539              # (should never be an error inserting the job, though, only thing
540              #  would be Pg f%*kage)
541   } else {
542
543     warn "job inserted successfully with jobnum ". $job->jobnum. "\n"
544       if $DEBUG;
545
546     $job->jobnum;
547   }
548   
549 }
550
551 sub job_status {
552   my( $self, $jobnum ) = @_; #$url ???
553
554   sleep 1; # XXX could use something better...
555
556   my $job;
557   if ( $jobnum =~ /^(\d+)$/ ) {
558     $job = qsearchs('queue', { 'jobnum' => $jobnum } );
559   } else {
560     die "FS::UI::Web::job_status: illegal jobnum $jobnum\n";
561   }
562
563   my @return;
564   if ( $job && $job->status ne 'failed' ) {
565     @return = ( 'progress', $job->statustext );
566   } elsif ( !$job ) { #handle job gone case : job successful
567                       # so close popup, redirect parent window...
568     @return = ( 'complete' );
569   } else {
570     @return = ( 'error', $job ? $job->statustext : $jobnum );
571   }
572
573   objToJson(\@return);
574
575 }
576
577 1;
578