# Copyright (c) 2023, SolutionERP LLC and Contributors
# License: MIT. See LICENSE


import xhiveframework
from pypika.terms import ExistsCriterion


def execute():
	pl = xhiveframework.qb.DocType("Pick List")
	se = xhiveframework.qb.DocType("Stock Entry")
	dn = xhiveframework.qb.DocType("Delivery Note")

	(
		xhiveframework.qb.update(pl).set(
			pl.status,
			(
				xhiveframework.qb.terms.Case()
				.when(pl.docstatus == 0, "Draft")
				.when(pl.docstatus == 2, "Cancelled")
				.else_("Completed")
			),
		)
	).run()

	(
		xhiveframework.qb.update(pl)
		.set(pl.status, "Open")
		.where(
			(
				ExistsCriterion(
					xhiveframework.qb.from_(se).select(se.name).where((se.docstatus == 1) & (se.pick_list == pl.name))
				)
				| ExistsCriterion(
					xhiveframework.qb.from_(dn).select(dn.name).where((dn.docstatus == 1) & (dn.pick_list == pl.name))
				)
			).negate()
			& (pl.docstatus == 1)
		)
	).run()
