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