假设我们知道 Project Name 为 001
,那么我们获取 Project 唯一标识:
ref_no = '001'
project = frappe.db.get_value("Project", {"project_name": ref_no}, "name")
if not project:
frappe.throw(f"未找到项目:{ref_no}", frappe.DoesNotExistError)
创建 Timesheet
now = now_datetime()
# 第一步:创建 Timesheet 文档
timesheet = frappe.new_doc("Timesheet")
timesheet.employee = None # 或实际员工邮箱/ID frappe.session.user
timesheet.parent_project = project
timesheet.start_date = now.strftime("%Y-%m-%d")
timesheet.end_date = now.strftime("%Y-%m-%d")
timesheet.append("time_logs", {
"activity_type": None,
"from_time": now,
"project": project,
"to_time": now.replace(hour=now.hour + 1), # 假设工时为1小时
"hours": 1
})
# 插入并提交 Timesheet
timesheet.insert()
# timesheet.submit() # 暂不提交,保留 draft 状态
frappe.db.commit() # 强制提交事务(通常不需要,但可用于调试)
# 第二步:创建 File 文档并附加到 Timesheet(如需要添加文件)
file_doc = frappe.get_doc({
"doctype": "File",
"file_url": "https://your-url/your-file.pdf", # 或使用 file_name + content 创建文件
"attached_to_doctype": "Timesheet",
"attached_to_name": timesheet.name,
"is_private": 0, # 设置为 1 表示私有文件
"file_name": "your-file.pdf",
})
file_doc.insert()
frappe.db.commit() # 强制提交事务(通常不需要,但可用于调试)
需要注意,Timesheet 中的可选字段不能为空串,要么设置为 None