add condition on "Invoice is newer than last payment type change", RT#31185
[freeside.git] / FS / FS / part_event / Condition / cust_bill_age_before_payby.pm
1 package FS::part_event::Condition::cust_bill_age_before_payby;
2 use base qw( FS::part_event::Condition );
3
4 use strict;
5 use FS::Record qw( qsearchs );
6 use FS::h_cust_main;
7
8 sub description { 'Invoice is newer than last payment type change'; }
9
10 sub eventtable_hashref {
11     { 'cust_main' => 0,
12       'cust_bill' => 1,
13       'cust_pkg'  => 0,
14     };
15 }
16
17 sub condition {
18   my( $self, $cust_bill, %opt ) = @_;
19
20   #my $cust_main = $cust_bill->cust_main;
21
22   my $change_date = 0;
23   my $newest = 2147483647; #2038 problem, because the field does
24
25   #this is pretty expensive, it would be way more efficient to check for
26   # changed payby in SQL
27   #  (it would also help if a replace_new had a real FK ref to its replace_old)
28   while ( my $replace_new = qsearchs({
29             'table' => 'h_cust_main',
30             'hashref'  => { 'custnum'        => $cust_bill->custnum,
31                             'history_action' => 'replace_new',
32                             'history_date'   => { op=>'<', value=>$newest },
33                           },
34             'order_by' => 'ORDER BY history_date DESC LIMIT 1',
35         }))
36   {
37     my $newest = $replace_new->history_date;
38     my $replace_old = qsearchs({
39       'table' => 'h_cust_main',
40       'hashref' => { 'custnum'        => $replace_new->custnum,
41                      'history_action' => 'replace_old',
42                      'history_date'   => $replace_new->history_date,
43                    }
44     }) or next; #no replace_old?  ignore and continue on i guess
45
46     if ( $replace_new->payby ne $replace_old->payby ) {
47       $change_date = $replace_new->history_date;
48       last;
49     }
50
51   }
52
53   ( $cust_bill->_date ) > $change_date;
54
55 }
56
57 1;