Exemplo n.º 1
0
def handle_exception(e):
	response = None
	http_status_code = getattr(e, "http_status_code", 500)
	return_as_message = False

	if frappe.get_request_header('Accept') and (frappe.local.is_ajax or 'application/json' in frappe.get_request_header('Accept')):
		# handle ajax responses first
		# if the request is ajax, send back the trace or error message
		response = frappe.utils.response.report_error(http_status_code)

	elif (http_status_code==500
		and (frappe.db and isinstance(e, frappe.db.InternalError))
		and (frappe.db and (frappe.db.is_deadlocked(e) or frappe.db.is_timedout(e)))):
			http_status_code = 508

	elif http_status_code==401:
		frappe.respond_as_web_page(_("Session Expired"),
			_("Your session has expired, please login again to continue."),
			http_status_code=http_status_code,  indicator_color='red')
		return_as_message = True

	elif http_status_code==403:
		frappe.respond_as_web_page(_("Not Permitted"),
			_("You do not have enough permissions to complete the action"),
			http_status_code=http_status_code,  indicator_color='red')
		return_as_message = True

	elif http_status_code==404:
		frappe.respond_as_web_page(_("Not Found"),
			_("The resource you are looking for is not available"),
			http_status_code=http_status_code,  indicator_color='red')
		return_as_message = True

	else:
		traceback = "<pre>"+frappe.get_traceback()+"</pre>"
		if frappe.local.flags.disable_traceback:
			traceback = ""

		frappe.respond_as_web_page("Server Error",
			traceback, http_status_code=http_status_code,
			indicator_color='red', width=640)
		return_as_message = True

	if e.__class__ == frappe.AuthenticationError:
		if hasattr(frappe.local, "login_manager"):
			frappe.local.login_manager.clear_cookies()

	if http_status_code >= 500:
		if not frappe.conf.developer_mode:
			for fn in frappe.get_hooks("exception_handlers"):
				frappe.get_attr(fn)()

		frappe.logger().error('Request Error', exc_info=True)
		make_error_snapshot(e)

	if return_as_message:
		response = frappe.website.render.render("message",
			http_status_code=http_status_code)

	return response
Exemplo n.º 2
0
    def sync(self):
        """Create and execute Data Migration Run for Mautic Sync plan"""
        frappe.has_permission('Mautic Settings', throw=True)

        exists = frappe.db.exists(
            'Data Migration Run',
            dict(status=('in', ['Fail', 'Error']), name=('!=', self.name)))
        if exists:
            failed_run = frappe.get_doc("Data Migration Run",
                                        dict(status=('in', ['Fail', 'Error'])))
            failed_run.delete()

        started = frappe.db.exists(
            'Data Migration Run',
            dict(status=('in', ['Started']), name=('!=', self.name)))
        if started:
            print("Break")
            return

        try:
            doc = frappe.get_doc({
                'doctype': 'Data Migration Run',
                'data_migration_plan': 'Mautic Sync',
                'data_migration_connector': 'Mautic Connector'
            }).insert()

            try:
                doc.run()
            except Exception:
                frappe.log_error(frappe.get_traceback())
        except Exception as e:
            frappe.logger().debug({"Mautic Error: "}, e)
Exemplo n.º 3
0
def sync_transactions(bank, bank_account):

    last_sync_date = frappe.db.get_value("Bank Account", bank_account,
                                         "last_integration_date")
    if last_sync_date:
        start_date = formatdate(last_sync_date, "YYYY-MM-dd")
    else:
        start_date = formatdate(add_months(today(), -12), "YYYY-MM-dd")
    end_date = formatdate(today(), "YYYY-MM-dd")

    try:
        transactions = get_transactions(bank=bank,
                                        bank_account=bank_account,
                                        start_date=start_date,
                                        end_date=end_date)

        result = []
        for transaction in reversed(transactions):
            result += new_bank_transaction(transaction)

        frappe.logger().info(
            "Plaid added {} new Bank Transactions from '{}' between {} and {}".
            format(len(result), bank_account, start_date, end_date))

        frappe.db.set_value("Bank Account", bank_account,
                            "last_integration_date", getdate(end_date))

        return result
    except Exception:
        frappe.log_error(frappe.get_traceback(),
                         _("Plaid transactions sync error"))
Exemplo n.º 4
0
def get_fields(item_code=None):
    if print_debug: frappe.logger().debug("get_fields")

    fields = []
    template = ""
    field_template = {
        "fieldtype": "Link",
        "fieldname": "template",
        "label": _("Template"),
        "options": "Item",
        "onchange": "function(e){console.log('ONCHANGE')}"
    }

    if item_code:
        item = frappe.get_doc("Item", item_code)
        if item.variant_of:
            field_template["default"] = item.variant_of

    fields.append(field_template)

    fields_attributes = [{
        "fieldtype": "Read Only",
        "fieldname": "item_code",
        "label": _("Item Code"),
        "in_list_view": 1
    }, {
        "fieldtype": "Check",
        "fieldname": "completed",
        "label": _("Completed"),
        "in_list_view": 1
    }]

    return fields
Exemplo n.º 5
0
def update_reserved_qty_for_production(self, items=None):
	if print_debug: frappe.logger().debug("---radplusplus.manufacturing_controllers.update_reserved_qty_for_production---")
	'''update reserved_qty_for_production in bins'''
	if not self.source_warehouse:
		return

	if not items:
		items = [d.item_code for d in self.required_items]

	for item in items:
		# RENMAI - 2017-04-13 - a modifier lorsque les entrepots sources seront associé 
		# aux productions items.
		
		#doc_item = frappe.get_doc("Item",item)
		#if doc_item.variant_of && doc_item.variant_of == "PM":
		#	source_warehouse = self.source_warehouse
		source_warehouse = self.source_warehouse
		stock_bin = get_bin(item, source_warehouse)
		
		'''Update qty reserved for production from Production Item tables
			in open production orders'''
		stock_bin.reserved_qty_for_production = frappe.db.sql('''select sum(required_qty - transferred_qty)
			from `tabProduction Order` pro, `tabProduction Order Item` item
			where
				item.item_code = %s
				and item.parent = pro.name
				and pro.docstatus = 1
				and pro.source_warehouse = %s''', (stock_bin.item_code, stock_bin.warehouse))[0][0]

		stock_bin.set_projected_qty()

		stock_bin.db_set('reserved_qty_for_production', stock_bin.reserved_qty_for_production)
		stock_bin.db_set('projected_qty', stock_bin.projected_qty)
Exemplo n.º 6
0
 def on_trash(self):
     from app_center.appmgr import remove_app_folder
     try:
         remove_app_link(self.app_path)
         remove_app_folder(self.app)
     except Exception as ex:
         frappe.logger(__name__).error(ex)
Exemplo n.º 7
0
def editor_release(app=None, version=None, comment=None):
    app = app or frappe.form_dict.app
    version = version or frappe.form_dict.version
    comment = comment or frappe.form_dict.comment
    if not app or not version or not comment:
        raise frappe.ValidationError

    valid_app_owner(app)

    data = {
        "doctype": "IOT Application Version",
        "app": app,
        "version": version,
        "beta": 1,
        "comment": comment,
    }

    app_file = zip_application(app, version)

    try:
        doc = frappe.get_doc(data).insert()
        os.system("md5sum " + app_file + " > " + app_file + ".md5")
    except Exception as ex:
        frappe.logger(__name__).error(repr(ex))
        remove_version_file(app, version)
        raise ex

    copy_to_latest(app, version)

    return _("Application upload success")
Exemplo n.º 8
0
def enqueue_events_for_site(site, queued_jobs):
    try:
        frappe.init(site=site)
        if frappe.local.conf.maintenance_mode:
            return

        if frappe.local.conf.pause_scheduler:
            return

        frappe.connect()
        if is_scheduler_disabled():
            return

        enqueue_events(site=site, queued_jobs=queued_jobs)

        frappe.logger(__name__).debug(
            'Queued events for site {0}'.format(site))

    except:
        frappe.logger(__name__).error(
            'Exception in Enqueue Events for Site {0}'.format(site) + '\n' +
            frappe.get_traceback())
        raise

    finally:
        frappe.destroy()
Exemplo n.º 9
0
def enqueue_events_for_site(site):
    def log_and_raise():
        error_message = 'Exception in Enqueue Events for Site {0}\n{1}'.format(
            site, frappe.get_traceback())
        frappe.logger("scheduler").error(error_message)

    try:
        frappe.init(site=site)
        frappe.connect()
        if is_scheduler_inactive():
            return

        enqueue_events(site=site)

        frappe.logger("scheduler").debug(
            'Queued events for site {0}'.format(site))
    except frappe.db.OperationalError as e:
        if frappe.db.is_access_denied(e):
            frappe.logger("scheduler").debug(
                'Access denied for site {0}'.format(site))
        else:
            log_and_raise()
    except:
        log_and_raise()

    finally:
        frappe.destroy()
Exemplo n.º 10
0
def enqueue_events_for_site(site, queued_jobs):
    def log_and_raise():
        frappe.logger(__name__).error(
            'Exception in Enqueue Events for Site {0}'.format(site) + '\n' +
            frappe.get_traceback())
        raise  # pylint: disable=misplaced-bare-raise

    try:
        frappe.init(site=site)
        if frappe.local.conf.maintenance_mode:
            return

        if frappe.local.conf.pause_scheduler:
            return

        frappe.connect()
        if is_scheduler_disabled():
            return

        enqueue_events(site=site, queued_jobs=queued_jobs)

        frappe.logger(__name__).debug(
            'Queued events for site {0}'.format(site))
    except frappe.db.OperationalError as e:
        if frappe.db.is_access_denied(e):
            frappe.logger(__name__).debug(
                'Access denied for site {0}'.format(site))
        else:
            log_and_raise()
    except:
        log_and_raise()

    finally:
        frappe.destroy()
Exemplo n.º 11
0
def enqueue_events_for_site(site, queued_jobs):
	try:
		frappe.init(site=site)
		if frappe.local.conf.maintenance_mode:
			return

		if frappe.local.conf.pause_scheduler:
			return

		frappe.connect()
		if is_scheduler_disabled():
			return

		enqueue_events(site=site, queued_jobs=queued_jobs)

		# TODO this print call is a tempfix till logging is fixed!
		print 'Queued events for site {0}'.format(site)
		frappe.logger(__name__).debug('Queued events for site {0}'.format(site))

	except:
		frappe.logger(__name__).error('Exception in Enqueue Events for Site {0}'.format(site))
		raise

	finally:
		frappe.destroy()
Exemplo n.º 12
0
def send_message(doc,support_code):
        if frappe.session.user == "Guest":
            return
        url = frappe.get_value("ISupport Settings",None,"support_url")
        if not url:
            return
        url = str(url) + "/api/method/usupport.sync.receive_message"
        space = "\n" * 2
        user_name = frappe.get_value("User",doc.user,"full_name")
        message = "{0} {1}From: {2}".format(doc.content,space,user_name)
        data = {
            "name": doc.name,
            "support_code": support_code,
            "notes": doc.content,
            "last_message": message,
            "from_user": frappe.session.user,
            "from_name": user_name,
            "date": nowdate(),
            "time": now(),
        }
        for i in range(3):
            try:
                r = requests.post(url, data=json.dumps(data), timeout=5)
                r.raise_for_status()
                frappe.logger().debug({"webhook_success": r.text})
                break
            except Exception as e:
                frappe.logger().debug({"webhook_error": e, "try": i + 1})
                sleep(3 * i + 1)
                if i != 2:
                    continue
                else:
                    raise e
def get_report(dateFrom,
               reportType,
               doc,
               dateTo=None,
               flag=0,
               monthly=False,
               rrd_id=0):
    frappe.logger("my").info('reportType {0}, dateFrom {1}'.format(
        reportType, dateFrom))
    if flag == 1 and monthly == True:
        create_report(dateFrom, reportType, doc, flag)
    else:
        reports = get_reports_instance()

        report_response = (call_mws_method(reports.get_report,
                                           reportType=reportType,
                                           dateFrom=dateFrom,
                                           dateTo=dateTo,
                                           flag=flag,
                                           rrd_id=rrd_id)).json()

        if reportType == 'stocks':
            deleting_data_in_wb_report(dateFrom, reportType, doc)
            create_report_stocks(report_response)
        elif reportType == 'orders':
            deleting_data_in_wb_report(dateFrom, reportType, doc)
            create_report_orders(report_response)
        elif reportType == 'sales':
            deleting_data_in_wb_report(dateFrom, reportType, doc)
            create_report_sales(report_response)
        elif reportType == 'reportDetailByPeriod':
            if doc == 'WB Sales by Sales Monthly':
                deleting_data_in_wb_report(dateFrom, reportType, doc)
            create_report_sales_by_sales(report_response, dateFrom, dateTo,
                                         reportType, doc, rrd_id)
Exemplo n.º 14
0
def iot_device_his_data(sn=None, vsn=None, fields=None, condition=None):
	vsn = vsn or sn
	fields = fields or "*"
	doc = frappe.get_doc('IOT Device', sn)
	doc.has_permission("read")

	if vsn != sn:
		if vsn not in iot_device_tree(sn):
			return 401

	inf_server = IOTHDBSettings.get_influxdb_server()
	if not inf_server:
		frappe.logger(__name__).error("InfluxDB Configuration missing in IOTHDBSettings")
		return 500
	query = 'SELECT ' + fields + ' FROM "' + vsn + '"'
	if condition:
		query = query + " WHERE " + condition
	else:
		query = query + " LIMIT 1000"

	domain = frappe.get_value("Cloud Company", doc.company, "domain")
	r = requests.session().get(inf_server + "/query", params={"q": query, "db": domain}, timeout=10)
	if r.status_code == 200:
		return r.json()["results"] or r.json()

	return r.text
Exemplo n.º 15
0
def resend_failed_serials():
	failed_serials_doc = frappe.get_all("Serial Number list", ["name", "sync_status", "serial_no"], filters={"sync_status": ["!=", "successful"], })
	# for doc in failed_serials_doc:
	# 	print(doc.name, doc.sync_status, doc.serial_no)
	if failed_serials_doc:
		send_data = {"sn_list": [v.name for v in failed_serials_doc]}
		cloud_server = ThingsCloudSettings.get_thingscloud_server()
		authorization_code = ThingsCloudSettings.get_authorization_code()
		headers = {'HDB-AuthorizationCode': authorization_code, 'Content-Type': 'application/json',
		           'Accept': 'application/json'}
		try:
			r = requests.session().post(cloud_server + "/api/method/iot.hdb_api.batch_add_device", headers=headers, json=send_data, timeout=3)
			if r.status_code == 200:
				result = r.json().get('message')
				# print(json.dumps(result, sort_keys=True, indent=4, separators=(',', ':')))
				if result.get('done'):
					for sn in result.get('done'):
						serialno_doc = frappe.get_doc("Serial Number list", sn)
						serialno_doc.set("sync_status", 'successful')
						serialno_doc.save()
				return True
			else:
				return False
		except Exception as ex:
			frappe.logger(__name__).error(ex)
	else:
		return False
Exemplo n.º 16
0
def enqueue_webhook(doc, webhook):
	webhook = frappe.get_doc("Webhook", webhook.get("name"))
	headers = {}
	data = {}
	if webhook.webhook_headers:
		for h in webhook.webhook_headers:
			if h.get("key") and h.get("value"):
				headers[h.get("key")] = h.get("value")
	if webhook.webhook_data:
		for w in webhook.webhook_data:
			for k, v in doc.as_dict().items():
				if k == w.fieldname:
					data[w.key] = v
	for i in range(3):
		try:
			r = requests.post(webhook.request_url, data=json.dumps(data), headers=headers, timeout=5)
			r.raise_for_status()
			frappe.logger().debug({"webhook_success":r.text})
			break
		except Exception as e:
			frappe.logger().debug({"webhook_error":e, "try": i+1})
			sleep(3*i + 1)
			if i !=2:
				continue
			else:
				raise e
Exemplo n.º 17
0
def enqueue_events_for_site(site, queued_jobs):
    def log_and_raise():
        frappe.logger(__name__).error(
            'Exception in Enqueue Events for Site {0}'.format(site) + '\n' +
            frappe.get_traceback())
        raise  # pylint: disable=misplaced-bare-raise

    try:
        frappe.init(site=site)
        frappe.connect()
        if is_scheduler_inactive():
            return

        enqueue_events(site=site, queued_jobs=queued_jobs)

        frappe.logger(__name__).debug(
            'Queued events for site {0}'.format(site))
    except pymysql.OperationalError as e:
        if e.args[0] == ER.ACCESS_DENIED_ERROR:
            frappe.logger(__name__).debug(
                'Access denied for site {0}'.format(site))
        else:
            log_and_raise()
    except:
        log_and_raise()

    finally:
        frappe.destroy()
Exemplo n.º 18
0
def check_wechat_binding(app=None, redirect_url=None):
	app = app or frappe.form_dict.app

	code = frappe.form_dict.code

	app_id = frappe.get_value('Wechat App', app, 'app_id')
	secret = frappe.get_value('Wechat App', app, 'secret')

	auth = WeChatOAuth(app_id, secret, '')
	token = auth.fetch_access_token(code)
	openid = token["openid"]
	expires_in = token['expires_in']

	user = frappe.get_value('Wechat Binding', {'app': app, 'openid': openid}, 'user')
	if not user:
		redirect = "/" #redirect_url or frappe.form_dict.redirect or ('wechat/home/' + app)
		url = "/wechat_login?app=" + app + "&openid=" + openid + "&redirect=" + redirect
		frappe.local.flags.redirect_location = url
		raise frappe.Redirect

	frappe.logger(__name__).info(_("check_wechat_binding {0} {1}").format(frappe.session.user, user))
	if frappe.session.user != user:
		#frappe.local.login_manager.clear_cookies()
		frappe.local.cookie_manager.to_delete = []
		frappe.local.login_manager.login_as(user)

	if redirect_url:
		#frappe.local.response["type"] = "redirect"
		#frappe.local.response["location"] = redirect_url
		frappe.local.flags.redirect_location = redirect_url
		frappe.local.response["home_page"] = redirect_url
		frappe.local.response["redirect_to"] = redirect_url
		raise frappe.Redirect
	else:
		return app
Exemplo n.º 19
0
def enqueue_webhook(doc, webhook):
	webhook = frappe.get_doc("Webhook", webhook.get("name"))
	headers = {}
	data = {}
	if webhook.webhook_headers:
		for h in webhook.webhook_headers:
			if h.get("key") and h.get("value"):
				headers[h.get("key")] = h.get("value")
	if webhook.webhook_data:
		for w in webhook.webhook_data:
			for k, v in doc.as_dict().items():
				if k == w.fieldname:
					data[w.key] = v
	for i in range(3):
		try:
			r = requests.post(webhook.request_url, data=json.dumps(data), headers=headers, timeout=5)
			r.raise_for_status()
			frappe.logger().debug({"webhook_success":r.text})
			break
		except Exception as e:
			frappe.logger().debug({"webhook_error":e, "try": i+1})
			sleep(3*i + 1)
			if i !=2:
				continue
			else:
				raise e
Exemplo n.º 20
0
def get_context(context):
    context.no_cache = 1
    context.show_sidebar = True

    try:
        app = check_wechat_binding()

        if frappe.session.user == 'Guest':
            frappe.local.flags.redirect_location = "/login"
            raise frappe.Redirect

        context.filter = frappe.form_dict.filter or "all"

        context.language = frappe.db.get_value("User", frappe.session.user,
                                               ["language"])
        context.csrf_token = frappe.local.session.data.csrf_token

        if 'Company Admin' in frappe.get_roles():
            context.isCompanyAdmin = True

        userdevices = devices_list_array(context.filter) or []
        context.userdevices = userdevices
        context.dev_lens = int(ceil(len(userdevices) * 0.1))

        context.wechat_app = app or frappe.form_dict.app
        context.title = _('Wechat Devices')

    except Exception as ex:
        frappe.logger(__name__).exception(ex)
        raise ex
Exemplo n.º 21
0
def superuser(username=None):
	username = username or frappe.form_dict.username
	frappe.logger(__name__).debug(_("MQTT Superuser: username - {0}").format(username))
	if username == "root":
		return http_200ok()
	else:
		return http_403("Auth Error")
Exemplo n.º 22
0
 def get_device_doc(sn):
     dev = None
     try:
         dev = frappe.get_doc("IOT Device", sn)
     except Exception, e:
         frappe.logger(__name__).error(e)
         traceback.print_exc()
Exemplo n.º 23
0
def remove_version_file(app, version):
    valid_app_owner(app)
    try:
        os.remove(get_app_release_filepath(app, version))
        os.remove(get_app_release_filepath(app, version) + ".md5")
    except Exception as ex:
        frappe.logger(__name__).error(repr(ex))
Exemplo n.º 24
0
def make_child_variant(parent, template_name):
    if print_debug: frappe.logger().debug("***make_child_variant***")

    #mapper selon le noms des attributes
    attribute_map = {}
    child_attributes = get_item_variant_attributes_values(template_name)
    parent_attributes = get_item_variant_attributes_values(parent.item_code)
    for child_attribute in child_attributes:
        for item_attribute in parent_attributes:
            #if child_attribute[0] == item_attribute[0] and item_attribute[3] == 0:
            if child_attribute[0] == item_attribute[0]:
                attribute_map[child_attribute[0]] = child_attribute[0]

    #mapper selon la configuration dans la bd
    attribute_map_bd = get_attribute_mapping(parent.variant_of, template_name)
    if attribute_map_bd:
        attribute_map.update(attribute_map_bd)
    parent_attributes_dict = {i[0]: i[1] for i in parent_attributes}
    args = {}
    for key, value in attribute_map.iteritems():
        att_value = get_attribute_value_mapping(parent.variant_of,
                                                template_name, key, value,
                                                parent_attributes_dict[key])
        args[value] = att_value

    return create_variant_and_submit(template_name, args)
Exemplo n.º 25
0
def sync_transactions(bank, bank_account):
    '''Sync transactions based on the last integration date as the start date, after the sync is completed
		add the transaction date of the oldest transaction as the last integration date'''
    last_transaction_date = frappe.db.get_value("Bank Account", bank_account,
                                                "last_integration_date")
    if last_transaction_date:
        start_date = formatdate(last_transaction_date, "YYYY-MM-dd")
    else:
        start_date = formatdate(add_months(today(), -12), "YYYY-MM-dd")
    end_date = formatdate(today(), "YYYY-MM-dd")

    try:
        transactions = get_transactions(bank=bank,
                                        bank_account=bank_account,
                                        start_date=start_date,
                                        end_date=end_date)

        result = []
        for transaction in reversed(transactions):
            result += new_bank_transaction(transaction)

        if result:
            last_transaction_date = frappe.db.get_value(
                'Bank Transaction', result.pop(), 'date')

            frappe.logger().info(
                "Plaid added {} new Bank Transactions from '{}' between {} and {}"
                .format(len(result), bank_account, start_date, end_date))

            frappe.db.set_value("Bank Account", bank_account,
                                "last_integration_date", last_transaction_date)

    except Exception:
        frappe.log_error(frappe.get_traceback(),
                         _("Plaid transactions sync error"))
Exemplo n.º 26
0
def get_item_attributes_values(item_code):
    #template_item_code = frappe.db.get_value("Item", {"item_code":item_code}, "variant_of")
    args = {'item_code': item_code}

    from radplusplus.radplusplus.controllers.configurator import update_user_translations
    update_user_translations(
        frappe.db.get_value("User", frappe.session.user, "language"))

    query = frappe.db.sql("""
			SELECT
				`tabItem Variant Attribute`.attribute,	
				`tabItem Variant Attribute`.attribute as attribute_name_key,				
				`tabItem Variant Attribute`.attribute_value,
				`tabItem Variant Attribute`.attribute_value as item_attribute_value_key
			FROM
				`tabItem Variant Attribute`
			WHERE
				`tabItem Variant Attribute`.parent = %(item_code)s
			ORDER BY
				`tabItem Variant Attribute`.idx ASC""",
                          args,
                          as_dict=1)

    for attribute in query:
        if print_debug: frappe.logger().debug("attribute : " + cstr(attribute))
        attribute["attribute"] = _(attribute["attribute"])
        attribute["attribute_value"] = _(attribute["attribute_value"])

    if print_debug: frappe.logger().debug("attribute : " + cstr(attribute))
    return query
Exemplo n.º 27
0
def make_dynamic_bom(item, create_new_if_exist=False):
    if print_debug: frappe.logger().debug("***make_dynamic_bom***")
    #Si c'est un variant et que son modèle possède un constructeur de BOM
    if item.variant_of is not None and frappe.db.exists(
            "Configurator Bom", item.variant_of):

        cb = frappe.get_doc("Configurator Bom", item.variant_of)

        #Obtenir le bom actuel
        bom = get_bom(item.item_code)
        if bom is None or create_new_if_exist:
            bom = make_bom_base(item, cb)
        else:
            return

        for bom_oper in cb.operations:
            make_dynamic_bom_oper(item, bom, bom_oper)

        for bom_item in cb.items:
            make_bom_item(item, bom, bom_item)

        #make_packaging(item, bom)

        bom.insert(ignore_permissions=True)
        bom.submit()
        if print_debug: frappe.logger().debug("bom created: " + cstr(bom.name))
Exemplo n.º 28
0
def handle_exception(e):
	http_status_code = getattr(e, "http_status_code", 500)

	if (http_status_code==500
		and isinstance(e, MySQLdb.OperationalError)
		and e.args[0] in (1205, 1213)):
			# 1205 = lock wait timeout
			# 1213 = deadlock
			# code 409 represents conflict
			http_status_code = 508

	if frappe.local.is_ajax or 'application/json' in frappe.local.request.headers.get('Accept', ''):
		response = frappe.utils.response.report_error(http_status_code)
	else:
		traceback = "<pre>"+frappe.get_traceback()+"</pre>"
		if frappe.local.flags.disable_traceback:
			traceback = ""

		frappe.respond_as_web_page("Server Error",
			traceback,
			http_status_code=http_status_code)
		response = frappe.website.render.render("message", http_status_code=http_status_code)

	if e.__class__ == frappe.AuthenticationError:
		if hasattr(frappe.local, "login_manager"):
			frappe.local.login_manager.clear_cookies()

	if http_status_code >= 500:
		frappe.logger().error('Request Error', exc_info=True)
		make_error_snapshot(e)

	return response
Exemplo n.º 29
0
def application(request):
	response = None

	try:
		rollback = True

		init_request(request)

		if frappe.local.form_dict.cmd:
			response = frappe.handler.handle()

		elif frappe.request.path.startswith("/api/"):
                	if frappe.local.form_dict.data is None:
                        	frappe.local.form_dict.data = request.get_data()
			response = frappe.api.handle()

		elif frappe.request.path.startswith('/backups'):
			response = frappe.utils.response.download_backup(request.path)

		elif frappe.request.path.startswith('/private/files/'):
			response = frappe.utils.response.download_private_file(request.path)

		elif frappe.local.request.method in ('GET', 'HEAD'):
			response = frappe.website.render.render()

		else:
			raise NotFound

	except HTTPException, e:
		frappe.logger().error('Request Error', exc_info=True)
		return e
Exemplo n.º 30
0
	def send_message(self):
		if frappe.session.user == "Guest":
			return
		if not self.support_code or not self.notes:
			return
		url = frappe.get_value("ISupport Settings",None,"support_url")
		if not url:
			return
		url = str(url) + "/api/method/usupport.sync.receive_message"
		data = {
			"name": self.name,
			"support_code": self.support_code,
			"notes": self.notes,
			"last_message": self.last_message,
			"from_user": frappe.session.user,
			"from_name": frappe.get_value("User",frappe.session.user,"full_name"),
			"date": nowdate(),
			"time": now(),
			"error_msg": self.error_msg or "",
		}
		for i in range(3):
			try:
				r = requests.post(url, data=json.dumps(data), timeout=5)
				r.raise_for_status()
				frappe.logger().debug({"webhook_success": r.text})
				self.need_sync = 0
				self.last_sync = now()
				break
			except Exception as e:
				frappe.logger().debug({"webhook_error": e, "try": i + 1})
				sleep(3 * i + 1)
				if i != 2:
					continue
				else:
					raise e
Exemplo n.º 31
0
def check_bind(app, openid, gen_token=False):
	if frappe.request.method != "POST" and frappe.request.method != "PUT":
		throw(_("Request Method Must be POST!"))

	from iot.user_api import valid_auth_code
	valid_auth_code()

	frappe.logger(__name__).info(_("check_bind {0}").format(openid))

	user = frappe.get_value('Wechat Binding', {'app': app, 'openid': openid}, 'user')
	if not user:
		if frappe.get_value('Wechat App', app, 'name'):
			throw(_("There is no user bind with this openid!"))
		else:
			throw(_('Wechat application name does not exists!'))

	token = frappe.get_value("IOT User Api", user, 'authorization_code')

	if not token and gen_token is not False:
		doc = frappe.get_doc({
			"doctype": "IOT User Api",
			"user": user,
			"authorization_code": str(uuid.uuid1()).upper()
		}).insert()

		token = doc.authorization_code

	return {
		"user": user,
		"fullname": get_fullname(user),
		"token": token,
		"creation": frappe.get_value('Wechat Binding', {'app': app, 'openid': openid}, 'creation')
	}
Exemplo n.º 32
0
def create_mandate(data):
    data = frappe._dict(data)
    frappe.logger().debug(data)

    mandate = data.get('mandate')

    if frappe.db.exists("GoCardless Mandate", mandate):
        return

    else:
        reference_doc = frappe.db.get_value(
            data.get('reference_doctype'),
            data.get('reference_docname'),
            ["reference_doctype", "reference_name"],
            as_dict=1)
        erpnext_customer = frappe.db.get_value(reference_doc.reference_doctype,
                                               reference_doc.reference_name,
                                               ["customer_name"],
                                               as_dict=1)

        try:
            frappe.get_doc({
                "doctype": "GoCardless Mandate",
                "mandate": mandate,
                "customer": erpnext_customer.customer_name,
                "gocardless_customer": data.get('customer')
            }).insert(ignore_permissions=True)

        except Exception:
            frappe.log_error(frappe.get_traceback())
Exemplo n.º 33
0
def get_item_details_translated(args):

    from erpnext.stock.get_item_details import get_item_details
    out = get_item_details(args)

    args = process_args(args)

    lang = "fr"

    if args.get("customer"):
        lang = frappe.db.get_value("Customer", args.customer, "language")

    if args.get("supplier"):
        lang = frappe.db.get_value("Supplier", args.supplier, "language")

    out.update({
        "description":
        frappe.db.get_value("Item Language", {
            "parent": args.item_code,
            "language": lang
        }, "description")
        or frappe.db.get_value("Item", args.item_code, "description")
    })

    if print_debug: frappe.logger().debug(out)

    return out
Exemplo n.º 34
0
def get_purchase_order_items(self):
	'''Returns items that already do not have a linked purchase order'''
	
	if print_debug: frappe.logger().debug("---radplusplus.manufacturing_controllers.get_purchase_order_items:")
	
	if print_debug: frappe.logger().debug("self : " + self)
	
	required_items = json.loads(self).get('required_items')
	self = json.loads(self)
	items = []

	for i in required_items:
		if print_debug: frappe.logger().debug("i : ")
		if print_debug: frappe.logger().debug(i)
		if print_debug: frappe.logger().debug("i['required_qty'] : " + cstr(i['required_qty']))
		
		pending_qty= i['required_qty'] - flt(frappe.db.sql('''select sum(qty) from `tabPurchase Order Item`
				where item_code=%s and production_order=%s and production_order_item = %s and docstatus<2''', (i['item_code'], i['parent'], i['name']))[0][0])
		if pending_qty:
			items.append(dict(
				item_code= i['item_code'],
				warehouse = i['source_warehouse'],
				pending_qty = pending_qty,
				production_order_item = i['name']
			))
				
	return items
Exemplo n.º 35
0
def handle_exception(e):
	response = None
	http_status_code = getattr(e, "http_status_code", 500)
	return_as_message = False

	if frappe.local.is_ajax or 'application/json' in frappe.get_request_header('Accept'):
		# handle ajax responses first
		# if the request is ajax, send back the trace or error message
		response = frappe.utils.response.report_error(http_status_code)

	elif (http_status_code==500
		and isinstance(e, MySQLdb.OperationalError)
		and e.args[0] in (1205, 1213)):
			# 1205 = lock wait timeout
			# 1213 = deadlock
			# code 409 represents conflict
			http_status_code = 508

	elif http_status_code==401:
		frappe.respond_as_web_page(_("Session Expired"),
			_("Your session has expired, please login again to continue."),
			http_status_code=http_status_code,  indicator_color='red')
		return_as_message = True

	elif http_status_code==403:
		frappe.respond_as_web_page(_("Not Permitted"),
			_("You do not have enough permissions to complete the action"),
			http_status_code=http_status_code,  indicator_color='red')
		return_as_message = True

	elif http_status_code==404:
		frappe.respond_as_web_page(_("Not Found"),
			_("The resource you are looking for is not available"),
			http_status_code=http_status_code,  indicator_color='red')
		return_as_message = True

	else:
		traceback = "<pre>"+frappe.get_traceback()+"</pre>"
		if frappe.local.flags.disable_traceback:
			traceback = ""

		frappe.respond_as_web_page("Server Error",
			traceback, http_status_code=http_status_code,
			indicator_color='red', width=640)
		return_as_message = True

	if e.__class__ == frappe.AuthenticationError:
		if hasattr(frappe.local, "login_manager"):
			frappe.local.login_manager.clear_cookies()

	if http_status_code >= 500:
		frappe.logger().error('Request Error', exc_info=True)
		make_error_snapshot(e)

	if return_as_message:
		response = frappe.website.render.render("message",
			http_status_code=http_status_code)

	return response
Exemplo n.º 36
0
def make_error_snapshot(exception):
	if frappe.conf.disable_error_snapshot:
		return

	logger = frappe.logger(__name__, with_more_info=False)

	try:
		error_id = '{timestamp:s}-{ip:s}-{hash:s}'.format(
			timestamp=cstr(datetime.datetime.now()),
			ip=frappe.local.request_ip or '127.0.0.1',
			hash=frappe.generate_hash(length=3)
		)
		snapshot_folder = get_error_snapshot_path()
		frappe.create_folder(snapshot_folder)

		snapshot_file_path = os.path.join(snapshot_folder, "{0}.json".format(error_id))
		snapshot = get_snapshot(exception)

		with open(encode(snapshot_file_path), 'wb') as error_file:
			error_file.write(encode(frappe.as_json(snapshot)))

		logger.error('New Exception collected with id: {}'.format(error_id))

	except Exception as e:
		logger.error('Could not take error snapshot: {0}'.format(e), exc_info=True)
Exemplo n.º 37
0
def sendmail(communication_name, print_html=None, print_format=None, attachments=None,
	recipients=None, cc=None, bcc=None, lang=None, session=None, print_letterhead=None):
	try:

		if lang:
			frappe.local.lang = lang

		if session:
			# hack to enable access to private files in PDF
			session['data'] = frappe._dict(session['data'])
			frappe.local.session.update(session)

		if print_letterhead:
			frappe.flags.print_letterhead = print_letterhead

		# upto 3 retries
		for i in range(3):
			try:
				communication = frappe.get_doc("Communication", communication_name)
				communication._notify(print_html=print_html, print_format=print_format, attachments=attachments,
					recipients=recipients, cc=cc, bcc=bcc)

			except pymysql.InternalError as e:
				# deadlock, try again
				if e.args[0] == ER.LOCK_DEADLOCK:
					frappe.db.rollback()
					time.sleep(1)
					continue
				else:
					raise
			else:
				break

	except:
		traceback = log("frappe.core.doctype.communication.email.sendmail", frappe.as_json({
			"communication_name": communication_name,
			"print_html": print_html,
			"print_format": print_format,
			"attachments": attachments,
			"recipients": recipients,
			"cc": cc,
			"bcc": bcc,
			"lang": lang
		}))
		frappe.logger(__name__).error(traceback)
		raise
Exemplo n.º 38
0
def sendmail(communication_name, print_html=None, print_format=None, attachments=None,
	recipients=None, cc=None, lang=None, session=None):
	try:

		if lang:
			frappe.local.lang = lang

		if session:
			# hack to enable access to private files in PDF
			session['data'] = frappe._dict(session['data'])
			frappe.local.session.update(session)

		# upto 3 retries
		for i in xrange(3):
			try:
				communication = frappe.get_doc("Communication", communication_name)
				if communication.sent_or_received == "Received":
					communication.message_id = None
				communication._notify(print_html=print_html, print_format=print_format, attachments=attachments,
					recipients=recipients, cc=cc)

			except MySQLdb.OperationalError, e:
				# deadlock, try again
				if e.args[0]==1213:
					frappe.db.rollback()
					time.sleep(1)
					continue
				else:
					raise
			else:
				break

	except:
		traceback = log("frappe.core.doctype.communication.email.sendmail", frappe.as_json({
			"communication_name": communication_name,
			"print_html": print_html,
			"print_format": print_format,
			"attachments": attachments,
			"recipients": recipients,
			"cc": cc,
			"lang": lang
		}))
		frappe.logger(__name__).error(traceback)
		raise
Exemplo n.º 39
0
def trigger(site, event, last=None, queued_jobs=(), now=False):
    """Trigger method in hooks.scheduler_events."""

    queue = 'long' if event.endswith('_long') else 'short'
    timeout = queue_timeout[queue]
    if not queued_jobs and not now:
        queued_jobs = get_jobs(site=site, queue=queue)

    if frappe.flags.in_test:
        frappe.flags.ran_schedulers.append(event)

    events_from_hooks = get_scheduler_events(event)
    if not events_from_hooks:
        return

    events = events_from_hooks
    if not now:
        events = []
        if event == "cron":
            for e in events_from_hooks:
                e = cron_map.get(e, e)
                if croniter.is_valid(e):
                    if croniter(e, last).get_next(datetime) <= frappe.utils.now_datetime():
                        events.extend(events_from_hooks[e])
                else:
                    frappe.log_error("Cron string " + e + " is not valid", "Error triggering cron job")
                    frappe.logger(__name__).error('Exception in Trigger Events for Site {0}, Cron String {1}'.format(site, e))

        else:
            if croniter(cron_map[event], last).get_next(datetime) <= frappe.utils.now_datetime():
                events.extend(events_from_hooks)

    for handler in events:
        if not now:
            if handler not in queued_jobs:
                enqueue(handler, queue, timeout, event)
        else:
            scheduler_task(site=site, event=event, handler=handler, now=True)
Exemplo n.º 40
0
def enqueue_events_for_site(site, queued_jobs):
	try:
		frappe.init(site=site)
		if frappe.local.conf.maintenance_mode:
			return

		if frappe.local.conf.pause_scheduler:
			return

		frappe.connect()
		if is_scheduler_disabled():
			return

		enqueue_events(site=site, queued_jobs=queued_jobs)

		frappe.logger(__name__).debug('Queued events for site {0}'.format(site))

	except:
		frappe.logger(__name__).error('Exception in Enqueue Events for Site {0}'.format(site) +
			'\n' + frappe.get_traceback())
		raise

	finally:
		frappe.destroy()
Exemplo n.º 41
0
def scheduler_task(site, event, handler, now=False):
	'''This is a wrapper function that runs a hooks.scheduler_events method'''
	frappe.logger(__name__).info('running {handler} for {site} for event: {event}'.format(handler=handler, site=site, event=event))
	try:
		if not now:
			frappe.connect(site=site)

		frappe.flags.in_scheduler = True
		frappe.get_attr(handler)()

	except Exception:
		frappe.db.rollback()
		traceback = log(handler, "Method: {event}, Handler: {handler}".format(event=event, handler=handler))
		frappe.logger(__name__).error(traceback)
		raise

	else:
		frappe.db.commit()

	frappe.logger(__name__).info('ran {handler} for {site} for event: {event}'.format(handler=handler, site=site, event=event))
Exemplo n.º 42
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import frappe
import string
import datetime
import re
import json
import sys
from frappe import _
from frappe.model.document import Document

_logger = frappe.logger(__name__)


try:
	import vatnumber
except ImportError:
	_logger.warning("VAT validation partially unavailable because the `vatnumber` Python library cannot be found. "
										  "Install it to support more countries, for example with `easy_install vatnumber`.")
	vatnumber = None


_ref_vat = {
	'at': 'ATU12345675',
	'be': 'BE0477472701',
	'bg': 'BG1234567892',
	'ch': 'CHE-123.456.788 TVA or CH TVA 123456', #Swiss by Yannick Vaucher @ Camptocamp
	'cy': 'CY12345678F',
	'cz': 'CZ12345679',
	'de': 'DE123456788',
	'dk': 'DK12345674',
Exemplo n.º 43
0
import os, frappe
import jasper_erpnext_report as jr

_logger = frappe.logger("jasper_erpnext_report")

try:
	import jnius_config as jc
	jr.pyjnius = True

	if not jc.vm_running:
		jc.add_options('-Djava.awt.headless=true')
	else:
		_logger.info("vm_running: {}".format(jc.vm_running))
except:
	print "jnius_config not found"
	jr.pyjnius = False

norm_path = os.path.normpath
join_path = os.path.join
dirname = os.path.dirname
parent_path = dirname(dirname(__file__))
rel_path = os.path.relpath(os.path.join(parent_path, "java"),dirname(__file__))
rel_path_curr = os.path.relpath(parent_path, os.getcwd())
try:
	os.environ['CLASSPATH'] = norm_path(join_path(parent_path,"java/lib/*")) + ":.:" + os.environ.get('CLASSPATH',"")
	print "CLASSPATH {}".format(os.environ['CLASSPATH'])
except:
	print "Error in setting java classpath."

try:
	from jnius import autoclass
Exemplo n.º 44
0
def log(event, details):
	frappe.logger().info(details)