def get_data(filters=None): logs = frappe.db.sql( "SELECT * FROM `tabTransaction Log` order by creation desc ", as_dict=1) result = [] for l in logs: row_index = int(l.row_index) if row_index > 1: previous_hash = frappe.db.sql( "SELECT chaining_hash FROM `tabTransaction Log` WHERE row_index = {0}" .format(row_index - 1)) if not previous_hash: integrity = False else: integrity = check_data_integrity(l.chaining_hash, l.transaction_hash, l.previous_hash, previous_hash[0][0]) result.append([ _(str(integrity)), _(l.reference_doctype), l.document_name, l.owner, l.modified_by, format_datetime(l.timestamp, "YYYYMMDDHHmmss") ]) else: result.append([ _("First Transaction"), _(l.reference_doctype), l.document_name, l.owner, l.modified_by, format_datetime(l.timestamp, "YYYYMMDDHHmmss") ]) return result
def get_dict(start, end, slots=None): return { "start": start.isoformat(), "end": end.isoformat(), "title": "{0}-{1}".format(format_datetime(start, "HH:mm"), format_datetime(end, "HH:mm")) }
def get_date_let(d, data): let_dates = [x.get("GlPostDate") for x in data if (x.get("against_voucher") == d.get("against_voucher") and x.get("against_voucher_type") == d.get("against_voucher_type") and x.get("party") == d.get("party"))] if not let_dates or len(let_dates) == 1: let_vouchers = frappe.get_all("GL Entry", filters={"against_voucher": d.get("against_voucher"), "against_voucher_type": d.get("against_voucher_type"), "party": d.get("party")}, fields=["posting_date"]) if len(let_vouchers) > 1: return format_datetime(max([x.get("posting_date") for x in let_vouchers]), "yyyyMMdd") return format_datetime(max(let_dates), "yyyyMMdd") if len(let_dates) > 1 else None
def notifify_admin_access_to_system_manager(login_manager=None): if (login_manager and login_manager.user == "Administrator" and frappe.local.conf.notifify_admin_access_to_system_manager): message = """<p> {dear_system_manager} <br><br> {access_message} <br><br> {is_it_unauthorized} </p>""".format( dear_system_manager=_("Dear System Manager,"), access_message=_( """Administrator accessed {0} on {1} via IP Address {2}.""" ).format( """<a href="{site}" target="_blank">{site}</a>""".format( site=frappe.local.request.host_url), """<b>{date_and_time}</b>""".format( date_and_time=format_datetime(now_datetime(), format_string="medium")), frappe.local.request_ip), is_it_unauthorized= _("If you think this is unauthorized, please change the Administrator password." )) frappe.sendmail(recipients=get_system_managers(), subject=_("Administrator Logged In"), message=message, bulk=True)
def validate_return_against(doc): if not frappe.db.exists(doc.doctype, doc.return_against): frappe.throw(_("Invalid {0}: {1}") .format(doc.meta.get_label("return_against"), doc.return_against)) else: ref_doc = frappe.get_doc(doc.doctype, doc.return_against) party_type = "customer" if doc.doctype in ("Sales Invoice", "Delivery Note") else "supplier" if ref_doc.company == doc.company and ref_doc.get(party_type) == doc.get(party_type) and ref_doc.docstatus == 1: # validate posting date time return_posting_datetime = "%s %s" % (doc.posting_date, doc.get("posting_time") or "00:00:00") ref_posting_datetime = "%s %s" % (ref_doc.posting_date, ref_doc.get("posting_time") or "00:00:00") if get_datetime(return_posting_datetime) < get_datetime(ref_posting_datetime): frappe.throw(_("Posting timestamp must be after {0}").format(format_datetime(ref_posting_datetime))) # validate same exchange rate if doc.conversion_rate != ref_doc.conversion_rate: frappe.throw(_("Exchange Rate must be same as {0} {1} ({2})") .format(doc.doctype, doc.return_against, ref_doc.conversion_rate)) # validate update stock if doc.doctype == "Sales Invoice" and doc.update_stock and not ref_doc.update_stock: frappe.throw(_("'Update Stock' can not be checked because items are not delivered via {0}") .format(doc.return_against))
def validate_return_against(doc): if not frappe.db.exists(doc.doctype, doc.return_against): frappe.throw( _("Invalid {0}: {1}").format(doc.meta.get_label("return_against"), doc.return_against)) else: ref_doc = frappe.get_doc(doc.doctype, doc.return_against) party_type = "customer" if doc.doctype in ( "Sales Invoice", "Delivery Note") else "supplier" if ref_doc.company == doc.company and ref_doc.get( party_type) == doc.get(party_type) and ref_doc.docstatus == 1: # validate posting date time return_posting_datetime = "%s %s" % ( doc.posting_date, doc.get("posting_time") or "00:00:00") ref_posting_datetime = "%s %s" % (ref_doc.posting_date, ref_doc.get("posting_time") or "00:00:00") if get_datetime(return_posting_datetime) < get_datetime( ref_posting_datetime): frappe.throw( _("Posting timestamp must be after {0}").format( format_datetime(ref_posting_datetime))) # validate same transaction type if doc.meta.get_field( "transaction_type" ) and doc.transaction_type != ref_doc.transaction_type: frappe.throw( _("Transaction Type must be the same as {0} {1} ({2})").format( doc.doctype, doc.return_against, ref_doc.transaction_type))
def add_data_row(row_group, dt, parentfield, doc, rowidx): d = doc.copy() meta = frappe.get_meta(dt) if all_doctypes: d.name = '"' + d.name + '"' if len(row_group) < rowidx + 1: row_group.append([""] * (len(columns) + 1)) row = row_group[rowidx] _column_start_end = column_start_end.get((dt, parentfield)) if _column_start_end: for i, c in enumerate(columns[_column_start_end. start:_column_start_end.end]): df = meta.get_field(c) fieldtype = df.fieldtype if df else "Data" value = d.get(c, "") if value: if fieldtype == "Date": value = formatdate(value) elif fieldtype == "Datetime": value = format_datetime(value) row[_column_start_end.start + i + 1] = value
def export_csv(company_name, fiscal_year): """Export FEC (Fichier des Ecritures Comptables)""" data = get_result(company_name, fiscal_year) # print(data) # filename format must be "SirenFECAAAAMMJJ.csv" siret = frappe.db.get_value("Company", company_name, "siret").replace( " ", "") or "" fiscal_year_end_date = frappe.db.get_value("Fiscal Year", fiscal_year, "year_end_date") filename = siret[:9] + "FEC" + format_datetime(fiscal_year_end_date, "yyyyMMdd") + ".csv" # generate data f = StringIO() writer = csv.writer(f, delimiter=u'\t'.encode('utf8')) for r in data: # encode only unicode type strings and not int, floats etc. writer.writerow( map(lambda v: isinstance(v, text_type) and v.encode('utf-8') or v, r)) f.seek(0) # send response frappe.local.response.filename = filename frappe.local.response.filecontent = text_type(f.read(), 'utf-8') frappe.local.response.type = "download"
def send_event_digest(doc, user): today = nowdate() events = get_events(today, today, True, for_reminder=True) send_events = {} send_emails = [] if events: for e in events: e.starts_on = format_datetime(e.starts_on, 'hh:mm a') #if e.all_day: # e.starts_on = "All Day" if e.employee_emails: employee_emails = e.employee_emails.split(',') for email in employee_emails: if email not in send_emails: send_emails.append(email) if send_emails: for email in send_emails: for e in events: if email in e.employee_emails: if not send_events.get(email): send_events[email] = [] send_events[email].append(e) if send_events.get(email): frappe.sendmail( recipients=email, subject=frappe._("Upcoming Booking Events for Today"), template="upcoming_events", args={ 'events': events, }, header=[frappe._("Events in Today's Calendar"), 'blue'])
def validate_return_against(doc): filters = {"doctype": doc.doctype, "docstatus": 1, "company": doc.company} if doc.meta.get_field("customer") and doc.customer: filters["customer"] = doc.customer elif doc.meta.get_field("supplier") and doc.supplier: filters["supplier"] = doc.supplier if not frappe.db.exists(filters): frappe.throw(_("Invalid {0}: {1}") .format(doc.meta.get_label("return_against"), doc.return_against)) else: ref_doc = frappe.get_doc(doc.doctype, doc.return_against) # validate posting date time return_posting_datetime = "%s %s" % (doc.posting_date, doc.get("posting_time") or "00:00:00") ref_posting_datetime = "%s %s" % (ref_doc.posting_date, ref_doc.get("posting_time") or "00:00:00") if get_datetime(return_posting_datetime) < get_datetime(ref_posting_datetime): frappe.throw(_("Posting timestamp must be after {0}").format(format_datetime(ref_posting_datetime))) # validate same exchange rate if doc.conversion_rate != ref_doc.conversion_rate: frappe.throw(_("Exchange Rate must be same as {0} {1} ({2})") .format(doc.doctype, doc.return_against, ref_doc.conversion_rate)) # validate update stock if doc.doctype == "Sales Invoice" and doc.update_stock and not ref_doc.update_stock: frappe.throw(_("'Update Stock' can not be checked because items are not delivered via {0}") .format(doc.return_against))
def validate_return_against(doc): if not doc.return_against: frappe.throw(_("{0} is mandatory for Return").format(doc.meta.get_label("return_against"))) else: filters = {"doctype": doc.doctype, "docstatus": 1, "company": doc.company} if doc.meta.get_field("customer"): filters["customer"] = doc.customer elif doc.meta.get_field("supplier"): filters["supplier"] = doc.supplier if not frappe.db.exists(filters): frappe.throw(_("Invalid {0}: {1}") .format(doc.meta.get_label("return_against"), doc.return_against)) else: ref_doc = frappe.get_doc(doc.doctype, doc.return_against) # validate posting date time return_posting_datetime = "%s %s" % (doc.posting_date, doc.get("posting_time") or "00:00:00") ref_posting_datetime = "%s %s" % (ref_doc.posting_date, ref_doc.get("posting_time") or "00:00:00") if get_datetime(return_posting_datetime) < get_datetime(ref_posting_datetime): frappe.throw(_("Posting timestamp must be after {0}").format(format_datetime(ref_posting_datetime))) # validate same exchange rate if doc.conversion_rate != ref_doc.conversion_rate: frappe.throw(_("Exchange Rate must be same as {0} {1} ({2})") .format(doc.doctype, doc.return_against, ref_doc.conversion_rate)) # validate update stock if doc.doctype == "Sales Invoice" and doc.update_stock and not ref_doc.update_stock: frappe.throw(_("'Update Stock' can not be checked because items are not delivered via {0}") .format(doc.return_against))
def add_row_ciel(self, doc): ecriture_num = '{:>5s}'.format(doc.get("name")[-5:]) journal_code = '{:<2s}'.format(self.journal_code) ecriture_date = format_datetime(doc.get("posting_date"), "yyyyMMdd") if doc.get("against_voucher_type") == "Purchase Invoice": echeance_date = format_datetime(doc.get("pinv_due_date"), "yyyyMMdd") elif doc.get("against_voucher_type") == "Sales Invoice": echeance_date = format_datetime(doc.get("sinv_due_date"), "yyyyMMdd") else: echeance_date = '{:<8s}'.format("") piece_num = '{:<12s}'.format(doc.get("voucher_no")) if doc.get("party_type") == "Supplier": compte_num = '{}{:<8s}'.format("401", doc.get("supp_subl_acc") or '') elif doc.get("party_type") == "Customer": compte_num = '{}{:<8s}'.format("411", doc.get("cust_subl_acc") or '') else: compte_num = '{:<11s}'.format(doc.get("account_number")) libelle = '{}{:<17s}'.format("FACTURE ", doc.get("voucher_no")[:17]) montant = '{:>13.2f}'.format(doc.get("debit")) if doc.get("debit") != 0 \ else '{:>13.2f}'.format(doc.get("credit")) credit_debit = "D" if doc.get("debit") > 0 else "C" numero_pointage = piece_num code_analytic = '{:<6s}'.format("") if doc.get("party_type") in ("Supplier", "Customer"): libelle_compte = '{:<34s}'.format(doc.get("party"))[:34] else: libelle_compte = '{:<34s}'.format(doc.get("account_name"))[:34] euro = "O" row = [ ecriture_num, journal_code, ecriture_date, echeance_date, piece_num, compte_num, libelle, montant, credit_debit, numero_pointage, code_analytic, libelle_compte, euro ] return ''.join(row)
def web(method, url, kwargs={}): res = {} escape = kwargs.pop('escape', False) as_json = kwargs.pop('as_json', False) if hasattr(requests, method): res.update(vars(getattr(requests, method)(url, **kwargs))) for k, v in res.items(): if k == '_content': try: res[k] = json.loads(res[k]) except ValueError: try: if as_json: res[k] = xmltodict.parse(res[k]) elif escape: res[k] = cgi.escape(res[k]) except ValueError: pass elif k == 'headers': res[k] = dict(res[k]) elif hasattr(v, 'get_dict'): #Cookies res[k] = res[k].get_dict() for sk, sv in res[k].items(): if hasattr(sv, 'strftime'): res[k][sk] = format_datetime(sv) elif isinstance(sv, datetime.timedelta): res[k][sk] = { 'days': sv.days, 'seconds': sv.seconds, 'microseconds': sv.microseconds } elif hasattr(v, 'strftime'): # Date and Datetimes res[k] = format_datetime(v) elif isinstance(v, datetime.timedelta): res[k] = { 'days': v.days, 'seconds': v.seconds, 'microseconds': v.microseconds } elif callable(v): res[k] = res[k]() elif inspect.isclass(v) or k in ('raw', 'request', 'connection'): res.pop(k) return json.loads(frappe.as_json(res))
def test_format_datetime(self): # Test formatdate with various default date formats set for date_fmt, valid_date in test_date_formats.items(): frappe.db.set_default("date_format", date_fmt) frappe.local.user_date_format = None for time_fmt, valid_time in test_time_formats.items(): frappe.db.set_default("time_format", time_fmt) frappe.local.user_time_format = None valid_fmt = valid_date + ' ' + valid_time self.assertEqual(format_datetime(test_datetime), valid_fmt)
def get_employees_who_are_born_today(): """Get Employee properties whose birthday is today.""" return frappe.db.get_values("Employee", fieldname=["name", "personal_email", "company", "company_email", "user_id", "employee_name"], filters={ "date_of_birth": ("like", "%{}".format(format_datetime(getdate(), "-MM-dd"))), "status": "Active", }, as_dict=True )
def get_data(filters=None): if filters is None: return [] documents = frappe.get_all(filters.get("doctype"), filters={"docstatus": [">", 0]}) modules = get_versions_data(filters.get("doctype")) doc_meta = frappe.get_meta(filters.get("doctype")) if not modules: frappe.throw( _("The versioning document for this doctype could not be found")) result = [] for document in documents: doc = frappe.get_doc(filters.get("doctype"), document.name) if doc._seal is None: comment = _("This document is not sealed") result.append([doc.name, format_datetime(doc.creation), doc.owner,\ "Out", comment, "", "", "", ""]) continue sealed_doc = get_sealed_doc(doc, modules, doc._seal_version, True) # Check for renamed links link_fields = get_link_fields(sealed_doc, doc_meta) if link_fields: submission_date = get_submission_date(doc) sealed_doc = revise_renamed_links(sealed_doc, link_fields, submission_date) if sealed_doc: seal = get_chained_seal(sealed_doc) integrity = "Yes" if seal == doc._seal else "No" comment = _( "Data integrity verified") if integrity == "Yes" else _( "Data integrity could not be verified") result.append([doc.name, format_datetime(doc.creation), doc.owner,\ integrity, comment, seal, doc._seal, doc._seal_version]) return result
def add_job(j, name): if j.kwargs.get('site')==frappe.local.site: jobs.append({ 'job_name': j.kwargs.get('kwargs', {}).get('playbook_method') \ or str(j.kwargs.get('job_name')), 'status': j.status, 'queue': name, 'creation': format_datetime(j.created_at), 'color': colors[j.status] }) if j.exc_info: jobs[-1]['exc_info'] = j.exc_info
def add_job(j, name): if j.kwargs.get('site')==frappe.local.site: jobs.append({ 'job_name': j.kwargs.get('kwargs', {}).get('playbook_method') \ or str(j.kwargs.get('job_name')), 'status': j.status, 'queue': name, 'creation': format_datetime(convert_utc_to_user_timezone(j.created_at)), 'color': colors[j.status] }) if j.exc_info: jobs[-1]['exc_info'] = j.exc_info
def get_employee_field_property(employee, fieldname): if employee and fieldname: field = frappe.get_meta("Employee").get_field(fieldname) value = frappe.db.get_value("Employee", employee, fieldname) options = field.options if field.fieldtype == "Date": value = formatdate(value) elif field.fieldtype == "Datetime": value = format_datetime(value) return {"value": value, "datatype": field.fieldtype, "label": field.label, "options": options} else: return False
def format_value(value, df, doc=None, currency=None, translated=False): # Convert dict to object if necessary if (isinstance(df, dict)): df = frappe._dict(df) if value is None: value = "" elif translated: value = frappe._(value) if not df: return value elif df.get("fieldtype") == "Date": return formatdate(value) elif df.get("fieldtype") == "Datetime": return format_datetime(value) elif value == 0 and df.get("fieldtype") in ( "Int", "Float", "Currency", "Percent") and df.get("print_hide_if_no_value"): # this is required to show 0 as blank in table columns return "" elif df.get("fieldtype") == "Currency" or (df.get("fieldtype") == "Float" and (df.options or "").strip()): return fmt_money(value, precision=get_field_precision(df, doc), currency=currency if currency else (get_field_currency(df, doc) if doc else None)) elif df.get("fieldtype") == "Float": precision = get_field_precision(df, doc) # show 1.000000 as 1 # options should not specified if not df.options and value is not None: temp = cstr(value).split(".") if len(temp) == 1 or cint(temp[1]) == 0: precision = 0 return fmt_money(value, precision=precision) elif df.get("fieldtype") == "Percent": return "{}%".format(flt(value, 2)) elif df.get("fieldtype") in ("Text", "Small Text"): if not re.search("(\<br|\<div|\<p)", value): return value.replace("\n", "<br>") return value
def test_format_datetime_forced_broken_locale(self): # Test with forced datetime formats # Currently format_datetime defaults to yyyy-MM-dd HH:mm:ss # if the locale is broken, so this is an expected failure. lang = frappe.local.lang # Force fallback from Babel try: frappe.local.lang = 'FAKE' self.assertEqual( format_datetime(test_datetime, 'dd-yyyy-MM ss:mm:HH'), test_date_obj.strftime('%d-%Y-%m %S:%M:%H')) finally: frappe.local.lang = lang
def update_delivery_date(delivery_date=None): quotation = _get_cart_quotation() minimum_d_day = frappe.db.get_single_value('E Commerce Settings', 'minimum_days_delivery_date') minimum_d_date = datetime.datetime.strptime( add_days(now(), minimum_d_day)[:19], '%Y-%m-%d %H:%M:%S') if not isinstance(delivery_date, datetime.datetime): d_date = datetime.datetime.strptime(delivery_date, "%d/%m/%Y %H:%M:%S") if d_date < minimum_d_date: frappe.throw( _("La date & l'heure de livraison minimales sont {0}").format( format_datetime(minimum_d_date))) else: quotation.delivery_date = d_date quotation.flags.ignore_permissions = True quotation.save() else: d_date = delivery_date if d_date < minimum_d_date: frappe.throw( _("La date & l'heure de livraison minimales sont {0}").format( format_datetime(minimum_d_date))) return d_date
def add_job(job: 'Job', name: str) -> None: if job.kwargs.get('site') == frappe.local.site: job_info = { 'job_name': job.kwargs.get('kwargs', {}).get('playbook_method') or job.kwargs.get('kwargs', {}).get('job_type') or str(job.kwargs.get('job_name')), 'status': job.get_status(), 'queue': name, 'creation': format_datetime(convert_utc_to_user_timezone(job.created_at)), 'color': JOB_COLORS[job.get_status()] } if job.exc_info: job_info['exc_info'] = job.exc_info jobs.append(job_info)
def format_value(value, df, doc=None, currency=None, translated=False): # Convert dict to object if necessary if (isinstance(df, dict)): df = frappe._dict(df) if value is None: value = "" elif translated: value = frappe._(value) if not df: return value elif df.get("fieldtype")=="Date": return formatdate(value) elif df.get("fieldtype")=="Datetime": return format_datetime(value) elif value==0 and df.get("fieldtype") in ("Int", "Float", "Currency", "Percent") and df.get("print_hide_if_no_value"): # this is required to show 0 as blank in table columns return "" elif df.get("fieldtype") == "Currency" or (df.get("fieldtype")=="Float" and (df.options or "").strip()): return fmt_money(value, precision=get_field_precision(df, doc), currency=currency if currency else (get_field_currency(df, doc) if doc else None)) elif df.get("fieldtype") == "Float": precision = get_field_precision(df, doc) # show 1.000000 as 1 # options should not specified if not df.options and value is not None: temp = cstr(value).split(".") if len(temp)==1 or cint(temp[1])==0: precision = 0 return fmt_money(value, precision=precision) elif df.get("fieldtype") == "Percent": return "{}%".format(flt(value, 2)) elif df.get("fieldtype") in ("Text", "Small Text"): if not re.search("(\<br|\<div|\<p)", value): return value.replace("\n", "<br>") return value
def get_employee_field_property(employee, fieldname): if employee and fieldname: field = frappe.get_meta("Employee").get_field(fieldname) value = frappe.db.get_value("Employee", employee, fieldname) options = field.options if field.fieldtype == "Date": value = formatdate(value) elif field.fieldtype == "Datetime": value = format_datetime(value) return { "value" : value, "datatype" : field.fieldtype, "label" : field.label, "options" : options } else: return False
def notify_admin_access_to_system_manager(login_manager=None): if (login_manager and login_manager.user == "Administrator" and frappe.local.conf.notify_admin_access_to_system_manager): site = '<a href="{0}" target="_blank">{0}</a>'.format(frappe.local.request.host_url) date_and_time = '<b>{0}</b>'.format(format_datetime(now_datetime(), format_string="medium")) ip_address = frappe.local.request_ip access_message = _('Administrator accessed {0} on {1} via IP Address {2}.').format( site, date_and_time, ip_address) frappe.sendmail( recipients=get_system_managers(), subject=_("Administrator Logged In"), template="administrator_logged_in", args={'access_message': access_message}, header=['Access Notification', 'orange'] )
def notify_admin_access_to_system_manager(login_manager=None): if (login_manager and login_manager.user == "Administrator" and frappe.local.conf.notify_admin_access_to_system_manager): site = '<a href="{0}" target="_blank">{0}</a>'.format( frappe.local.request.host_url) date_and_time = '<b>{0}</b>'.format( format_datetime(now_datetime(), format_string="medium")) ip_address = frappe.local.request_ip access_message = _( 'Administrator accessed {0} on {1} via IP Address {2}.').format( site, date_and_time, ip_address) frappe.sendmail(recipients=get_system_managers(), subject=_("Administrator Logged In"), template="administrator_logged_in", args={'access_message': access_message}, header=['Access Notification', 'orange'])
def add_data_row(row_group, dt, doc, rowidx): d = doc.copy() meta = frappe.get_meta(dt) if all_doctypes: d.name = '"'+ d.name+'"' if len(row_group) < rowidx + 1: row_group.append([""] * (len(columns) + 1)) row = row_group[rowidx] for i, c in enumerate(columns[column_start_end[dt].start:column_start_end[dt].end]): df = meta.get_field(c) fieldtype = df.fieldtype if df else "Data" value = d.get(c, "") if value: if fieldtype == "Date": value = formatdate(value) elif fieldtype == "Datetime": value = format_datetime(value) row[column_start_end[dt].start + i + 1] = value
def send_event_digest(): today = nowdate() for user in get_enabled_system_users(): events = get_events(today, today, user.name, for_reminder=True) if events: frappe.set_user_lang(user.name, user.language) for e in events: e.starts_on = format_datetime(e.starts_on, 'hh:mm a') if e.all_day: e.starts_on = "All Day" frappe.sendmail( recipients=user.email, subject=frappe._("Upcoming Events for Today"), template="upcoming_events", args={ 'events': events, }, header=[frappe._("Events in Today's Calendar"), 'blue'])
def send_event_digest(): today = nowdate() for user in get_enabled_system_users(): events = get_events(today, today, user.name, for_reminder=True) if events: frappe.set_user_lang(user.name, user.language) for e in events: e.starts_on = format_datetime(e.starts_on, 'hh:mm a') if e.all_day: e.starts_on = "All Day" frappe.sendmail( recipients=user.email, subject=frappe._("Upcoming Events for Today"), template="upcoming_events", args={ 'events': events, }, header=[frappe._("Events in Today's Calendar"), 'blue'] )
def add_job(job: "Job", name: str) -> None: if job.kwargs.get("site") == frappe.local.site: job_info = { "job_name": job.kwargs.get("kwargs", {}).get("playbook_method") or job.kwargs.get("kwargs", {}).get("job_type") or str(job.kwargs.get("job_name")), "status": job.get_status(), "queue": name, "creation": format_datetime(convert_utc_to_user_timezone(job.created_at)), "color": JOB_COLORS[job.get_status()], } if job.exc_info: job_info["exc_info"] = job.exc_info jobs.append(job_info)
def add_data_row(row_group, dt, doc, rowidx): # print "Adddddd ddddaaaaaaaaattttttttttttttttttttaaaaaaa" d = doc.copy() meta = frappe.get_meta(dt) if all_doctypes: d.name = '"' + d.name + '"' if len(row_group) < rowidx + 1: row_group.append([""] * (len(columns) + 1)) row = row_group[rowidx] for i, c in enumerate(columns[column_start_end[dt]. start:column_start_end[dt].end]): df = meta.get_field(c) fieldtype = df.fieldtype if df else "Data" value = d.get(c, "") if value: if fieldtype == "Date": value = formatdate(value) elif fieldtype == "Datetime": value = format_datetime(value) row[column_start_end[dt].start + i + 1] = value
def notifify_admin_access_to_system_manager(login_manager=None): if (login_manager and login_manager.user == "Administrator" and frappe.local.conf.notifify_admin_access_to_system_manager): message = """<p> {dear_system_manager} <br><br> {access_message} <br><br> {is_it_unauthorized} </p>""".format( dear_system_manager=_("Dear System Manager,"), access_message=_("""Administrator accessed {0} on {1} via IP Address {2}.""").format( """<a href="{site}" target="_blank">{site}</a>""".format(site=frappe.local.request.host_url), """<b>{date_and_time}</b>""".format(date_and_time=format_datetime(now_datetime(), format_string="medium")), frappe.local.request_ip ), is_it_unauthorized=_("If you think this is unauthorized, please change the Administrator password.") ) frappe.sendmail(recipients=get_system_managers(), subject=_("Administrator Logged In"), message=message, bulk=True)
def add_data_row(self, rows, dt, parentfield, doc, rowidx): d = doc.copy() meta = frappe.get_meta(dt) if self.all_doctypes: d.name = '"'+ d.name+'"' if len(rows) < rowidx + 1: rows.append([""] * (len(self.columns) + 1)) row = rows[rowidx] _column_start_end = self.column_start_end.get((dt, parentfield)) if _column_start_end: for i, c in enumerate(self.columns[_column_start_end.start:_column_start_end.end]): df = meta.get_field(c) fieldtype = df.fieldtype if df else "Data" value = d.get(c, "") if value: if fieldtype == "Date": value = formatdate(value) elif fieldtype == "Datetime": value = format_datetime(value) row[_column_start_end.start + i + 1] = value
def get_result_as_list(data, filters): result = [] company_currency = frappe.db.get_value("Company", filters.company, "default_currency") accounts = frappe.get_all("Account", filters={"Company": filters.company}, fields=["name", "account_number"]) for d in data: JournalCode = re.split("-|/", d.get("voucher_no"))[0] EcritureNum = re.split("-|/", d.get("voucher_no"))[1] EcritureDate = format_datetime(d.get("GlPostDate"), "yyyyMMdd") account_number = [ account.account_number for account in accounts if account.name == d.get("account") ] if account_number[0] is not None: CompteNum = account_number[0] else: frappe.throw( _("Account number for account {0} is not available.<br> Please setup your Chart of Accounts correctly." ).format(account.name)) if d.get("party_type") == "Customer": CompAuxNum = d.get("cusName") CompAuxLib = d.get("customer_name") elif d.get("party_type") == "Supplier": CompAuxNum = d.get("supName") CompAuxLib = d.get("supplier_name") else: CompAuxNum = "" CompAuxLib = "" ValidDate = format_datetime(d.get("GlPostDate"), "yyyyMMdd") PieceRef = d.get("voucher_no") if d.get( "voucher_no") else "Sans Reference" # EcritureLib is the reference title unless it is an opening entry if d.get("is_opening") == "Yes": EcritureLib = _("Opening Entry Journal") if d.get("voucher_type") == "Sales Invoice": EcritureLib = d.get("InvTitle") elif d.get("voucher_type") == "Purchase Invoice": EcritureLib = d.get("PurTitle") elif d.get("voucher_type") == "Journal Entry": EcritureLib = d.get("JnlTitle") elif d.get("voucher_type") == "Payment Entry": EcritureLib = d.get("PayTitle") else: EcritureLib = d.get("voucher_type") PieceDate = format_datetime(d.get("GlPostDate"), "yyyyMMdd") debit = '{:.2f}'.format(d.get("debit")).replace(".", ",") credit = '{:.2f}'.format(d.get("credit")).replace(".", ",") Idevise = d.get("account_currency") if Idevise != company_currency: Montantdevise = '{:.2f}'.format(d.get("debitCurr")).replace( ".", ",") if d.get("debitCurr") != 0 else '{:.2f}'.format( d.get("creditCurr")).replace(".", ",") else: Montantdevise = '{:.2f}'.format(d.get("debit")).replace( ".", ",") if d.get("debit") != 0 else '{:.2f}'.format( d.get("credit")).replace(".", ",") row = [ JournalCode, d.get("voucher_type"), EcritureNum, EcritureDate, CompteNum, d.get("account"), CompAuxNum, CompAuxLib, PieceRef, PieceDate, EcritureLib, debit, credit, "", "", ValidDate, Montantdevise, Idevise ] result.append(row) return result
def format_value(value, df=None, doc=None, currency=None, translated=False): '''Format value based on given fieldtype, document reference, currency reference. If docfield info (df) is not given, it will try and guess based on the datatype of the value''' if isinstance(df, string_types): df = frappe._dict(fieldtype=df) if not df: df = frappe._dict() if isinstance(value, datetime.datetime): df.fieldtype = 'Datetime' elif isinstance(value, datetime.date): df.fieldtype = 'Date' elif isinstance(value, datetime.timedelta): df.fieldtype = 'Time' elif isinstance(value, int): df.fieldtype = 'Int' elif isinstance(value, float): df.fieldtype = 'Float' else: df.fieldtype = 'Data' elif (isinstance(df, dict)): # Convert dict to object if necessary df = frappe._dict(df) if value is None: value = "" elif translated: value = frappe._(value) if not df: return value elif df.get("fieldtype")=="Date": return formatdate(value) elif df.get("fieldtype")=="Datetime": return format_datetime(value) elif df.get("fieldtype")=="Time": return format_time(value) elif value==0 and df.get("fieldtype") in ("Int", "Float", "Currency", "Percent") and df.get("print_hide_if_no_value"): # this is required to show 0 as blank in table columns return "" elif df.get("fieldtype") == "Currency" or (df.get("fieldtype")=="Float" and (df.options or "").strip()): return fmt_money(value, precision=get_field_precision(df, doc), currency=currency if currency else (get_field_currency(df, doc) if doc else None)) elif df.get("fieldtype") == "Float": precision = get_field_precision(df, doc) # show 1.000000 as 1 # options should not specified if not df.options and value is not None: temp = cstr(value).split(".") if len(temp)==1 or cint(temp[1])==0: precision = 0 return fmt_money(value, precision=precision) elif df.get("fieldtype") == "Percent": return "{}%".format(flt(value, 2)) elif df.get("fieldtype") in ("Text", "Small Text"): if not re.search("(\<br|\<div|\<p)", value): return value.replace("\n", "<br>") return value
def get_data(filters=None): logs = frappe.db.sql("SELECT * FROM `tabTransaction Log` order by creation desc ", as_dict=1) result = [] for l in logs: row_index = int(l.row_index) if row_index > 1: previous_hash = frappe.db.sql("SELECT chaining_hash FROM `tabTransaction Log` WHERE row_index = {0}".format(row_index - 1)) if not previous_hash: integrity = False else: integrity = check_data_integrity(l.chaining_hash, l.transaction_hash, l.previous_hash, previous_hash[0][0]) result.append([_(str(integrity)), _(l.reference_doctype), l.document_name, l.owner, l.modified_by, format_datetime(l.timestamp, "YYYYMMDDHHmmss")]) else: result.append([_("First Transaction"), _(l.reference_doctype), l.document_name, l.owner, l.modified_by, format_datetime(l.timestamp, "YYYYMMDDHHmmss")]) return result
def get_result_as_list(data, company): result = [] company_currency = frappe.db.get_value("Company", company, "default_currency") # Journal dict journal_dict = {} journal_list = frappe.db.get_all("Mode of Payment Account", filters=[["company", "=", company], ["journal_code", "!=", ""]], fields=['journal_code', 'journal_label']) for i, elt in enumerate(journal_list): journal_dict[elt["journal_code"]] = elt["journal_label"] row = [ "JournalCode", "JournalLib", "EcritureNum", "EcritureDate", "CompteNum", "CompteLib", "CompAuxNum", "CompAuxLib", "PieceRef", "PieceDate", "EcritureLib", "Debit", "Credit", "EcritureLet", "DateLet", "ValidDate", "Montantdevise", "Idevise" ] result.append(row) for d in data: # 1. Le code journal de l'écriture comptable journal_code = d.get("voucher_no").split("-")[0] # 2. Le libellé journal de l'écriture comptable if d.get("voucher_type") == "Sales Invoice": journal_lib = "Journal des Ventes" elif d.get("voucher_type") == "Purchase Invoice": journal_lib = "Journal des Achats" elif d.get("voucher_type") == "Payment Entry": if journal_code in journal_dict.keys(): journal_lib = journal_dict[journal_code] else: journal_lib = "Journal de Tresorerie" elif d.get("voucher_type") == "Period Closing Voucher": journal_lib = "Journal de Cloture" elif d.get("is_opening") == "Yes": journal_lib = "Journal des A-Nouveaux" else: journal_lib = "Journal des Operations Diverses" # 3. Le numéro sur une séquence continue de l'écriture comptable ecriture_num = d.get("voucher_no").split("-")[-1] # 4. La date de comptabilisation de l'écriture comptable ecriture_date = format_datetime(d.get("posting_date"), "yyyyMMdd") # 5. Le numéro de compte, dont les trois premiers caractères doivent correspondre à # des chiffres respectant les normes du plan comptable français compte_num = '{:<08d}'.format( int(d.get("account").split("|")[0].strip())) # 6. Le libellé de compte, conformément à la nomenclature du plan comptable français compte_lib = unidecode.unidecode( d.get("account")).split("|")[-1].strip() # 7. Le numéro de compte auxiliaire (à blanc si non utilisé) # 8. Le libellé de compte auxiliaire (à blanc si non utilisé) if d.get("party_type") == "Customer": comp_aux_num = unidecode.unidecode(d.get("party")) comp_aux_lib = unidecode.unidecode(d.get("customer_name")) elif d.get("party_type") == "Supplier": comp_aux_num = unidecode.unidecode(d.get("party")) comp_aux_lib = unidecode.unidecode(d.get("supplier_name")) else: comp_aux_num = "" comp_aux_lib = "" # 9. La référence de la pièce justificative # 10. La date de la pièce justificative if d.get("against_voucher_type") == "Sales Invoice": piece_ref = d.get("against_voucher") piece_date = format_datetime(d.get("sinv_posting_date"), "yyyyMMdd") elif d.get("against_voucher_type") == "Purchase Invoice": piece_ref = d.get("against_voucher") piece_date = format_datetime(d.get("pinv_posting_date"), "yyyyMMdd") elif d.get("against_voucher_type") == "Journal Entry": piece_ref = d.get("against_voucher") piece_date = format_datetime(d.get("jv_posting_date"), "yyyyMMdd") elif d.get("against_voucher_type") == "Payment Entry": piece_ref = d.get("against_voucher") piece_date = format_datetime(d.get("pe_posting_date"), "yyyyMMdd") else: piece_ref = d.get("voucher_no") piece_date = ecriture_date # 11. Le libellé de l'écriture comptable ecriture_lib = d.get("voucher_no") # 12. Le montant au débit debit = '{:.2f}'.format(d.get("debit")).replace(".", ",") # 13. Le montant au crédit credit = '{:.2f}'.format(d.get("credit")).replace(".", ",") # 14. Le lettrage de l'écriture comptable (à blanc si non utilisé) ecriture_let = "" # 15. La date de lettrage (à blanc si non utilisé) date_let = "" # 16. La date de validation de l'écriture comptable valid_date = format_datetime(d.get("creation"), "yyyyMMdd") # 17. Le montant en devise (à blanc si non utilisé) # 18. L'identifiant de la devise (à blanc si non utilisé) idevise = d.get("account_currency") if idevise != company_currency: montant_devise = d.get("debit_cur") \ if d.get("debit_cur") != 0 else d.get("credit_cur") else: montant_devise = "" idevise = "" row = [ journal_code, journal_lib, ecriture_num, ecriture_date, compte_num, compte_lib, comp_aux_num, comp_aux_lib, piece_ref, piece_date, ecriture_lib, debit, credit, ecriture_let, date_let, valid_date, montant_devise, idevise ] result.append(row) return result
def test_format_datetime_forced(self): # Test with forced date formats self.assertEqual(format_datetime(test_datetime, 'dd-yyyy-MM ss:mm:HH'), test_date_obj.strftime('%d-%Y-%m %S:%M:%H'))
def mytest(): return frappe.db.sql( "SELECT CONVERT( %s ,datetime(6))", str(format_datetime( '15:49:46.000000'))) #frappe.get_doc("DocType", "User")
def getAvailableFacilitator(start,end,event_obj,faci_cond=None): facilitator=frappe.db.sql("""select name,email from `tabFacilitator`""") start_date=add_days(format_datetime(start,'YYYY-MM-dd'),1) end_date=format_datetime(end,'YYYY-MM-dd') #return (start_date,end_date) faci_obj=[] if faci_cond==None: #frappe.msgprint("None") while start_date<end_date: #title='Available'+'\n'+'----------------'+'\n' flag=False for row in facilitator: faci_item={} event=frappe.db.sql("""select ev.name,ev.starts_on,ev.ends_on,ft.facilitator from `tabEvent` as ev inner join `tabFacilitator Table` as ft on ev.name=ft.parent where %s between ev.starts_on and ev.ends_on and ft.facilitator=%s""",(start_date,row[0])) if event: continue holiday=frappe.db.sql("""select name,start_on,end_on,facilitator from `tabFacilitator Holiday` where %s between start_on and end_on and facilitator=%s""",(start_date,row[0])) if holiday: continue flag=True #title+=row[0]+'\n' faci_item["name"]=row[0] faci_item["start_on"]=start_date faci_item["end_on"]=start_date faci_item["title"]=row[0] faci_item["doctype"]="Facilitator" faci_item["color"]="#000080" event_obj.append(faci_item) start_date=add_days(start_date,1) else: while start_date<end_date: #title='Available'+'\n'+'----------------'+'\n' flag=False #for row in facilitator: faci_item={} event=frappe.db.sql("""select ev.name,ev.starts_on,ev.ends_on,ft.facilitator from `tabEvent` as ev inner join `tabFacilitator Table` as ft on ev.name=ft.parent where %s between ev.starts_on and ev.ends_on and ft.facilitator=%s""",(start_date,faci_cond)) if event: start_date=add_days(start_date,1) continue holiday=frappe.db.sql("""select name,start_on,end_on,facilitator from `tabFacilitator Holiday` where %s between start_on and end_on and facilitator=%s""",(start_date,faci_cond)) if holiday: start_date=add_days(start_date,1) continue flag=True #title+=row[0]+'\n' faci_item["name"]=faci_cond faci_item["start_on"]=start_date faci_item["end_on"]=start_date faci_item["title"]=faci_cond faci_item["doctype"]="Facilitator" faci_item["color"]="#000080" event_obj.append(faci_item) start_date=add_days(start_date,1) return event_obj