5 use Date::Format qw(time2str);
6 use File::Temp qw(tempdir);
7 use Net::SFTP::Foreign;
8 use FS::UID qw(adminsuidsetup);
9 use FS::Record qw(qsearch qsearchs);
12 use File::Copy qw(copy);
16 getopts('vqNa:P:C:e:', \%opt);
18 # Product codes that are subject to flat rate E911 charges. For these
19 # products, the'quantity' field represents the number of lines.
20 my @E911_CODES = ( 'V-HPBX', 'V-TRUNK' );
22 # Map TAXNONVOICE/TAXVOICE to Freeside taxclass names
24 'TAXNONVOICE' => 'Other',
29 #$Net::SFTP::Foreign::debug = -1;
32 freeside-ipifony-download
40 freesideuser sftpuser@hostname[:path]
52 my $user = shift or die &HELP_MESSAGE;
53 my $dbh = adminsuidsetup $user;
54 $FS::UID::AutoCommit = 0;
64 die "no such directory: $opt{a}\n"
66 die "archive directory $opt{a} is not writable by the freeside user\n"
72 $e911_part_pkg = FS::part_pkg->by_key($opt{e})
73 or die "E911 pkgpart $opt{e} not found.\n";
75 if ( $e911_part_pkg->base_recur > 0 or $e911_part_pkg->freq ) {
76 die "E911 pkgpart $opt{e} must be a one-time charge.\n";
82 # find this category (don't auto-create it, it should exist already)
83 my $category = qsearchs('pkg_category', { categoryname => $opt{C} });
84 if (!defined($category)) {
85 die "Package category '$opt{C}' does not exist.\n";
87 $categorynum = $category->categorynum;
90 #my $tmpdir = File::Temp->newdir();
91 my $tmpdir = tempdir( CLEANUP => 1 ); #DIR=>somewhere?
95 my ($sftpuser, $path);
97 $sftpuser = $1 || $ENV{USER};
102 if ( $opt{P} =~ /^(\d+)$/ ) {
106 # for now assume SFTP download as the only method
107 print STDERR "Connecting to $sftpuser\@$host...\n" if $opt{v};
109 my $sftp = Net::SFTP::Foreign->new(
113 # for now we don't support passwords. use authorized_keys.
115 #more => ($opt{v} ? '-v' : ''),
117 die "failed to connect to '$sftpuser\@$host'\n(".$sftp->error.")\n"
120 $sftp->setcwd($path) if $path;
122 my $files = $sftp->ls('ready', wanted => qr/\.csv$/, names_only => 1);
124 print STDERR "No charge files found.\n" if $opt{v};
128 my %cust_main; # cache
129 my %e911_qty; # custnum => sum of E911-subject quantity
131 my %is_e911 = map {$_ => 1} @E911_CODES;
133 FILE: foreach my $filename (@$files) {
134 print STDERR "Retrieving $filename\n" if $opt{v};
135 $sftp->get("ready/$filename", "$tmpdir/$filename");
137 warn "failed to download $filename\n";
141 # make sure server archive dir exists
142 if ( !$sftp->stat('done') ) {
143 print STDERR "Creating $path/done\n" if $opt{v};
144 $sftp->mkdir('done');
146 # something is seriously wrong
147 die "failed to create archive directory on server:\n".$sftp->error."\n";
150 #move to server archive dir
151 $sftp->rename("ready/$filename", "done/$filename");
153 warn "failed to archive $filename on server:\n".$sftp->error."\n";
154 } # process it anyway, I guess/
156 #copy to local archive dir
158 print STDERR "Copying $tmpdir/$filename to archive dir $opt{a}\n"
160 copy("$tmpdir/$filename", $opt{a});
161 warn "failed to copy $tmpdir/$filename to $opt{a}: $!" if $!;
164 open my $fh, "<$tmpdir/$filename";
165 my $csv = Text::CSV->new; # orthodox CSV
167 while (my $line = <$fh>) {
168 $csv->parse($line) or do {
169 warn "can't parse $filename: ".$csv->error_input."\n";
172 @hash{@fields} = $csv->fields();
173 if ( $hash{custnum} =~ /^cust/ ) {
174 # there appears to be a header row
175 print STDERR "skipping header row\n" if $opt{v};
179 $cust_main{$hash{custnum}} ||= FS::cust_main->by_key($hash{custnum});
181 warn "customer #$hash{custnum} not found\n";
184 print STDERR "Found customer #$hash{custnum}: ".$cust_main->name."\n"
187 my $amount = sprintf('%.2f',$hash{quantity} * $hash{unit_price});
189 # bill the charge on the customer's next bill date, if that's within
190 # the current calendar month; otherwise bill it immediately
192 my $next_bill_date = $cust_main->next_bill_date;
193 if ( $next_bill_date ) {
194 my ($bill_month, $bill_year) = (localtime($next_bill_date))[4, 5];
195 my ($this_month, $this_year) = (localtime(time))[4, 5];
197 $this_month == $bill_month and $this_year == $bill_year ) {
198 $cust_main->set('charge_date', $next_bill_date);
202 # construct arguments for $cust_main->charge
204 amount => $hash{unit_price},
205 quantity => $hash{quantity},
206 start_date => $cust_main->get('charge_date'),
207 pkg => $hash{date_desc},
208 taxclass => $TAXCLASSES{ $hash{taxclass} },
211 $charge_opt{pkg} .= ' (' . $hash{quantity} . ' @ $' . $hash{unit_price} . ' ea)';
213 if (my $classname = $hash{classname}) {
214 if (!exists($classnum_of{$classname}) ) {
216 my $pkg_class = qsearchs('pkg_class', {
217 classname => $classname,
218 categorynum => $categorynum,
220 if (!defined($pkg_class)) {
222 $pkg_class = FS::pkg_class->new({
223 classname => $classname,
224 categorynum => $categorynum,
226 my $error = $pkg_class->insert;
227 die "Error creating package class for product code '$classname':\n".
232 $classnum_of{$classname} = $pkg_class->classnum;
234 $charge_opt{classnum} = $classnum_of{$classname};
236 print STDERR " Charging $hash{unit_price} * $hash{quantity}\n"
238 my $error = $cust_main->charge(\%charge_opt);
240 warn "Error creating charge: $error" if $error;
244 $sum_charges += $amount;
247 if ( $opt{e} and $is_e911{$hash{classname}} ) {
248 $e911_qty{$hash{custnum}} ||= 0;
249 $e911_qty{$hash{custnum}} += $hash{quantity};
255 # Order E911 packages
258 foreach my $custnum ( keys (%e911_qty) ) {
259 my $cust_main = $cust_main{$custnum};
260 my $quantity = $e911_qty{$custnum};
261 next if $quantity == 0;
262 my $cust_pkg = FS::cust_pkg->new({
265 start_date => $cust_main->get('charge_date'),
266 quantity => $quantity,
268 my $error = $cust_main->order_pkg({ cust_pkg => $cust_pkg });
270 warn "Error creating e911 charge for customer $custnum: $error\n";
274 $num_lines += $quantity;
283 Processed files: @$files
284 Created charges: $num_charges
285 Sum of charges: \$".sprintf('%0.2f', $sum_charges)."
286 E911 charges: $num_e911
287 E911 lines: $num_lines
294 freeside-ipifony-download - Download and import invoice items from IPifony.
298 freeside-ipifony-download
307 freesideuser sftpuser@hostname[:path]
309 =head1 REQUIRED PARAMETERS
311 I<freesideuser>: the Freeside user to run as.
313 I<sftpuser>: the SFTP user to connect as. The 'freeside' system user should
314 have an authorization key to connect as that user.
316 I<hostname>: the SFTP server.
318 I<path>: the path on the server to the working directory. The working
319 directory is the one containing the "ready/" and "done/" subdirectories.
321 =head1 OPTIONAL PARAMETERS
325 -q: Include the quantity and unit price in the charge description.
327 -N: Always bill the charges on the customer's next bill date, if they have
328 one. Otherwise, charges will be billed on the next bill date only if it's
329 within the current calendar month.
331 -a I<archivedir>: Save a copy of the downloaded file to I<archivedir>.
333 -P I<port>: Connect to that TCP port.
335 -C I<category>: The name of a package category to use when creating package
338 -e I<pkgpart>: The pkgpart (L<FS::part_pkg>) to use for E911 charges. A
339 package of this type will be ordered for each invoice that has E911-subject
340 line items. The 'quantity' field on this package will be set to the total
341 quantity of those line items.
343 The E911 package must be a one-time package (flat rate, no frequency, no
344 recurring fee) with setup fee equal to the fee per line.