コード例 #1
0
def get_data(filters=None):

    logs = dataent.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 = dataent.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
コード例 #2
0
    def add_data_row(self, rows, dt, parentfield, doc, rowidx):
        d = doc.copy()
        meta = dataent.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
コード例 #3
0
 def add_job(j, name):
     if j.kwargs.get('site') == dataent.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
コード例 #4
0
ファイル: employee.py プロジェクト: dataent/epaas
def get_employees_who_are_born_today():
    """Get Employee properties whose birthday is today."""
    return dataent.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)
コード例 #5
0
def get_employee_field_property(employee, fieldname):
    if employee and fieldname:
        field = dataent.get_meta("Employee").get_field(fieldname)
        value = dataent.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
コード例 #6
0
def notify_admin_access_to_system_manager(login_manager=None):
    if (login_manager and login_manager.user == "Administrator"
            and dataent.local.conf.notify_admin_access_to_system_manager):

        site = '<a href="{0}" target="_blank">{0}</a>'.format(
            dataent.local.request.host_url)
        date_and_time = '<b>{0}</b>'.format(
            format_datetime(now_datetime(), format_string="medium"))
        ip_address = dataent.local.request_ip

        access_message = _(
            'Administrator accessed {0} on {1} via IP Address {2}.').format(
                site, date_and_time, ip_address)

        dataent.sendmail(recipients=get_system_managers(),
                         subject=_("Administrator Logged In"),
                         template="administrator_logged_in",
                         args={'access_message': access_message},
                         header=['Access Notification', 'orange'])
コード例 #7
0
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 dataent.db.exists(filters):
        dataent.throw(
            _("Invalid {0}: {1}").format(doc.meta.get_label("return_against"),
                                         doc.return_against))
    else:
        ref_doc = dataent.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):
            dataent.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:
            dataent.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:
            dataent.throw(
                _("'Update Stock' can not be checked because items are not delivered via {0}"
                  ).format(doc.return_against))
コード例 #8
0
def get_result_as_list(data, filters):
	result = []

	company_currency = dataent.get_cached_value('Company',  filters.company,  "default_currency")
	accounts = dataent.get_all("Account", filters={"Company": filters.company}, fields=["name", "account_number"])

	for d in data:

		JournalCode = re.split("-|/|[0-9]", d.get("voucher_no"))[0]

		if d.get("voucher_no").startswith("{0}-".format(JournalCode)) or d.get("voucher_no").startswith("{0}/".format(JournalCode)):
			EcritureNum = re.split("-|/", d.get("voucher_no"))[1]
		else:
			EcritureNum = re.search("{0}(\d+)".format(JournalCode), d.get("voucher_no"), re.IGNORECASE).group(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:
			dataent.throw(_("Account number for account {0} is not available.<br> Please setup your Chart of Accounts correctly.").format(d.get("account")))

		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")

		elif d.get("party_type") == "Employee":
			CompAuxNum = d.get("empName")
			CompAuxLib = d.get("employee_name")

		elif d.get("party_type") == "Student":
			CompAuxNum = d.get("stuName")
			CompAuxLib = d.get("student_name")

		elif d.get("party_type") == "Member":
			CompAuxNum = d.get("memName")
			CompAuxLib = d.get("member_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
コード例 #9
0
ファイル: formatters.py プロジェクト: dataent/dataent
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 = dataent._dict(fieldtype=df)

    if not df:
        df = dataent._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 = dataent._dict(df)

    if value is None:
        value = ""
    elif translated:
        value = dataent._(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