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