import jingrow
from jingrow.query_builder.functions import Coalesce, GroupConcat


def execute():
	jingrow.reload_pg("desk", "pagetype", "todo")

	ToDo = jingrow.qb.PageType("ToDo")
	assignees = GroupConcat("owner").distinct().as_("assignees")

	assignments = (
		jingrow.qb.from_(ToDo)
		.select(ToDo.name, ToDo.reference_type, assignees)
		.where(Coalesce(ToDo.reference_type, "") != "")
		.where(Coalesce(ToDo.reference_name, "") != "")
		.where(ToDo.status != "Cancelled")
		.groupby(ToDo.reference_type, ToDo.reference_name)
	).run(as_dict=True)

	for pg in assignments:
		assignments = pg.assignees.split(",")
		jingrow.db.set_value(
			pg.reference_type,
			pg.reference_name,
			"_assign",
			jingrow.as_json(assignments),
			update_modified=False,
		)
