Ticket #31242 Fix A2billing suspends
[freeside.git] / FS / FS / part_export / a2billing.pm
1 package FS::part_export::a2billing;
2
3 use strict;
4 use vars qw(@ISA @EXPORT_OK $DEBUG %info %options);
5 use Exporter;
6 use Tie::IxHash;
7 use FS::Record qw( qsearch qsearchs str2time_sql );
8 use FS::part_export;
9 use FS::svc_acct;
10 use FS::svc_phone;
11 use Locale::Country qw(country_code2code);
12 use Date::Format qw(time2str);
13 use Carp qw( cluck );
14
15 @ISA = qw(FS::part_export);
16
17 $DEBUG = 0;
18
19 tie %options, 'Tie::IxHash',
20   'datasrc'     => { label=>'DBI data source ' },
21   'username'    => { label=>'Database username' },
22   'password'    => { label=>'Database password' },
23   'didgroup'    => { label=>'DID group ID', default=>1 },
24   'credit'      => { label=>'Default credit limit' },
25   'billtype'    => {label=>'Billing type',
26                     type => 'select',
27                     options => ['monthly', 'weekly']
28                   },
29   'debug'       => { label=>'Enable debugging', type=>'checkbox' }
30 ;
31
32 my $notes = <<'END';
33 <p>Real-time export to the backend database of an <a
34 href="http://www.asterisk2billing.org">Asterisk2Billing</a> billing server.
35 This is both a svc_acct and a svc_phone export, and needs to be attached 
36 to both a svc_acct and svc_phone definition within the same package.</p>
37 <ul>
38 <li>When you set up this export, it will create 'svcnum' fields in the 
39 cc_card and cc_did tables in the A2Billing database to store the 
40 service numbers of svc_acct and svc_phone records.  The database username 
41 must have ALTER TABLE privileges.</li>
42 <li><i>DBI data source</i> should look like<br>
43 <b>dbi:mysql:host=</b><i>hostname</i><b>;database=</b><i>dbname</i>
44 </li>
45 END
46
47 %info = (
48   'svc'      => ['svc_acct', 'svc_phone'],
49   'desc'     => 'Export to Asterisk2Billing database',
50   'options'  => \%options,
51   'nodomain' => 'Y',
52   'no_machine' => 1,
53   'notes'    => $notes
54 );
55
56 sub dbh {
57   my $self = shift;
58   $self->{dbh} ||= DBI->connect(
59                       $self->option('datasrc'),
60                       $self->option('username'),
61                       $self->option('password')
62                       ) or die $DBI::errstr;
63
64   $self->{dbh}->trace(1, '%%%FREESIDE_LOG%%%/a2b_exportlog.'.$self->exportnum)
65     if $DEBUG;
66
67   $self->{dbh};
68 }
69
70 # hook insert/replace, because we need to make some changes to the
71 # database when the export is created
72 sub insert {
73   my $self = shift;
74   my $error = $self->SUPER::insert(@_);
75   return $error if $error;
76   if ( $self->option('datasrc') ) {
77     my $error;
78     foreach (qw(cc_card cc_did)) {
79       $self->dbh->do("ALTER TABLE $_ ADD COLUMN svcnum int")
80         or $error = $self->dbh->errstr;
81       $error = '' if $error =~ /Duplicate column name/; # harmless
82       return "Error preparing a2billing database: $error\n" if $error;
83     }
84   }
85   '';
86 }
87
88 sub replace {
89   my $new = shift;
90   my $old = shift || $new->replace_old;
91   my $old_datasrc = $old->option('datasrc');
92   my $error = $new->SUPER::replace($old, @_);
93   return $error if $error;
94
95   if ($new->option('datasrc') and $new->option('datasrc') ne $old_datasrc) {
96     my $dbh = $new->a2b_connect;
97     my $error;
98     foreach (qw(cc_card cc_did)) {
99       $new->dbh->do("ALTER TABLE $_ ADD COLUMN svcnum int")
100         or $error = $new->dbh->errstr;
101       $error = '' if $error =~ /Duplicate column name/; # harmless
102       return "Error preparing a2billing database: $error\n" if $error;
103     }
104   }
105   '';
106 }
107
108 sub export_insert {
109   my $self = shift;
110   my $svc = shift;
111   my $cust_pkg = $svc->cust_svc->cust_pkg;
112   my $cust_main = $cust_pkg->cust_main;
113   my $location = $cust_pkg->cust_location;
114   my $part_pkg = $cust_pkg->part_pkg;
115
116   my $error;
117   $DEBUG ||= $self->option('debug');
118
119   # 3-letter UN country code
120   my $country3 = uc(country_code2code($location->country, 'alpha2' => 'alpha3'));
121   
122   my $dbh = $self->a2b_connect;
123
124   if ( $svc->isa('FS::svc_acct') ) {
125     # export to cc_card (customer identity) and cc_sip_buddies (SIP extension)
126
127     my $username = $svc->username;
128
129     my %cc_card = (
130       svcnum    => $svc->svcnum,
131       username  => $username,
132       useralias => $username,
133       uipass    => $svc->_password,
134       credit    => $self->option('credit') || 0,
135       tariff    => $part_pkg->option('a2billing_tariff'),
136       status    => 1,
137       lastname  => $cust_main->last, # $svc->finger?
138       firstname => $cust_main->first,
139       address   => $location->address1 .
140                   ($location->address2 ? ', '.$location->address2 : ''),
141       city      => $location->city,
142       state     => $location->state,
143       country   => $country3,
144       zipcode   => $location->zip,
145       typepaid  => $part_pkg->option('a2billing_type'),
146       sip_buddy => 1,
147       company_name => $cust_main->company,
148       activated => 't',
149     );
150     warn "creating A2B cc_card record for $username\n" if $DEBUG;
151     $error = $self->a2b_insert_or_replace('cc_card', 'svcnum', \%cc_card);
152     return "Error creating A2Billing customer identity: $error" if $error;
153     
154     my $fullcontact = '';
155     if ( $svc->ip_addr ) {
156       $fullcontact = "sip:$username\@".$svc->ip_addr;
157     }
158
159     my $cc_card_id = $self->a2b_find('cc_card', 'svcnum', $svc->svcnum);
160     # these are the fields we know about; some of them might need to be 
161     # export options eventually, and there are a lot more fields in the table
162     my %cc_sip_buddy = (
163       id_cc_card      => $cc_card_id,
164       name            => $username,
165       accountcode     => $username,
166       regexten        => $username,
167       amaflags        => 'billing',
168       context         => 'a2billing',
169       host            => 'dynamic',
170       port            => 5060,
171       secret          => $svc->_password,
172       username        => $username,
173       allow           => 'ulaw,alaw,gsm,g729',
174       ipaddr          => ($svc->slipip || ''),
175       fullcontact     => $fullcontact,
176     );
177     warn "creating A2B cc_sip_buddies record for $username\n" if $DEBUG;
178     $error = $self->a2b_insert_or_replace('cc_sip_buddies', 'id_cc_card',
179                                           \%cc_sip_buddy);
180     return "Error creating A2Billing SIP extension: $error" if $error;
181
182     # then, if there are any DIDs on the package, set them up
183     foreach ( $self->_linked_svcs($svc, 'svc_phone') ) {
184       warn "triggering export of svc_phone #".$_->svcnum."\n" if $DEBUG;
185       $error = $self->export_insert($_->svc_x);
186       return $error if $error;
187     }
188     return '';
189
190   } elsif ( $svc->isa('FS::svc_phone') ) {
191     # find the linked svc_acct
192     my $svc_acct;
193     foreach ($self->_linked_svcs($svc, 'svc_acct')) {
194       $svc_acct = $_->svc_x;
195       last;
196     }
197     if ( !$svc_acct ) {
198       # it hasn't been created yet, so just exit.
199       # this service will be exported later.
200       warn "no linked svc_acct; deferring phone number export\n" if $DEBUG;
201       return '';
202     }
203     # find the card and sip_buddies records
204     my $cc_card_id = $self->a2b_find('cc_card', 'svcnum', $svc_acct->svcnum);
205     my $cc_sip_buddies_id = $self->a2b_find('cc_sip_buddies', 'id_cc_card', $cc_card_id);
206     if (!$cc_card_id or !$cc_sip_buddies_id) {
207       warn "When exporting svc_phone #".$svc->svcnum.", svc_acct #".$svc_acct->svcnum." was not found in A2Billing.\n";
208       if ( $FS::svc_Common::noexport_hack ) {
209         # recursion protection
210         return "During export of linked DID#".$svc->phonenum.", svc_acct #".$svc_acct->svcnum." was not found in A2Billing.";
211       }
212       return $svc_acct->export_insert; # which will call back to here when 
213                                        # it's done
214     }
215
216     # Create the DID.
217     my $cc_country_id = $self->a2b_find('cc_country', 'countrycode', $country3);
218     my %cc_did = (
219       svcnum          => $svc->svcnum,
220       id_cc_didgroup  => $self->option('didgroup'),
221       id_cc_country   => $cc_country_id,
222       iduser          => $cc_card_id,
223       did             => $svc->phonenum,
224       billingtype     => ($self->option('billtype') eq 'weekly' ? 1 : 0),
225       activated       => 1,
226     );
227
228     # use 'did' as the key here so that if the DID already exists, we 
229     # link it to this customer.
230     $error = $self->a2b_insert_or_replace('cc_did', 'did', \%cc_did);
231     return "Error creating A2Billing DID record: $error" if $error;
232
233     my $cc_did_id = $self->a2b_find('cc_did', 'svcnum', $svc->svcnum);
234     
235     my $destination = 'SIP/' . $svc->phonenum . '@' . $svc_acct->username;
236     my %cc_did_destination = (
237       destination     => $destination,
238       priority        => 1,
239       id_cc_card      => $cc_card_id,
240       id_cc_did       => $cc_did_id,
241     );
242
243     # and if there's already a destination, change it to point to
244     # this customer's SIP extension
245     $error = $self->a2b_insert_or_replace('cc_did_destination', 'id_cc_did',
246                                           \%cc_did_destination);
247     return "Error linking A2Billing DID record to customer: $error" if $error;
248
249     my %cc_did_use = (
250       id_cc_card      => $cc_card_id,
251       id_did          => $cc_did_id,
252       activated       => 1,
253       month_payed     => 1, # it's the default in the A2Billing code, I think
254     );
255     # and change the in-use record, too
256     my $id_use = $self->a2b_find('cc_did_use',
257       id_did          => $cc_did_id,
258       activated       => 1,
259     );
260     if ( $id_use ) {
261       $error = $self->a2b_insert_or_replace('cc_did_use', 'id',
262         { id          => $id_use,
263           releasedate => time2str('%Y-%m-%d %H:%M:%S', time),
264           activated   => 0
265         }
266       );
267       return "Error closing existing A2Billing DID assignment record: $error"
268         if $error;
269
270       # and do an update instead of an insert
271       $cc_did_use{id} = $id_use;
272     }
273
274     $error = $self->a2b_insert_or_replace('cc_did_use', 'id', \%cc_did_use);
275     return "Error creating A2Billing DID use record: $error" if $error;
276
277   } # if $svc->isa(...)
278   '';
279 }
280
281 sub export_delete {
282   my $self = shift;
283   my $svc = shift;
284
285   my $error;
286   $DEBUG ||= $self->option('debug');
287
288   if ( $svc->isa('FS::svc_acct') ) {
289
290     # first remove the DID links
291     foreach ($self->_linked_svcs($svc, 'svc_phone')) {
292       warn "triggering export of svc_phone #".$_->svcnum."\n" if $DEBUG;
293       $error = $self->export_delete($_->svc_x);
294       return $error if $error;
295     }
296
297     # a2billing never deletes a card, just sets status = 0.
298     # though we also need to remove the svcnum, since that svcnum is no 
299     # longer valid.
300     my $cc_card_id = $self->a2b_find('cc_card', 'svcnum', $svc->svcnum);
301     if (!$cc_card_id) {
302       warn "tried to remove svc_acct #".$svc->svcnum." from A2Billing, but couldn't find it.\n";
303       # which is not really a problem.
304       return '';
305     }
306     warn "deactivating A2B cc_card record #$cc_card_id\n" if $DEBUG;
307     $error = $self->a2b_insert_or_replace('cc_card', 'id', {
308         id        => $cc_card_id,
309         status    => 0,
310         activated => 0,
311         svcnum    => 0,
312     });
313     return $error if $error;
314
315   } elsif ( $svc->isa('FS::svc_phone') ) {
316
317     my $cc_did_id = $self->a2b_find('cc_did', 'svcnum', $svc->svcnum);
318     if ( $cc_did_id ) {
319       warn "deactivating DID ".$svc->phonenum."\n" if $DEBUG;
320       $error = $self->a2b_insert_or_replace('cc_did', 'id',
321         { id        => $cc_did_id,
322           activated => 0,
323           iduser    => 0,
324           svcnum    => 0,
325         }
326       );
327       return $error if $error;
328     } else {
329       warn "tried to remove svc_phone #".$svc->svcnum." from A2Billing, but couldn't find it.\n";
330       return '';
331     }
332
333     my $cc_did_destination_id = $self->a2b_find('cc_did_destination',
334       'id_cc_did', $cc_did_id,
335       'activated', 1
336     );
337     if ( $cc_did_destination_id ) {
338       warn "unlinking DID ".$svc->phonenum." from customer\n" if $DEBUG;
339       $error = $self->a2b_delete('cc_did_destination', $cc_did_destination_id);
340       return $error if $error;
341     } else {
342       warn "no cc_did_destination found for cc_did #$cc_did_id\n";
343     }
344     
345     my $cc_did_use_id = $self->a2b_find('cc_did_use',
346       'id_did', $cc_did_id,
347       'activated', 1
348     );
349     if ( $cc_did_use_id ) {
350       warn "closing DID assignment\n" if $DEBUG;
351       $error = $self->a2b_insert_or_replace('cc_did_use', 'id',
352         { id          => $cc_did_use_id,
353           releasedate => time2str('%Y-%m-%d %H:%M:%S', time),
354           activated   => 0
355         }
356       );
357       return "Error closing existing A2Billing DID assignment record: $error"
358         if $error;
359     } else {
360       warn "no cc_did_use found for cc_did #$cc_did_id\n";
361     }
362
363   }
364   '';
365 }
366
367 sub export_replace {
368   my $self = shift;
369   my $new = shift;
370   my $old = shift || $self->replace_old;
371
372   my $error;
373   $DEBUG ||= $self->option('debug');
374
375   if ( $new->isa('FS::svc_acct') ) {
376
377     my $cc_card_id = $self->a2b_find('cc_card', 'svcnum', $new->svcnum);
378     if ( $cc_card_id and $new->username ne $old->username ) {
379       # If the username is changing and any DIDs are provisioned, we need to 
380       # change their destinations.  To do this, we unlink them.  This will 
381       # close their did_use records, delete their cc_did_destinations, and 
382       # set their cc_dids to inactive.
383       foreach ($self->_linked_svcs($new, 'svc_phone')) {
384         warn "triggering export of svc_phone #".$_->svcnum."\n" if $DEBUG;
385         $error = $self->export_delete($_->svc_x);
386         return $error if $error;
387       }
388     }
389
390     # export_insert will replace the record with the same svcnum, if there 
391     # is one, and then re-export all existing DIDs (which is convenient since
392     # we just unlinked them).
393     $error = $self->export_insert($new);
394     return $error if $error;
395
396   } elsif ( $new->isa('FS::svc_phone') ) {
397
398     # if the phone number has changed, need to create a new DID.
399     if ( $new->phonenum ne $old->phonenum ) {
400       # deactivate/unlink/close the old DID
401       # and create/link the new one
402       $error = $self->export_delete($old)
403             || $self->export_insert($new);
404       return $error if $error;
405     }
406     # otherwise we don't care
407   }
408
409   '';
410 }
411
412 sub export_suspend {
413   my $self = shift;
414   my $svc = shift;
415
416   my $error;
417   $DEBUG ||= $self->option('debug');
418
419   if ( $svc->isa('FS::svc_acct') ) {
420     $error = $self->a2b_insert_or_replace('cc_card', 'svcnum',
421       { svcnum    => $svc->svcnum,
422         status    => 6, # "SUSPENDED FOR UNDERPAYMENT"
423         activated => 0, # still used in some places, grrr
424       }
425     );
426   } elsif ( $svc->isa('FS::svc_phone') ) {
427     # deactivate the DID
428     $error = $self->a2b_insert_or_replace('cc_did', 'svcnum',
429       { svcnum    => $svc->svcnum,
430         activated => 0,
431       }
432     );
433   }
434   $error || '';
435 }
436
437 sub export_unsuspend {
438   my $self = shift;
439   my $svc = shift;
440
441   my $error;
442   $DEBUG ||= $self->option('debug');
443
444   if ( $svc->isa('FS::svc_acct') ) {
445     $error = $self->a2b_insert_or_replace('cc_card', 'svcnum',
446       { svcnum    => $svc->svcnum,
447         status    => 1, #"ACTIVE"
448         activated => 1,
449       }
450     );
451   } elsif ( $svc->isa('FS::svc_phone') ) {
452     $error = $self->a2b_insert_or_replace('cc_did', 'svcnum',
453       { svcnum    => $svc->svcnum,
454         activated => 1,
455       }
456     );
457   }
458   $error || '';
459 }
460
461 =item a2b_insert_or_replace TABLE KEY HASHREF
462
463 Create a record in TABLE with the values in HASHREF.  If there's already one 
464 that matches on the KEY field, update the existing record instead of creating
465 a new one.  Pass an empty KEY to just insert the record without checking.
466
467 =cut
468
469 sub a2b_insert_or_replace {
470   my $self = shift;
471   my $table = shift;
472   my $key = shift;
473   my $hashref = shift;
474
475   if ( $key ) {
476     my $id = $self->a2b_find($table, $key, $hashref->{$key});
477     if ( $id ) {
478       my $sql = "UPDATE $table SET " .
479                 join(', ', map { "$_ = ?" } keys(%$hashref)) .
480                 " WHERE id = ?";
481       $self->dbh->do($sql, {}, values(%$hashref), $id)
482         or return $self->dbh->errstr;
483       return '';
484     }
485   }
486   # no key, or no existing record
487   my $sql = "INSERT INTO $table (".  join(', ', keys(%$hashref)) . ")" .
488             " VALUES (" . join(', ', map { '?' } keys(%$hashref)) . ")";
489   $self->dbh->do($sql, {}, values(%$hashref))
490     or return $self->dbh->errstr;
491   return '';
492 }
493
494 =item a2b_delete TABLE ID
495
496 Remove the record with id ID from TABLE.
497
498 =cut
499
500 sub a2b_delete {
501   my $self = shift;
502   my ($table, $id) = @_;
503   my $sql = "DELETE FROM $table WHERE id = ?";
504   $self->dbh->do($sql, {}, $id)
505     or return $self->dbh->errstr;
506   return '';
507 }
508
509 =item a2b_find TABLE KEY VALUE [ KEY VALUE ... ]
510
511 Search TABLE for a row where KEY equals VALUE, and return its "id" field.
512
513 =cut
514
515 sub a2b_find {
516   my $self = shift;
517   my ($table, %params) = @_;
518   my $sql = "SELECT id FROM $table WHERE " .
519     join(' AND ', map { "$_ = ?" } keys(%params));
520   my ($id) = $self->dbh->selectrow_array($sql, {}, values(%params));
521   die $self->dbh->errstr if $self->dbh->errstr;
522   $id || '';
523 }
524
525 # find services on the same package that are exportable with this export
526 # and are of a specified svcdb
527 #
528 # just to avoid repeating myself
529 sub _linked_svcs {
530   my ($self, $svc, $svcdb) = @_;
531   # index the svcparts that belong to the a2billing export
532   my $export_svcparts = $self->{export_svcparts} ||= 
533     { map { $_->svcpart => $_->part_svc->svcdb }
534       $self->export_svc
535     };
536
537   my $pkgnum = $svc->cust_svc->pkgnum;
538   my @svcs = qsearch('cust_svc', { pkgnum => $pkgnum });
539   grep { $export_svcparts->{$_->svcpart} eq $svcdb } @svcs;
540 }
541
542 1;