def as_txt(): response = Response() response.mimetype = 'text' response.charset = 'utf-8' response.headers["Content-Disposition"] = ("attachment; filename=\"%s.txt\"" % frappe.response['doctype'].replace(' ', '_')).encode("utf-8") response.data = frappe.response['result'] return response
def as_json(*args, **kwargs): """constructs and formats response as json""" make_logs() response = Response() if frappe.local.response.http_status_code: response.status_code = frappe.local.response['http_status_code'] del frappe.local.response['http_status_code'] response.mimetype = 'application/json' response.charset = 'utf-8' response.headers["X-Frame-Options"] = "DENY" response.headers["X-Content-Type-Options"] = "nosniff" response.headers[ "Strict-Transport-Security"] = "max-age=31536000; includeSubDomains" response.headers["Cache-Control"] = "no-store" response.headers[ "Content-Security-Policy"] = "default-src https: frame-ancestors 'none'" response.headers["Feature-Policy"] = "'none'" response.headers["Referrer-Policy"] = "no-referrer" data = kwargs.get("data") status_code = data.get("status_code") if "status_code" in data: del data["status_code"] response.status_code = status_code or kwargs.get("status_code") or 200 response.data = json.dumps(kwargs.get("data"), default=json_handler, separators=(',', ':')) return response
def get_xml(name): doc = frappe.get_doc("Tax Report GTGT01", name) if not doc.has_permission("read"): raise frappe.PermissionError if (doc.period_type == "Month"): #convert from_date from_date = get_first_day(str(doc.period_num) + '-' + str(doc.year)) doc.to_date = get_last_day(doc.period_num + '-' + doc.year) #frappe.msgprint(doc.from_date) if (doc.period_type == "Quarter"): #convert from_date period_num = "1" if (doc.period_num == "2"): period_num = "4" if (doc.period_num == "3"): period_num = "7" if (doc.period_num == "4"): period_num = "10" doc.from_date = get_first_day(str(period_num) + '-' + str(doc.year)) doc.to_date = add_months(doc.from_date, 3) doc.to_date = add_days(doc.to_date, -1) response = Response() response.mimetype = 'text/xml' response.charset = 'utf-8' # response.headers[b"Content-Disposition"] = ("attachment; filename=\"%s.xml\"" % "gtgt01").encode("utf-8") response.data = frappe.render_template( "templates/print_format/tax_report_gtgt01.xml", dict(doc=doc)) return response
def as_txt(): response = Response() response.mimetype = 'text' response.charset = 'utf-8' response.headers["Content-Disposition"] = ("attachment; filename=\"%s.txt\"" % frappe.response['doctype'].replace(' ', '_')).encode("utf-8") response.data = frappe.response['result'] return response
def shipstation_xml(): root = etree.Element("Orders") out = etree.tostring(root, pretty_print=True) response = Response() response.mimetype = "text/xml" response.charset = "utf-8" response.data = out return response
def as_csv(): response = Response() response.mimetype = 'text/csv' response.charset = 'utf-8' response.headers["Content-Disposition"] = ( "attachment; filename=\"%s.csv\"" % dataent.response['doctype'].replace(' ', '_')).encode("utf-8") response.data = dataent.response['result'] return response
def as_txt(): response = Response() response.mimetype = "text" response.charset = "utf-8" response.headers["Content-Disposition"] = ( 'attachment; filename="%s.txt"' % frappe.response["doctype"].replace(" ", "_")).encode("utf-8") response.data = frappe.response["result"] return response
def get_token_response(body, content_type='application/json'): if content_type == 'application/json': body = json.dumps(body) response = Response(body) response.status = HTTP_STATUS_CODES[200] response.status_code = 200 response.charset = 'utf-8' response.content_type = content_type return response
def build_page(request): response = Response() data = dash_dispatcher(request) response.data = data response.status_code = 200 response.mimetype = 'text/html' response.charset = 'utf-8' return response
def as_json(): make_logs() response = Response() if frappe.local.response.http_status_code: response.status_code = frappe.local.response['http_status_code'] del frappe.local.response['http_status_code'] response.mimetype = 'application/json' response.charset = 'utf-8' response.data = json.dumps(frappe.local.response, default=json_handler, separators=(',',':')) return response
def as_json(): make_logs() response = Response() if frappe.local.response.http_status_code: response.status_code = frappe.local.response['http_status_code'] del frappe.local.response['http_status_code'] response.mimetype = 'application/json' response.charset = 'utf-8' response.data = json.dumps(frappe.local.response, default=json_handler, separators=(',',':')) return response
def as_json(): make_logs() response = Response() if frappe.local.response.http_status_code: response.status_code = frappe.local.response["http_status_code"] del frappe.local.response["http_status_code"] response.mimetype = "application/json" response.charset = "utf-8" response.data = json.dumps(frappe.local.response, default=json_handler, separators=(",", ":")) return response
def build_ajax(request): response = Response() data = dash_dispatcher(request) if isinstance(data, dict): data = json.dumps(data) response.data = data response.status_code = 200 response.mimetype = 'application/json' response.charset = 'utf-8' return response
def download_file(): print("Inside Download") response = Response() filename = "qrcode.txt" frappe.response.filename = "qrcode.txt" response.mimetype = 'text/plain' response.charset = 'utf-8' with open("site1.local/public/files/qrcode.txt", "rb") as fileobj: filedata = fileobj.read() print("Created Filedata") frappe.response.filecontent = filedata print("Created Filecontent") response.type = "download" response.headers[b"Content-Disposition"] = ("filename=\"%s\"" % frappe.response['filename'].replace(' ', '_')).encode("utf-8") response.data = frappe.response['filecontent'] print(frappe.response)
def build_ajax(request): response = Response() data = dash_dispatcher(request) if data: if isinstance(data, dict): data = json.dumps(data) response.data = data response.status_code = 200 response.mimetype = 'application/json' response.charset = 'utf-8' else: # incase of dash.exceptions.PreventUpdate or dash.no_update # data will == '' # response with 204 response.status_code = 204 return response
def search_test_result(): file_name = "Bella_M.JPG" url_addon = "private/" search = "<div style='float:left'>" search += "<img src='/" + url_addon + "files/" + file_name + "' alt='' style='width:200px' />" search += "</div>" search += "<div style='float:left;padding-left: 10px;'>Searching Image</div>" from werkzeug.wrappers import Response response = Response() response.mimetype = 'text/html' response.charset = 'utf-8' response.data = "<html><head><title>Test</title></head><body><table><tr><td>" + \ search + "</td></tr><tr><td>" + \ ('</td></tr><tr><td>'.join(search_result(file_name, url_addon))) + \ "</td></tr></table></body></html>" return response
def mark_attendance(**args): args = frappe._dict(args) employee = args.get("userid") posix_timestamp = args.get("att_time") att_type = args.get("att_type") stgid = args.get("stgid") token = args.get("auth_token") # create the custom response response = Response() response.mimetype = 'text/plain' response.charset = 'utf-8' response.data = "ok" if not employee or not posix_timestamp or not stgid or not token: log_error("invalid data", args) return response # TODO validate URL/IP if provided if not frappe.db.exists("Custom Biometric Unit Integration Settings", {"device_id": stgid}): log_error("settings for device missing", args) return response auth_token = frappe.db.get_value( "Custom Biometric Unit Integration Settings", {"device_id": stgid}, "auth_token") if not auth_token or (auth_token and auth_token != token): log_error("device auth error", args) return response if not frappe.db.exists("Employee", employee): log_error("employee not found", args) return response try: timestamp = float(posix_timestamp) tz = pytz.timezone('UTC') dt = datetime.fromtimestamp(timestamp, tz) dt = get_datetime_str(dt) date = getdate(dt) except: log_error("invalid timestamp", args) return response attendance = None company = frappe.db.get_value("Employee", employee, "company") attendance_name = frappe.db.exists("Attendance", { "employee": employee, "attendance_date": date }) if attendance_name: attendance = frappe.get_doc("Attendance", attendance_name) if attendance: if attendance.docstatus == 1: log_error("attendance already submitted", args) return response else: attendance.cams_out = dt attendance.cams_out_device = stgid else: try: attendance = frappe.get_doc({ "doctype": "Attendance", "employee": employee, "attendance_date": date, "company": company, "status": "Present", "cams_in": dt, "cams_in_device": stgid, "cams_spend": None }).insert(ignore_permissions=1) frappe.db.commit() return response except: log_error("insert attendance", args) return response if attendance.cams_in and attendance.cams_out: attendance.cams_spend = time_diff(attendance.cams_out, attendance.cams_in) try: attendance.db_update() frappe.db.commit() except: log_error("update attendance", args) return response return response
def attendance(): # restrict request from list of IP addresses # create the custom response response = Response() response.mimetype = 'text/plain' response.charset = 'utf-8' response.data = "ok" try: userid = frappe.form_dict.get("userid") employee = frappe.db.get_value("Employee", { "biometric_id": userid, 'status': 'Active'}) if employee: date = time.strftime("%Y-%m-%d", time.gmtime( int(frappe.form_dict.get("att_time")))) name, company = frappe.db.get_value( "Employee", employee, ["employee_name", "company"]) attendance_id = frappe.db.get_value("Attendance", { "employee": employee, "attendance_date": date}) is_leave = check_leave_record(employee, date) if is_leave == 'On Leave': attendance = frappe.new_doc("Attendance") in_time = time.strftime("%H:%M:%S", time.gmtime( int(frappe.form_dict.get("att_time")))) attendance.update({ "employee": employee, "employee_name": name, "attendance_date": date, "status": "On Leave", "in_time": "00:00:00", "out_time": "00:00:00", "company": company }) attendance.save(ignore_permissions=True) attendance.submit() frappe.db.commit() return response else: if attendance_id: attendance = frappe.get_doc("Attendance", attendance_id) out_time = time.strftime("%H:%M:%S", time.gmtime( int(frappe.form_dict.get("att_time")))) if not attendance.in_time: attendance.in_time = out_time else: times = [out_time, attendance.in_time] attendance.out_time = max(times) attendance.in_time = min(times) send_present_alert(employee,name,attendance.in_time,date,out_time) attendance.db_update() frappe.db.commit() # return employee,name,attendance.in_time,date,out_time return response else: attendance = frappe.new_doc("Attendance") in_time = time.strftime("%H:%M:%S", time.gmtime( int(frappe.form_dict.get("att_time")))) attendance.update({ "employee": employee, "employee_name": name, "attendance_date": date, "status": "Present", "in_time": in_time, "company": company }) attendance.save(ignore_permissions=True) attendance.submit() frappe.db.commit() send_present_alert(employee, name, in_time, date) return response else: employee = frappe.form_dict.get("userid") date = time.strftime("%Y-%m-%d", time.gmtime( int(frappe.form_dict.get("att_time")))) ure_id = frappe.db.get_value("Unregistered Employee", { "employee": employee, "attendance_date": date}) if ure_id: attendance = frappe.get_doc( "Unregistered Employee", ure_id) out_time = time.strftime("%H:%M:%S", time.gmtime( int(frappe.form_dict.get("att_time")))) times = [out_time, attendance.in_time] attendance.out_time = max(times) attendance.in_time = min(times) attendance.db_update() frappe.db.commit() else: attendance = frappe.new_doc("Unregistered Employee") in_time = time.strftime("%H:%M:%S", time.gmtime( int(frappe.form_dict.get("att_time")))) attendance.update({ "employee": employee, "attendance_date": date, "stgid": frappe.form_dict.get("stgid"), "in_time": in_time, }) attendance.save(ignore_permissions=True) frappe.db.commit() return response except frappe.ValidationError as e: log_error("ValidationError", e) return response
def make_report(names): import json if names[0] != "[": names = [names] else: names = json.loads(names) # setup html tags html = "<html><head><title>Print Report</title></head><body style='margin: 0; padding-left: 100px; padding-right: 100px;'>" # get all docs docs = frappe.db.get_values("Sales Order", {"name":("in", names)}, "*", as_dict=True, order_by="delivery_date") # header html += u"<h1 align=center> Поръчки " if len(docs) > 0: if docs[0].delivery_date: if len(docs) > 1 and docs[len(docs) - 1].delivery_date: html += u"от " else: html += u"за "; html += safe_str(docs[0].delivery_date.strftime("%d") + "-" + docs[0].delivery_date.strftime("%m") + "-" + docs[0].delivery_date.strftime("%Y")) + u"г. " if len(docs) > 1 and docs[len(docs) - 1].delivery_date: html += u"до " + safe_str(docs[len(docs) - 1].delivery_date.strftime("%d") + "-" + docs[len(docs) - 1].delivery_date.strftime("%m") + "-" + docs[len(docs) - 1].delivery_date.strftime("%Y")) + u"г. " html += "</h1><br/><br/>" # doc info and attachments for doc in docs: attachments = frappe.db.sql("""SELECT * FROM `tabFile` WHERE `attached_to_doctype`='Sales Order' AND `attached_to_name`=%s;""", (doc.name), as_dict=True) items = frappe.db.sql("""SELECT * FROM `tabSales Order Item` WHERE `parent`=%s;""", (doc.name), as_dict=True) # doc name html += u"<font style='font-weight: bold;background-color: yellow;'> ⏺ </font>" html += "<font style='font-weight: bold;background-color: yellow;'>" + doc.title + "</font>" # doc date info = False if doc.delivery_date: if not info: html += " - " info = True html += u"Срок " date = safe_str(doc.delivery_date.strftime("%d") + "-" + doc.delivery_date.strftime("%m") + "-" + doc.delivery_date.strftime("%Y")) import datetime d = datetime.datetime.now() now = '-'.join(safe_str(x) for x in (d.day, d.month, d.year)) html += "<font color='" if datetime.datetime.strptime(now, "%d-%m-%Y") >= datetime.datetime.strptime(date, "%d-%m-%Y"): html += "red" else: html += "blue" html += "'>"+date + u"г. </font>" # doc item info and type image html += "<br/>" for item in items: # doc item name html += "<div style='padding-left: 30px; padding-right: 30px;'>- " if item.type==u"Механизъм": html += item.item_name else: html += item.cdescription + "<br/>" # doc item koja section if item.estestvena_koja or item.eco_koja or item.damaska: koja = False html += "<b>" if item.estestvena_koja: html += u"Естествена кожа" koja = True if item.eco_koja: if koja: html += ", " html += u"Еко кожа" koja = True if item.damaska: if koja: html += ", " html += u"Дамаска" html += u" от Димела</b>" if item.collection_1 or item.collection_2 or item.collection_3: html += '<table style="width:100%;border-collapse: collapse;border 0px; margin-left: 30px; margin-right: 30px;">' if item.collection_1: html += collection(item, 1) if item.collection_2: html += collection(item, 2) if item.collection_3: html += collection(item, 3) if item.collection_1 or item.collection_2 or item.collection_3: html += "</table>" # doc item pillow section if item.divan_pillow_collection_1 or item.divan_pillow_collection_2 or item.divan_pillow_collection_3: html += u'<b>Декоративни възглавници</b><table style="width:100%;border-collapse: collapse;border 0px; margin-left: 30px; margin-right: 30px;">' if item.divan_pillow_collection_1: html += divan_pillow_collection(item, 1) if item.divan_pillow_collection_2: html += divan_pillow_collection(item, 2) if item.divan_pillow_collection_3: html += divan_pillow_collection(item, 3) if item.divan_pillow_collection_1 or item.divan_pillow_collection_2 or item.divan_pillow_collection_3: html += "</table>" # doc item type image html += "</div>" if item.divan_modification or item.image: html += "<div style='margin-left: auto; margin-right: auto; display: block; text-align: center;'>" if item.divan_modification: html += "<img src='/private/files/divan_" + item.divan_modification + "' alt='' style='vertical-align: top;max-height: 150px;' />" if item.image: html += "<img src='/private/files/divan_" + item.image + "' alt='' style='vertical-align: top;max-height: 150px;' />" html += "</div><br/>" # doc attachment images if len(attachments) > 0: html += "<div style='margin-left: auto; margin-right: auto; display: block; text-align: center;'>" for doc_file in attachments: html += "<img src='" + doc_file.file_url + "' alt='' style='vertical-align: top;max-height: 150px;' />" html += "</div><br/>" html += "<br/>" # html end tags html += "</body></html>" from werkzeug.wrappers import Response response = Response() response.mimetype = 'text/html' response.charset = 'utf-8' response.data = html return response
def as_text(): response = Response() response.mimetype = 'text/plain' response.charset = 'utf-8' response.data = frappe.local.response.message return response
def as_text(): response = Response() response.mimetype = 'text/plain' response.charset = 'utf-8' response.data = frappe.local.response.message return response
def attendance(**args): args = frappe._dict(args) global attendance_date, att_time userid = args.get("userid") biotime = args.get("att_time") att_type = args.get("att_type") stgid = args.get("stgid") token = args.get("auth_token") employee = frappe.db.get_value("Employee", { "biometric_id": userid, "status": "Active" }) response = Response() response.mimetype = 'text/plain' response.charset = 'utf-8' response.data = "ok" auth_token = frappe.db.get_value("Biometric Settings", {"device_id": stgid}, "auth_token") if not auth_token or (auth_token and auth_token != token): log_error("device auth error", args) return response if employee: log_error("att", args) create_pr(userid, biotime, employee) date = time.strftime( "%Y-%m-%d", time.gmtime(int(frappe.form_dict.get("att_time")))) date = datetime.strptime(date, "%Y-%m-%d").date() attendance_date = time.strftime( "%Y-%m-%d %X", time.gmtime(int(frappe.form_dict.get("att_time")))) time_m = time.strftime( "%H:%M:%S", time.gmtime(int(frappe.form_dict.get("att_time")))) frappe.errprint(time_m) time_m = datetime.strptime(time_m, '%H:%M:%S').time() m_time = datetime.combine(date, time_m) total_working_hours = 0 doc = frappe.get_doc("Employee", employee) if doc.date_of_joining > date: log_error( "Attendance date can not be less than employee's joining date", args) return response if doc.employment_type == 'Contract' or doc.employment_type == 'Operator' or doc.designation == 'Operator': # if doc.select_biometric_machine ! = 'Reception': a_min_time = datetime.strptime('07:30', '%H:%M') a_max_time = datetime.strptime('08:30', '%H:%M') b_min_time = datetime.strptime('04:30', '%H:%M') b_max_time = datetime.strptime('05:30', '%H:%M') c_min_time = datetime.strptime('00:30', '%H:%M') c_max_time = datetime.strptime('01:30', '%H:%M') d_min_time = datetime.strptime('20:00', '%H:%M') d_max_time = datetime.strptime('21:00', '%H:%M') e_min_time = datetime.strptime('18:30', '%H:%M') e_max_time = datetime.strptime('19:30', '%H:%M') if att_type == 'in': attendance_id = frappe.db.exists("Attendance", { "employee": doc.name, "attendance_date": date }) if attendance_id: attendance = frappe.get_doc("Attendance", attendance_id) attendance.update({"in_time": m_time}) attendance.db_update() else: intime = datetime.strptime(str(time_m), '%H:%M:%S') if intime >= a_min_time and intime <= a_max_time: shift = "A" elif intime >= b_min_time and intime <= b_max_time: shift = "B" elif intime >= c_min_time and intime <= c_max_time: shift = "C" elif intime >= d_min_time and intime <= d_max_time: shift = "D" elif intime >= e_min_time and intime <= e_max_time: shift = "E" else: shift = "NA" attendance = frappe.new_doc("Attendance") attendance.update({ "employee": employee, "employee_name": doc.employee_name, "employment_type": doc.employment_type, "attendance_date": date, "shift": shift, "status": "Present", "in_time": m_time, "company": doc.company }) attendance.save(ignore_permissions=True) attendance.submit() frappe.db.commit() return response if att_type == 'out': attendance_id = frappe.db.exists("Attendance", { "employee": doc.name, "attendance_date": date }) if attendance_id: attendance = frappe.get_doc("Attendance", attendance_id) if attendance.in_time: attendance_in_time = datetime.strptime( attendance.in_time, '%Y-%m-%d %H:%M:%S').time() times = [time_m, attendance_in_time] attendance.out_date = date in_time = min(times) out_time = max(times) final_out_time = datetime.combine(date, out_time) attendance.out_time = final_out_time final_in_time = datetime.combine(date, in_time) attendance.in_time = final_in_time attendance.status = "Present" in_time_f = timedelta(hours=in_time.hour, minutes=in_time.minute, seconds=in_time.second) out_time_f = timedelta(hours=out_time.hour, minutes=out_time.minute, seconds=out_time.second) actual_working_hours = frappe.db.get_value( "Employee", doc.employee, "working_hours") if actual_working_hours: diff2 = (out_time_f - in_time_f) td = diff2 - actual_working_hours if actual_working_hours > (out_time_f - in_time_f): td = (out_time_f - in_time_f) worked_hrs = time_diff_in_seconds( out_time_f, in_time_f) total_working_hours = (worked_hrs / 3600.00) if td.seconds >= 2700: total_working_hours = math.ceil( total_working_hours) else: total_working_hours = math.floor( total_working_hours) attendance.total_working_hours = total_working_hours else: attendance.out_time = datetime.combine(date, time_m) attendance.db_update() frappe.db.commit() return response else: prev_attendance_id = frappe.db.get_value( "Attendance", { "employee": doc.name, "attendance_date": add_days(date, -1) }) if prev_attendance_id: attendance = frappe.get_doc("Attendance", prev_attendance_id) if attendance.in_time and not attendance.out_time: in_time = datetime.strptime( attendance.in_time, '%Y-%m-%d %H:%M:%S').time() attendance.out_date = date out_time = time_m final_out_time = datetime.combine(date, out_time) attendance.out_time = final_out_time in_time_f = timedelta(hours=in_time.hour, minutes=in_time.minute, seconds=in_time.second) out_time_f = timedelta(hours=out_time.hour, minutes=out_time.minute, seconds=out_time.second) actual_working_hours = frappe.db.get_value( "Employee", doc.employee, "working_hours") if actual_working_hours: td = (out_time_f - in_time_f) - actual_working_hours if actual_working_hours > (out_time_f - in_time_f): td = (out_time_f - in_time_f) if out_time_f <= in_time_f: min_hr = timedelta(hours=24) worked_hrs = time_diff_in_seconds( out_time_f + min_hr, in_time_f) else: worked_hrs = time_diff_in_seconds( out_time_f, in_time_f) total_working_hours = (worked_hrs / 3600.00) if td.seconds >= 2700: total_working_hours = math.ceil( total_working_hours) else: total_working_hours = math.floor( total_working_hours) attendance.total_working_hours = total_working_hours attendance.db_update() frappe.db.commit() log_error("no in today,prev day full punch", args) return response else: log_error("no in today,prev day no punch", args) return response else: return response else: employee = frappe.form_dict.get("userid") date = time.strftime( "%Y-%m-%d", time.gmtime(int(frappe.form_dict.get("att_time")))) date = datetime.strptime(date, "%Y-%m-%d").date() ure_id = frappe.db.get_value("Unregistered Employee", { "employee": employee, "attendance_date": date }) if ure_id: attendance = frappe.get_doc("Unregistered Employee", ure_id) out_time = time.strftime( "%H:%M:%S", time.gmtime(int(frappe.form_dict.get("att_time")))) times = [out_time, attendance.in_time] out_time = max(times) in_time = min(times) attendance.in_time = in_time attendance.out_time = out_time attendance.db_update() frappe.db.commit() else: attendance = frappe.new_doc("Unregistered Employee") in_time = time.strftime( "%H:%M:%S", time.gmtime(int(frappe.form_dict.get("att_time")))) attendance.update({ "employee": employee, "attendance_date": date, "stgid": frappe.form_dict.get("stgid"), "in_time": in_time, }) attendance.save(ignore_permissions=True) frappe.db.commit() return response