Last active
March 29, 2021 09:43
-
-
Save pythonandchips/4ea495a423bd97df82f9afd467a0c83e to your computer and use it in GitHub Desktop.
backfill bill items
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def backfill_bill_items | |
bills = Bill.all | |
progress_bar = ProgressBar.new(bills.count) | |
# Keeping the batch size low to reduce the time we are locking the 100 records | |
# for update | |
bills.select( | |
:id, | |
:contact_id, | |
:reference, | |
:company_id, | |
:depreciation_schedule, | |
:general_ledger_account_id, | |
:manual_sales_tax_amount, | |
:sales_tax_rate, | |
:second_sales_tax_rate, | |
:stock_altering_quantity, | |
:stock_item_id, | |
:total_value, | |
).includes(:contact, :bill_items).lock("FOR UPDATE").find_each(batch_size: 100) do |bill| | |
begin | |
params = bill.attributes.symbolize_keys.slice(*Billing::Params::BILL_ITEM_ATTRIBUTES) | |
bill_item = bill.bill_items.first | |
if bill_item.nil? | |
item_type = bill.stock_item_id ? LineItem::STOCK : LineItem::NO_UNIT | |
bill_item = bill.bill_items.build( | |
{ | |
company_id: bill.company_id, | |
quantity: 1, | |
item_type: item_type, | |
description: bill.description | |
}.merge(params) | |
) | |
bill_item.save(validate: false) | |
end | |
rescue StandardError => ex | |
Rails.logger.info({ | |
event: "BILL_ITEM_BACKFILL_ITEM_FAILED", | |
exception: ex.message, | |
bill_id: bill.id | |
}) | |
raise | |
end | |
progress_bar.increment! | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks good 👍