Ejemplo n.º 1
0
	def make_payment_gl_entries(self, gl_entries):
		# Make Cash GL Entries
		if cint(self.is_paid) and self.cash_bank_account and self.paid_amount:
			bank_account_currency = get_account_currency(self.cash_bank_account)
			# CASH, make payment entries
			gl_entries.append(
				self.get_gl_dict({
					"account": self.credit_to,
					"party_type": "Supplier",
					"party": self.supplier,
					"against": self.cash_bank_account,
					"debit": self.base_paid_amount,
					"debit_in_account_currency": self.base_paid_amount \
						if self.party_account_currency==self.company_currency else self.paid_amount,
					"against_voucher": self.return_against if cint(self.is_return) and self.return_against else self.name,
					"against_voucher_type": self.doctype,
					"cost_center": self.cost_center
				}, self.party_account_currency)
			)

			gl_entries.append(
				self.get_gl_dict({
					"account": self.cash_bank_account,
					"against": self.supplier,
					"credit": self.base_paid_amount,
					"credit_in_account_currency": self.base_paid_amount \
						if bank_account_currency==self.company_currency else self.paid_amount,
					"cost_center": self.cost_center
				}, bank_account_currency)
			)
Ejemplo n.º 2
0
def disable_users(limits=None):
	if not limits:
		return

	if limits.get('users'):
		system_manager = get_system_managers(only_name=True)
		user_list = ['Administrator', 'Guest']
		if system_manager:
			user_list.append(system_manager[-1])
		#exclude system manager from active user list
		# active_users =  dataent.db.sql_list("""select name from tabUser
		# 	where name not in ('Administrator', 'Guest', %s) and user_type = 'System User' and enabled=1
		# 	order by creation desc""", system_manager)
		active_users = dataent.get_all("User", filters={"user_type":"System User", "enabled":1, "name": ["not in", user_list]}, fields=["name"])
		user_limit = cint(limits.get('users')) - 1

		if len(active_users) > user_limit:

			# if allowed user limit 1 then deactivate all additional users
			# else extract additional user from active user list and deactivate them
			if cint(limits.get('users')) != 1:
				active_users = active_users[:-1 * user_limit]

			for user in active_users:
				dataent.db.set_value("User", user, 'enabled', 0)

		from dataent.core.doctype.user.user import get_total_users

		if get_total_users() > cint(limits.get('users')):
			reset_simultaneous_sessions(cint(limits.get('users')))

	dataent.db.commit()
Ejemplo n.º 3
0
    def apply_property_setters(self):
        property_setters = dataent.db.sql(
            """select * from `tabProperty Setter` where
			doc_type=%s""", (self.name, ),
            as_dict=1)

        if not property_setters: return

        integer_docfield_properties = [
            d.fieldname for d in dataent.get_meta('DocField').fields
            if d.fieldtype in ('Int', 'Check')
        ]

        for ps in property_setters:
            if ps.doctype_or_field == 'DocType':
                if ps.property_type in ('Int', 'Check'):
                    ps.value = cint(ps.value)

                self.set(ps.property, ps.value)
            else:
                docfield = self.get("fields", {"fieldname": ps.field_name},
                                    limit=1)
                if docfield:
                    docfield = docfield[0]
                else:
                    continue

                if ps.property in integer_docfield_properties:
                    ps.value = cint(ps.value)

                docfield.set(ps.property, ps.value)
Ejemplo n.º 4
0
    def get_current_tax_fraction(self, tax, item_tax_map):
        """
			Get tax fraction for calculating tax exclusive amount
			from tax inclusive amount
		"""
        current_tax_fraction = 0

        if cint(tax.included_in_print_rate):
            tax_rate = self._get_tax_rate(tax, item_tax_map)

            if tax.charge_type == "On Net Total":
                current_tax_fraction = tax_rate / 100.0

            elif tax.charge_type == "On Previous Row Amount":
                current_tax_fraction = (tax_rate / 100.0) * \
                 self.doc.get("taxes")[cint(tax.row_id) - 1].tax_fraction_for_current_item

            elif tax.charge_type == "On Previous Row Total":
                current_tax_fraction = (tax_rate / 100.0) * \
                 self.doc.get("taxes")[cint(tax.row_id) - 1].grand_total_fraction_for_current_item

        if getattr(tax, "add_deduct_tax", None):
            current_tax_fraction *= -1.0 if (tax.add_deduct_tax
                                             == "Deduct") else 1.0
        return current_tax_fraction
Ejemplo n.º 5
0
    def _validate_length(self):
        if dataent.flags.in_install:
            return

        if self.meta.issingle:
            # single doctype value type is mediumtext
            return

        column_types_to_check_length = ('varchar', 'int', 'bigint')

        for fieldname, value in iteritems(self.get_valid_dict()):
            df = self.meta.get_field(fieldname)

            if not df or df.fieldtype == 'Check':
                # skip standard fields and Check fields
                continue

            column_type = type_map[df.fieldtype][0] or None
            default_column_max_length = type_map[df.fieldtype][1] or None

            if df and df.fieldtype in type_map and column_type in column_types_to_check_length:
                max_length = cint(
                    df.get("length")) or cint(default_column_max_length)

                if len(cstr(value)) > max_length:
                    if self.parentfield and self.idx:
                        reference = _("{0}, Row {1}").format(
                            _(self.doctype), self.idx)

                    else:
                        reference = "{0} {1}".format(_(self.doctype),
                                                     self.name)

                    dataent.throw(_("{0}: '{1}' ({3}) will get truncated, as max characters allowed is {2}")\
                     .format(reference, _(df.label), max_length, value), dataent.CharacterLengthExceededError, title=_('Value too big'))
Ejemplo n.º 6
0
    def get_amount_based_on_payment_days(self, row, joining_date,
                                         relieving_date):
        amount, additional_amount = row.amount, row.additional_amount
        if (self.salary_structure and cint(row.depends_on_payment_days)
                and cint(self.total_working_days)
                and (not self.salary_slip_based_on_timesheet
                     or getdate(self.start_date) < joining_date
                     or getdate(self.end_date) > relieving_date)):
            additional_amount = flt(
                (flt(row.additional_amount) * flt(self.payment_days) /
                 cint(self.total_working_days)),
                row.precision("additional_amount"))
            amount = flt((flt(row.default_amount) * flt(self.payment_days) /
                          cint(self.total_working_days)),
                         row.precision("amount")) + additional_amount

        elif not self.payment_days and not self.salary_slip_based_on_timesheet and cint(
                row.depends_on_payment_days):
            amount, additional_amount = 0, 0
        elif not row.amount:
            amount = flt(row.default_amount) + flt(row.additional_amount)

        # apply rounding
        if dataent.get_cached_value("Salary Component", row.salary_component,
                                    "round_to_the_nearest_integer"):
            amount, additional_amount = rounded(amount), rounded(
                additional_amount)

        return amount, additional_amount
Ejemplo n.º 7
0
    def get_context(self, context):
        context.show_search = True
        context.page_length = cint(
            dataent.db.get_single_value('Products Settings',
                                        'products_per_page')) or 6
        context.search_link = '/product_search'

        start = int(dataent.form_dict.start or 0)
        if start < 0:
            start = 0
        context.update({
            "items":
            get_product_list_for_group(product_group=self.name,
                                       start=start,
                                       limit=context.page_length + 1,
                                       search=dataent.form_dict.get("search")),
            "parents":
            get_parent_item_groups(self.parent_item_group),
            "title":
            self.name,
            "products_as_list":
            cint(
                dataent.db.get_single_value('Products Settings',
                                            'products_as_list'))
        })

        if self.slideshow:
            context.update(get_slideshow(self))

        return context
def execute(filters=None):
    # key yyyy-mm
    new_customers_in = {}
    repeat_customers_in = {}
    customers = []
    company_condition = ""

    if filters.get("company"):
        company_condition = ' and company=%(company)s'

    for si in dataent.db.sql(
            """select posting_date, customer, base_grand_total from `tabSales Invoice`
		where docstatus=1 and posting_date <= %(to_date)s
		{company_condition} order by posting_date""".format(
                company_condition=company_condition),
            filters,
            as_dict=1):

        key = si.posting_date.strftime("%Y-%m")
        if not si.customer in customers:
            new_customers_in.setdefault(key, [0, 0.0])
            new_customers_in[key][0] += 1
            new_customers_in[key][1] += si.base_grand_total
            customers.append(si.customer)
        else:
            repeat_customers_in.setdefault(key, [0, 0.0])
            repeat_customers_in[key][0] += 1
            repeat_customers_in[key][1] += si.base_grand_total

    # time series
    from_year, from_month, temp = filters.get("from_date").split("-")
    to_year, to_month, temp = filters.get("to_date").split("-")

    from_year, from_month, to_year, to_month = \
     cint(from_year), cint(from_month), cint(to_year), cint(to_month)

    out = []
    for year in range(from_year, to_year + 1):
        for month in range(from_month if year == from_year else 1,
                           (to_month + 1) if year == to_year else 13):
            key = "{year}-{month:02d}".format(year=year, month=month)

            new = new_customers_in.get(key, [0, 0.0])
            repeat = repeat_customers_in.get(key, [0, 0.0])

            out.append([
                year, calendar.month_name[month], new[0], repeat[0],
                new[0] + repeat[0], new[1], repeat[1], new[1] + repeat[1]
            ])

    return [
        _("Year"),
        _("Month"),
        _("New Customers") + ":Int",
        _("Repeat Customers") + ":Int",
        _("Total") + ":Int",
        _("New Customer Revenue") + ":Currency:150",
        _("Repeat Customer Revenue") + ":Currency:150",
        _("Total Revenue") + ":Currency:150"
    ], out
Ejemplo n.º 9
0
    def validate(self):
        enable_password_policy = cint(
            self.enable_password_policy) and True or False
        minimum_password_score = cint(
            getattr(self, 'minimum_password_score', 0)) or 0
        if enable_password_policy and minimum_password_score <= 0:
            dataent.throw(_("Please select Minimum Password Score"))
        elif not enable_password_policy:
            self.minimum_password_score = ""

        for key in ("session_expiry", "session_expiry_mobile"):
            if self.get(key):
                parts = self.get(key).split(":")
                if len(parts) != 2 or not (cint(parts[0]) or cint(parts[1])):
                    dataent.throw(
                        _("Session Expiry must be in format {0}").format(
                            "hh:mm"))

        if self.enable_two_factor_auth:
            if self.two_factor_method == 'SMS':
                if not dataent.db.get_value('SMS Settings', None,
                                            'sms_gateway_url'):
                    dataent.throw(
                        _('Please setup SMS before setting it as an authentication method, via SMS Settings'
                          ))
            toggle_two_factor_auth(True, roles=['All'])
        else:
            self.bypass_2fa_for_retricted_ip_users = 0
            self.bypass_restrict_ip_check_if_2fa_enabled = 0
Ejemplo n.º 10
0
    def add_system_manager_role(self):
        # if adding system manager, do nothing
        if not cint(self.enabled) or ("System Manager" in [
                user_role.role for user_role in self.get("roles")
        ]):
            return

        if (self.name not in STANDARD_USERS and self.user_type == "System User"
                and not self.get_other_system_managers() and cint(
                    dataent.db.get_single_value('System Settings',
                                                'setup_complete'))):

            msgprint(
                _("Adding System Manager to this User as there must be atleast one System Manager"
                  ))
            self.append("roles", {
                "doctype": "Has Role",
                "role": "System Manager"
            })

        if self.name == 'Administrator':
            # Administrator should always have System Manager Role
            self.extend("roles", [{
                "doctype": "Has Role",
                "role": "System Manager"
            }, {
                "doctype": "Has Role",
                "role": "Administrator"
            }])
Ejemplo n.º 11
0
	def update_status_updater_args(self):
		if cint(self.update_stock):
			self.status_updater.append({
				'source_dt': 'Purchase Invoice Item',
				'target_dt': 'Purchase Order Item',
				'join_field': 'po_detail',
				'target_field': 'received_qty',
				'target_parent_dt': 'Purchase Order',
				'target_parent_field': 'per_received',
				'target_ref_field': 'qty',
				'source_field': 'received_qty',
				'second_source_dt': 'Purchase Receipt Item',
				'second_source_field': 'received_qty',
				'second_join_field': 'purchase_order_item',
				'percent_join_field':'purchase_order',
				'overflow_type': 'receipt',
				'extra_cond': """ and exists(select name from `tabPurchase Invoice`
					where name=`tabPurchase Invoice Item`.parent and update_stock = 1)"""
			})
			if cint(self.is_return):
				self.status_updater.append({
					'source_dt': 'Purchase Invoice Item',
					'target_dt': 'Purchase Order Item',
					'join_field': 'po_detail',
					'target_field': 'returned_qty',
					'source_field': '-1 * qty',
					'second_source_dt': 'Purchase Receipt Item',
					'second_source_field': '-1 * qty',
					'second_join_field': 'purchase_order_item',
					'overflow_type': 'receipt',
					'extra_cond': """ and exists (select name from `tabPurchase Invoice`
						where name=`tabPurchase Invoice Item`.parent and update_stock=1 and is_return=1)"""
				})
Ejemplo n.º 12
0
def get_default_outgoing_email_account(raise_exception_not_set=True):
    '''conf should be like:
		{
		 "mail_server": "smtp.example.com",
		 "mail_port": 587,
		 "use_tls": 1,
		 "mail_login": "******",
		 "mail_password": "******",
		 "auto_email_id": "*****@*****.**",
		 "email_sender_name": "Example Notifications",
		 "always_use_account_email_id_as_sender": 0,
		 "always_use_account_name_as_sender_name": 0
		}
	'''
    email_account = _get_email_account({
        "enable_outgoing": 1,
        "default_outgoing": 1
    })
    if email_account:
        email_account.password = email_account.get_password(
            raise_exception=False)

    if not email_account and dataent.conf.get("mail_server"):
        # from site_config.json
        email_account = dataent.new_doc("Email Account")
        email_account.update({
            "smtp_server":
            dataent.conf.get("mail_server"),
            "smtp_port":
            dataent.conf.get("mail_port"),

            # legacy: use_ssl was used in site_config instead of use_tls, but meant the same thing
            "use_tls":
            cint(dataent.conf.get("use_tls") or 0)
            or cint(dataent.conf.get("use_ssl") or 0),
            "login_id":
            dataent.conf.get("mail_login"),
            "email_id":
            dataent.conf.get("auto_email_id") or dataent.conf.get("mail_login")
            or '*****@*****.**',
            "password":
            dataent.conf.get("mail_password"),
            "always_use_account_email_id_as_sender":
            dataent.conf.get("always_use_account_email_id_as_sender", 0),
            "always_use_account_name_as_sender_name":
            dataent.conf.get("always_use_account_name_as_sender_name", 0)
        })
        email_account.from_site_config = True
        email_account.name = dataent.conf.get("email_sender_name") or "Dataent"

    if not email_account and not raise_exception_not_set:
        return None

    if dataent.are_emails_muted():
        # create a stub
        email_account = dataent.new_doc("Email Account")
        email_account.update({"email_id": "*****@*****.**"})

    return email_account
Ejemplo n.º 13
0
    def clear_active_sessions(self):
        """Clear other sessions of the current user if `deny_multiple_sessions` is not set"""
        if not (cint(dataent.conf.get("deny_multiple_sessions")) or cint(
                dataent.db.get_system_setting('deny_multiple_sessions'))):
            return

        if dataent.session.user != "Guest":
            clear_sessions(dataent.session.user, keep_current=True)
Ejemplo n.º 14
0
def filter_pricing_rules(args, pricing_rules):
    # filter for qty
    if pricing_rules:
        stock_qty = flt(args.get('qty')) * args.get('conversion_factor', 1)

        pricing_rules = list(
            filter(
                lambda x: (flt(stock_qty) >= flt(x.min_qty) and
                           (flt(stock_qty) <= x.max_qty
                            if x.max_qty else True)), pricing_rules))

        # add variant_of property in pricing rule
        for p in pricing_rules:
            if p.item_code and args.variant_of:
                p.variant_of = args.variant_of
            else:
                p.variant_of = None

    # find pricing rule with highest priority
    if pricing_rules:
        max_priority = max([cint(p.priority) for p in pricing_rules])
        if max_priority:
            pricing_rules = list(
                filter(lambda x: cint(x.priority) == max_priority,
                       pricing_rules))

    # apply internal priority
    all_fields = [
        "item_code", "item_group", "brand", "customer", "customer_group",
        "territory", "supplier", "supplier_group", "campaign", "sales_partner",
        "variant_of"
    ]

    if len(pricing_rules) > 1:
        for field_set in [["item_code", "variant_of", "item_group", "brand"],
                          ["customer", "customer_group", "territory"],
                          ["supplier", "supplier_group"]]:
            remaining_fields = list(set(all_fields) - set(field_set))
            if if_all_rules_same(pricing_rules, remaining_fields):
                pricing_rules = apply_internal_priority(
                    pricing_rules, field_set, args)
                break

    if len(pricing_rules) > 1:
        rate_or_discount = list(
            set([d.rate_or_discount for d in pricing_rules]))
        if len(rate_or_discount
               ) == 1 and rate_or_discount[0] == "Discount Percentage":
            pricing_rules = list(filter(lambda x: x.for_price_list==args.price_list, pricing_rules)) \
             or pricing_rules

    if len(pricing_rules) > 1 and not args.for_shopping_cart:
        dataent.throw(
            _("Multiple Price Rules exists with same criteria, please resolve conflict by assigning priority. Price Rules: {0}"
              ).format("\n".join([d.name for d in pricing_rules])),
            MultiplePricingRuleConflict)
    elif pricing_rules:
        return pricing_rules[0]
Ejemplo n.º 15
0
    def check_if_enabled(self, user):
        """raise exception if user not enabled"""
        doc = dataent.get_doc("System Settings")
        if cint(doc.allow_consecutive_login_attempts) > 0:
            check_consecutive_login_attempts(user, doc)

        if user == 'Administrator': return
        if not cint(dataent.db.get_value('User', user, 'enabled')):
            self.fail('User disabled or missing', user=user)
Ejemplo n.º 16
0
def get_assessment_data(args=None):

    # [total, saved, submitted, remaining]
    chart_data = [0, 0, 0, 0]

    condition = ''
    if args["assessment_group"]:
        condition += "and assessment_group = %(assessment_group)s"
    if args["schedule_date"]:
        condition += "and schedule_date <= %(schedule_date)s"

    assessment_plan = dataent.db.sql('''
			SELECT
				ap.name as assessment_plan,
				ap.assessment_name,
				ap.student_group,
				ap.schedule_date,
				(select count(*) from `tabStudent Group Student` sgs where sgs.parent=ap.student_group)
					as student_group_strength
			FROM
				`tabAssessment Plan` ap
			WHERE
				ap.docstatus = 1 {condition}
			ORDER BY
				ap.modified desc
		'''.format(condition=condition), (args),
                                     as_dict=1)

    assessment_plan_list = [d.assessment_plan for d in assessment_plan
                            ] if assessment_plan else ['']
    assessment_result = get_assessment_result(assessment_plan_list)

    for d in assessment_plan:

        assessment_plan_details = assessment_result.get(d.assessment_plan)
        assessment_plan_details = dataent._dict() if not assessment_plan_details else \
         dataent._dict(assessment_plan_details)
        if "saved" not in assessment_plan_details:
            assessment_plan_details.update({"saved": 0})
        if "submitted" not in assessment_plan_details:
            assessment_plan_details.update({"submitted": 0})

        # remaining students whose marks not entered
        remaining_students = cint(d.student_group_strength) - cint(assessment_plan_details.saved) -\
         cint(assessment_plan_details.submitted)
        assessment_plan_details.update({"remaining": remaining_students})
        d.update(assessment_plan_details)

        chart_data[0] += cint(d.student_group_strength)
        chart_data[1] += assessment_plan_details.saved
        chart_data[2] += assessment_plan_details.submitted
        chart_data[3] += assessment_plan_details.remaining

    chart = get_chart(chart_data[1:])

    return assessment_plan, chart
Ejemplo n.º 17
0
    def validate_asset_finance_books(self, row):
        if flt(row.expected_value_after_useful_life) >= flt(
                self.gross_purchase_amount):
            dataent.throw(
                _("Row {0}: Expected Value After Useful Life must be less than Gross Purchase Amount"
                  ).format(row.idx))

        if not row.depreciation_start_date:
            dataent.throw(
                _("Row {0}: Depreciation Start Date is required").format(
                    row.idx))

        if not self.is_existing_asset:
            self.opening_accumulated_depreciation = 0
            self.number_of_depreciations_booked = 0
        else:
            depreciable_amount = flt(self.gross_purchase_amount) - flt(
                row.expected_value_after_useful_life)
            if flt(self.opening_accumulated_depreciation) > depreciable_amount:
                dataent.throw(
                    _("Opening Accumulated Depreciation must be less than equal to {0}"
                      ).format(depreciable_amount))

            if self.opening_accumulated_depreciation:
                if not self.number_of_depreciations_booked:
                    dataent.throw(
                        _("Please set Number of Depreciations Booked"))
            else:
                self.number_of_depreciations_booked = 0

            if cint(self.number_of_depreciations_booked) > cint(
                    row.total_number_of_depreciations):
                dataent.throw(
                    _("Number of Depreciations Booked cannot be greater than Total Number of Depreciations"
                      ))

        if row.depreciation_start_date and getdate(
                row.depreciation_start_date) < getdate(nowdate()):
            dataent.msgprint(_(
                "Depreciation Row {0}: Depreciation Start Date is entered as past date"
            ).format(row.idx),
                             title=_('Warning'),
                             indicator='red')

        if row.depreciation_start_date and getdate(
                row.depreciation_start_date) < getdate(self.purchase_date):
            dataent.throw(
                _("Depreciation Row {0}: Next Depreciation Date cannot be before Purchase Date"
                  ).format(row.idx))

        if row.depreciation_start_date and getdate(
                row.depreciation_start_date) < getdate(
                    self.available_for_use_date):
            dataent.throw(
                _("Depreciation Row {0}: Next Depreciation Date cannot be before Available-for-use Date"
                  ).format(row.idx))
Ejemplo n.º 18
0
    def validate(self):
        self.validate_value("exchange_rate", ">", 0)

        if self.from_currency == self.to_currency:
            throw(_("From Currency and To Currency cannot be same"))

        if not cint(self.for_buying) and not cint(self.for_selling):
            throw(
                _("Currency Exchange must be applicable for Buying or for Selling."
                  ))
Ejemplo n.º 19
0
    def get_columns_from_docfields(self):
        """
			get columns from docfields and custom fields
		"""
        fl = dataent.db.sql("SELECT * FROM tabDocField WHERE parent = %s",
                            self.doctype,
                            as_dict=1)
        lengths = {}
        precisions = {}
        uniques = {}

        # optional fields like _comments
        if not self.meta.istable:
            for fieldname in optional_columns:
                fl.append({"fieldname": fieldname, "fieldtype": "Text"})

            # add _seen column if track_seen
            if getattr(self.meta, 'track_seen', False):
                fl.append({'fieldname': '_seen', 'fieldtype': 'Text'})

        if not dataent.flags.in_install_db and (
                dataent.flags.in_install != "dataent"
                or dataent.flags.ignore_in_install):
            custom_fl = dataent.db.sql("""\
				SELECT * FROM `tabCustom Field`
				WHERE dt = %s AND docstatus < 2""", (self.doctype, ),
                                       as_dict=1)
            if custom_fl: fl += custom_fl

            # apply length, precision and unique from property setters
            for ps in dataent.get_all(
                    "Property Setter",
                    fields=["field_name", "property", "value"],
                    filters={
                        "doc_type": self.doctype,
                        "doctype_or_field": "DocField",
                        "property": ["in", ["precision", "length", "unique"]]
                    }):

                if ps.property == "length":
                    lengths[ps.field_name] = cint(ps.value)

                elif ps.property == "precision":
                    precisions[ps.field_name] = cint(ps.value)

                elif ps.property == "unique":
                    uniques[ps.field_name] = cint(ps.value)

        for f in fl:
            self.columns[f['fieldname']] = DbColumn(
                self, f['fieldname'], f['fieldtype'],
                lengths.get(f["fieldname"]) or f.get('length'),
                f.get('default'), f.get('search_index'), f.get('options'),
                uniques.get(f["fieldname"], f.get('unique')),
                precisions.get(f['fieldname']) or f.get('precision'))
Ejemplo n.º 20
0
def get_month_details(year, month):
    ysd = dataent.db.get_value("Fiscal Year", year, "year_start_date")
    if ysd:
        import calendar, datetime
        diff_mnt = cint(month) - cint(ysd.month)
        if diff_mnt < 0:
            diff_mnt = 12 - int(ysd.month) + cint(month)
        msd = ysd + relativedelta(months=diff_mnt)  # month start date
        month_days = cint(calendar.monthrange(cint(msd.year),
                                              cint(month))[1])  # days in month
        mid_start = datetime.date(msd.year, cint(month),
                                  16)  # month mid start date
        mid_end = datetime.date(msd.year, cint(month),
                                15)  # month mid end date
        med = datetime.date(msd.year, cint(month),
                            month_days)  # month end date
        return dataent._dict({
            'year': msd.year,
            'month_start_date': msd,
            'month_end_date': med,
            'month_mid_start_date': mid_start,
            'month_mid_end_date': mid_end,
            'month_days': month_days
        })
    else:
        dataent.throw(_("Fiscal Year {0} not found").format(year))
Ejemplo n.º 21
0
def enable_2fa(bypass_two_factor_auth=0, bypass_restrict_ip_check=0):
    '''Enable Two factor in system settings.'''
    system_settings = dataent.get_doc('System Settings')
    system_settings.enable_two_factor_auth = 1
    system_settings.bypass_2fa_for_retricted_ip_users = cint(
        bypass_two_factor_auth)
    system_settings.bypass_restrict_ip_check_if_2fa_enabled = cint(
        bypass_restrict_ip_check)
    system_settings.two_factor_method = 'OTP App'
    system_settings.save(ignore_permissions=True)
    dataent.db.commit()
Ejemplo n.º 22
0
    def test_reserved_qty_for_production_cancel(self):
        self.test_reserved_qty_for_production_submit()

        self.wo_order.cancel()

        bin1_on_cancel = get_bin(self.item, self.warehouse)

        # reserved_qty_for_producion updated
        self.assertEqual(cint(self.bin1_at_start.reserved_qty_for_production),
                         cint(bin1_on_cancel.reserved_qty_for_production))
        self.assertEqual(self.bin1_at_start.projected_qty,
                         cint(bin1_on_cancel.projected_qty))
Ejemplo n.º 23
0
    def check_enable_disable(self):
        # do not allow disabling administrator/guest
        if not cint(self.enabled) and self.name in STANDARD_USERS:
            dataent.throw(_("User {0} cannot be disabled").format(self.name))

        if not cint(self.enabled):
            self.a_system_manager_should_exist()

        # clear sessions if disabled
        if not cint(self.enabled) and getattr(dataent.local, "login_manager",
                                              None):
            dataent.local.login_manager.logout(user=self.name)
Ejemplo n.º 24
0
def export_customizations(module,
                          doctype,
                          sync_on_migrate=0,
                          with_permissions=0):
    """Export Custom Field and Property Setter for the current document to the app folder.
		This will be synced with bench migrate"""

    sync_on_migrate = cint(sync_on_migrate)
    with_permissions = cint(with_permissions)

    if not dataent.get_conf().developer_mode:
        raise Exception('Not developer mode')

    custom = {
        'custom_fields': [],
        'property_setters': [],
        'custom_perms': [],
        'doctype': doctype,
        'sync_on_migrate': sync_on_migrate
    }

    def add(_doctype):
        custom['custom_fields'] += dataent.get_all('Custom Field',
                                                   fields='*',
                                                   filters={'dt': _doctype})
        custom['property_setters'] += dataent.get_all(
            'Property Setter', fields='*', filters={'doc_type': _doctype})

    add(doctype)

    if with_permissions:
        custom['custom_perms'] = dataent.get_all('Custom DocPerm',
                                                 fields='*',
                                                 filters={'parent': doctype})

    # also update the custom fields and property setters for all child tables
    for d in dataent.get_meta(doctype).get_table_fields():
        export_customizations(module, d.options, sync_on_migrate,
                              with_permissions)

    if custom["custom_fields"] or custom["property_setters"] or custom[
            "custom_perms"]:
        folder_path = os.path.join(get_module_path(module), 'custom')
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)

        path = os.path.join(folder_path, scrub(doctype) + '.json')
        with open(path, 'w') as f:
            f.write(dataent.as_json(custom))

        dataent.msgprint(
            _('Customizations for <b>{0}</b> exported to:<br>{1}').format(
                doctype, path))
Ejemplo n.º 25
0
    def set_default_if_missing(self):
        if cint(self.selling):
            if not dataent.db.get_value("Selling Settings", None,
                                        "selling_price_list"):
                dataent.set_value("Selling Settings", "Selling Settings",
                                  "selling_price_list", self.name)

        elif cint(self.buying):
            if not dataent.db.get_value("Buying Settings", None,
                                        "buying_price_list"):
                dataent.set_value("Buying Settings", "Buying Settings",
                                  "buying_price_list", self.name)
Ejemplo n.º 26
0
    def validate_stock_exists_for_template_item(self):
        if self.stock_ledger_created() and self._doc_before_save:
            if (cint(self._doc_before_save.has_variants) != cint(
                    self.has_variants)
                    or self._doc_before_save.variant_of != self.variant_of):
                dataent.throw(
                    _("Cannot change Variant properties after stock transaction. You will have to make a new Item to do this."
                      ).format(self.name), StockExistsForTemplate)

            if self.has_variants or self.variant_of:
                if not self.is_child_table_same('attributes'):
                    dataent.throw(
                        _('Cannot change Attributes after stock transaction. Make a new Item and transfer stock to the new Item'
                          ))
Ejemplo n.º 27
0
    def _fix_numeric_types(self):
        for df in self.meta.get("fields"):
            if df.fieldtype == "Check":
                self.set(df.fieldname, cint(self.get(df.fieldname)))

            elif self.get(df.fieldname) is not None:
                if df.fieldtype == "Int":
                    self.set(df.fieldname, cint(self.get(df.fieldname)))

                elif df.fieldtype in ("Float", "Currency", "Percent"):
                    self.set(df.fieldname, flt(self.get(df.fieldname)))

        if self.docstatus is not None:
            self.docstatus = cint(self.docstatus)
Ejemplo n.º 28
0
	def validate_students(self):
		program_enrollment = get_program_enrollment(self.academic_year, self.academic_term, self.program, self.batch, self.course)
		students = [d.student for d in program_enrollment] if program_enrollment else []
		for d in self.students:
			if not dataent.db.get_value("Student", d.student, "enabled") and d.active and not self.disabled:
				dataent.throw(_("{0} - {1} is inactive student".format(d.group_roll_number, d.student_name)))

			if (self.group_based_on == "Batch") and cint(dataent.defaults.get_defaults().validate_batch)\
				and d.student not in students:
				dataent.throw(_("{0} - {1} is not enrolled in the Batch {2}".format(d.group_roll_number, d.student_name, self.batch)))

			if (self.group_based_on == "Course") and cint(dataent.defaults.get_defaults().validate_course)\
				and (d.student not in students):
				dataent.throw(_("{0} - {1} is not enrolled in the Course {2}".format(d.group_roll_number, d.student_name, self.course)))
Ejemplo n.º 29
0
def get_feed(start, page_length, name):
    """get feed"""
    result = dataent.db.sql("""select name, owner, modified, creation,
			reference_doctype, reference_name, subject
		from `tabPatient Medical Record`
		where patient=%(patient)s
		order by creation desc
		limit %(start)s, %(page_length)s""", {
        "start": cint(start),
        "page_length": cint(page_length),
        "patient": name
    },
                            as_dict=True)

    return result
Ejemplo n.º 30
0
	def process(self):
		self.grouped = {}
		self.grouped_data = []

		self.currency_precision = cint(dataent.db.get_default("currency_precision")) or 3
		self.float_precision = cint(dataent.db.get_default("float_precision")) or 2

		for row in self.si_list:
			if self.skip_row(row, self.product_bundles):
				continue

			row.base_amount = flt(row.base_net_amount, self.currency_precision)

			product_bundles = []
			if row.update_stock:
				product_bundles = self.product_bundles.get(row.parenttype, {}).get(row.parent, dataent._dict())
			elif row.dn_detail:
				product_bundles = self.product_bundles.get("Delivery Note", {})\
					.get(row.delivery_note, dataent._dict())
				row.item_row = row.dn_detail

			# get buying amount
			if row.item_code in product_bundles:
				row.buying_amount = flt(self.get_buying_amount_from_product_bundle(row,
					product_bundles[row.item_code]), self.currency_precision)
			else:
				row.buying_amount = flt(self.get_buying_amount(row, row.item_code),
					self.currency_precision)

			# get buying rate
			if row.qty:
				row.buying_rate = flt(row.buying_amount / row.qty, self.float_precision)
				row.base_rate = flt(row.base_amount / row.qty, self.float_precision)
			else:
				row.buying_rate, row.base_rate = 0.0, 0.0

			# calculate gross profit
			row.gross_profit = flt(row.base_amount - row.buying_amount, self.currency_precision)
			if row.base_amount:
				row.gross_profit_percent = flt((row.gross_profit / row.base_amount) * 100.0, self.currency_precision)
			else:
				row.gross_profit_percent = 0.0

			# add to grouped
			self.grouped.setdefault(row.get(scrub(self.filters.group_by)), []).append(row)

		if self.grouped:
			self.get_average_rate_based_on_group_by()