# Copyright (c) 2021, JINGROW
# For license information, please see license.txt


import jingrow
from jingrow.utils import update_progress_bar


def execute():
	jingrow.reload_pg("jcloud", "pagetype", "invoice")
	# only apply to invoices that has credits applied
	invoices = jingrow.db.get_all(
		"Invoice", {"pagestatus": 1, "applied_credits": (">", 0)}, pluck="name"
	)

	total_invoices = len(invoices)
	for i, inv in enumerate(invoices):
		update_progress_bar("Updating invoices", i, total_invoices)
		invoice = jingrow.get_pg("Invoice", inv)
		invoice.compute_free_credits()
		invoice.db_set("free_credits", invoice.free_credits, update_modified=False)
