+=item estimate
+
+Calculates current prices for all items on this quotation, including
+discounts and taxes, and updates the quotation_pkg records accordingly.
+
+=cut
+
+sub estimate {
+ my $self = shift;
+ my $conf = FS::Conf->new;
+
+ my %pkgnum_of; # quotationpkgnum => temporary pkgnum
+
+ my $me = "[quotation #".$self->quotationnum."]"; # for debug messages
+
+ my @return_bill = ([]);
+ my $error;
+
+ ###### BEGIN TRANSACTION ######
+ local $@;
+ eval {
+ my $temp_dbh = myconnect();
+ local $FS::UID::dbh = $temp_dbh;
+ local $FS::UID::AutoCommit = 0;
+
+ my $fake_self = FS::quotation->new({ $self->hash });
+
+ # if this is a prospect, make them into a customer for now
+ # XXX prospects currently can't have service locations
+ my $cust_or_prospect = $self->cust_or_prospect;
+ my $cust_main;
+ if ( $cust_or_prospect->isa('FS::prospect_main') ) {
+ $cust_main = $cust_or_prospect->convert_cust_main;
+ die "$cust_main (simulating customer signup)\n" unless ref $cust_main;
+ $fake_self->set('prospectnum', '');
+ $fake_self->set('custnum', $cust_main->custnum);
+ } else {
+ $cust_main = $cust_or_prospect;
+ }
+
+ # order packages
+ $error = $fake_self->order(\%pkgnum_of);
+ die "$error (simulating package order)\n" if $error;
+
+ my @new_pkgs = map { FS::cust_pkg->by_key($_) } values(%pkgnum_of);
+
+ # simulate the first bill
+ my %bill_opt = (
+ 'estimate' => 1,
+ 'pkg_list' => \@new_pkgs,
+ 'time' => time, # an option to adjust this?
+ 'return_bill' => $return_bill[0],
+ 'no_usage_reset' => 1,
+ );
+ $error = $cust_main->bill(%bill_opt);
+ die "$error (simulating initial billing)\n" if $error;
+
+ # pick dates for future bills
+ my %next_bill_pkgs;
+ foreach (@new_pkgs) {
+ my $bill = $_->get('bill');
+ next if !$bill;
+ push @{ $next_bill_pkgs{$bill} ||= [] }, $_;
+ }
+
+ my $i = 1;
+ foreach my $next_bill (keys %next_bill_pkgs) {
+ $bill_opt{'time'} = $next_bill;
+ $bill_opt{'return_bill'} = $return_bill[$i] = [];
+ $bill_opt{'pkg_list'} = $next_bill_pkgs{$next_bill};
+ $error = $cust_main->bill(%bill_opt);
+ die "$error (simulating recurring billing cycle $i)\n" if $error;
+ $i++;
+ }
+
+ $temp_dbh->rollback;
+ };
+ return $@ if $@;
+ ###### END TRANSACTION ######
+ my %quotationpkgnum_of = reverse %pkgnum_of;
+
+ if ($DEBUG) {
+ warn "pkgnums:\n".Dumper(\%pkgnum_of);
+ warn Dumper(\@return_bill);
+ }
+
+ # Careful: none of the foreign keys in here are correct outside the sandbox.
+ # We have a translation table for pkgnums; all others are total lies.
+
+ my %quotation_pkg; # quotationpkgnum => quotation_pkg
+ foreach my $qp ($self->quotation_pkg) {
+ $quotation_pkg{$qp->quotationpkgnum} = $qp;
+ $qp->set($_, 0) foreach qw(unitsetup unitrecur);
+ $qp->set('freq', '');
+ # flush old tax records
+ foreach ($qp->quotation_pkg_tax) {
+ $error = $_->delete;
+ return "$error (flushing tax records for pkgpart ".$qp->part_pkg->pkgpart.")"
+ if $error;
+ }
+ }
+
+ my %quotation_pkg_tax; # quotationpkgnum => tax name => quotation_pkg_tax obj
+ my %quotation_pkg_discount; # quotationpkgnum => quotation_pkg_discount obj
+
+ for (my $i = 0; $i < scalar(@return_bill); $i++) {
+ my $this_bill = $return_bill[$i]->[0];
+ if (!$this_bill) {
+ warn "$me billing cycle $i produced no invoice\n";
+ next;
+ }
+
+ my @nonpkg_lines;
+ my %cust_bill_pkg;
+ foreach my $cust_bill_pkg (@{ $this_bill->get('cust_bill_pkg') }) {
+ my $pkgnum = $cust_bill_pkg->pkgnum;
+ $cust_bill_pkg{ $cust_bill_pkg->billpkgnum } = $cust_bill_pkg;
+ if ( !$pkgnum ) {
+ # taxes/fees; come back to it
+ push @nonpkg_lines, $cust_bill_pkg;
+ next;
+ }
+ my $quotationpkgnum = $quotationpkgnum_of{$pkgnum};
+ my $qp = $quotation_pkg{$quotationpkgnum};
+ if (!$qp) {
+ # XXX supplemental packages could do this (they have separate pkgnums)
+ # handle that special case at some point
+ warn "$me simulated bill returned a package not on the quotation (pkgpart ".$cust_bill_pkg->pkgpart.")\n";
+ next;
+ }
+ if ( $i == 0 ) {
+ # then this is the first (setup) invoice
+ $qp->set('start_date', $cust_bill_pkg->sdate);
+ $qp->set('unitsetup', $qp->unitsetup + $cust_bill_pkg->unitsetup);
+ # pkgpart_override is a possibility
+ } else {
+ # recurring invoice (should be only one of these per package, though
+ # it may have multiple lineitems with the same pkgnum)
+ $qp->set('unitrecur', $qp->unitrecur + $cust_bill_pkg->unitrecur);
+ }
+
+ # discounts
+ if ( $cust_bill_pkg->get('discounts') ) {
+ my $discount = $cust_bill_pkg->get('discounts')->[0];
+ if ( $discount ) {
+ # discount records are generated as (setup, recur).
+ # well, not always, sometimes it's just (recur), but fixing this
+ # is horribly invasive.
+ my $qpd = $quotation_pkg_discount{$quotationpkgnum}
+ ||= qsearchs('quotation_pkg_discount', {
+ 'quotationpkgnum' => $quotationpkgnum
+ });
+
+ if (!$qpd) { #can't happen
+ warn "$me simulated bill returned a discount but no discount is in effect.\n";
+ }
+ if ($discount and $qpd) {
+ if ( $i == 0 ) {
+ $qpd->set('setup_amount', $discount->amount);
+ } else {
+ $qpd->set('recur_amount', $discount->amount);
+ }
+ }
+ }
+ } # end of discount stuff
+
+ }
+
+ # create tax records
+ foreach my $cust_bill_pkg (@nonpkg_lines) {
+
+ my $itemdesc = $cust_bill_pkg->itemdesc;
+
+ if ($cust_bill_pkg->feepart) {
+ warn "$me simulated bill included a non-package fee (feepart ".
+ $cust_bill_pkg->feepart.")\n";
+ next;
+ }
+ my $links = $cust_bill_pkg->get('cust_bill_pkg_tax_location') ||
+ $cust_bill_pkg->get('cust_bill_pkg_tax_rate_location') ||
+ [];
+ # breadth-first unrolled recursion:
+ # take each tax link and any tax-on-tax descendants, and merge them
+ # into a single quotation_pkg_tax record for each pkgnum/taxname
+ # combination
+ while (my $tax_link = shift @$links) {
+ my $target = $cust_bill_pkg{ $tax_link->taxable_billpkgnum }
+ or die "$me unable to resolve tax link\n";
+ if ($target->pkgnum) {
+ my $quotationpkgnum = $quotationpkgnum_of{$target->pkgnum};
+ # create this if there isn't one yet
+ my $qpt = $quotation_pkg_tax{$quotationpkgnum}{$itemdesc} ||=
+ FS::quotation_pkg_tax->new({
+ quotationpkgnum => $quotationpkgnum,
+ itemdesc => $itemdesc,
+ setup_amount => 0,
+ recur_amount => 0,
+ });
+ if ( $i == 0 ) { # first invoice
+ $qpt->set('setup_amount', $qpt->setup_amount + $tax_link->amount);
+ } else { # subsequent invoices
+ # this isn't perfectly accurate, but that's why it's an estimate
+ $qpt->set('recur_amount', $qpt->recur_amount + $tax_link->amount);
+ $qpt->set('setup_amount', sprintf('%.2f', $qpt->setup_amount - $tax_link->amount));
+ $qpt->set('setup_amount', 0) if $qpt->setup_amount < 0;
+ }
+ } elsif ($target->feepart) {
+ # do nothing; we already warned for the fee itself
+ } else {
+ # tax on tax: the tax target is another tax item.
+ # since this is an estimate, I'm just going to assign it to the
+ # first of the underlying packages. (RT#5243 is why we can't have
+ # nice things.)
+ my $sublinks = $target->cust_bill_pkg_tax_rate_location;
+ if ($sublinks and $sublinks->[0]) {
+ $tax_link->set('taxable_billpkgnum', $sublinks->[0]->taxable_billpkgnum);
+ push @$links, $tax_link; #try again
+ } else {
+ warn "$me unable to assign tax on tax; ignoring\n";
+ }
+ }
+ } # while my $tax_link
+
+ } # foreach my $cust_bill_pkg
+ }
+ foreach my $quotation_pkg (values %quotation_pkg) {
+ $error = $quotation_pkg->replace;
+ return "$error (recording estimate for ".$quotation_pkg->part_pkg->pkg.")"
+ if $error;
+ }
+ foreach my $quotation_pkg_discount (values %quotation_pkg_discount) {
+ $error = $quotation_pkg_discount->replace;
+ return "$error (recording estimated discount)"
+ if $error;
+ }
+ foreach my $quotation_pkg_tax (map { values %$_ } values %quotation_pkg_tax) {
+ $error = $quotation_pkg_tax->insert;
+ return "$error (recording estimated tax for ".$quotation_pkg_tax->itemdesc.")"
+ if $error;
+ }
+ return;
+}
+