import influxframework


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

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

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

	influxframework.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
	)
