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


import jingrow


def execute():
	jingrow.reload_pg("jcloud", "pagetype", "invoice")
	jingrow.reload_pg("jcloud", "pagetype", "invoice_item")

	# invoice site usage -> invoice item
	jingrow.db.sql(
		"""
		update
			`tabInvoice Item` i,
			`tabInvoice Site Usage` u
		set
			i.document_type = 'Site',
			i.document_name = u.site,
			i.plan = u.plan
		where
			u.parent = i.parent
			and u.idx = i.idx
	"""
	)

	# compute applied_credits
	jingrow.db.sql(
		"""
		update
			tabInvoice
		set
			applied_credits = -1 * (starting_balance - ending_balance)
	"""
	)
