import xhiveframework


def execute():
	xhiveframework.reload_doctype("Maintenance Visit")
	xhiveframework.reload_doctype("Maintenance Visit Purpose")

	# Updates the Maintenance Schedule link to fetch serial nos
	from xhiveframework.query_builder.functions import Coalesce

	mvp = xhiveframework.qb.DocType("Maintenance Visit Purpose")
	mv = xhiveframework.qb.DocType("Maintenance Visit")

	xhiveframework.qb.update(mv).join(mvp).on(mvp.parent == mv.name).set(
		mv.maintenance_schedule, Coalesce(mvp.prevdoc_docname, "")
	).where(
		(mv.maintenance_type == "Scheduled") & (mvp.prevdoc_docname.notnull()) & (mv.docstatus < 2)
	).run(
		as_dict=1
	)
