# Copyright (c) 2017, Xhiveframework and Contributors
# License: GNU General Public License v3. See license.txt


import xhiveframework

from xhiveerp.manufacturing.doctype.work_order.work_order import create_job_card


def execute():
	xhiveframework.reload_doc("manufacturing", "doctype", "work_order")
	xhiveframework.reload_doc("manufacturing", "doctype", "work_order_item")
	xhiveframework.reload_doc("manufacturing", "doctype", "job_card")
	xhiveframework.reload_doc("manufacturing", "doctype", "job_card_item")

	fieldname = xhiveframework.db.get_value(
		"DocField", {"fieldname": "work_order", "parent": "Timesheet"}, "fieldname"
	)
	if not fieldname:
		fieldname = xhiveframework.db.get_value(
			"DocField", {"fieldname": "production_order", "parent": "Timesheet"}, "fieldname"
		)
		if not fieldname:
			return

	for d in xhiveframework.get_all(
		"Timesheet", filters={fieldname: ["!=", ""], "docstatus": 0}, fields=[fieldname, "name"]
	):
		if d[fieldname]:
			doc = xhiveframework.get_doc("Work Order", d[fieldname])
			for row in doc.operations:
				create_job_card(doc, row, auto_create=True)
			xhiveframework.delete_doc("Timesheet", d.name)
