def execute():
	language = frappe.get_single("System Settings").language

	if language and language.startswith('en'): return

	frappe.local.lang = language

	all_domains = frappe.get_hooks("domains")

	for domain in all_domains:
		translated_domain = _(domain, lang=language)
		if frappe.db.exists("Domain", translated_domain):
			#if domain already exists merged translated_domain and domain
			merge = False
			if frappe.db.exists("Domain", domain):
				merge=True

			frappe.rename_doc("Domain", translated_domain, domain, ignore_permissions=True, merge=merge)

	domain_settings = frappe.get_single("Domain Settings")
	active_domains = [d.domain for d in domain_settings.active_domains]
	
	try:
		for domain in active_domains:
			domain = frappe.get_doc("Domain", domain)
			domain.setup_domain()

			if int(frappe.db.get_single_value('System Settings', 'setup_complete')):
				domain.setup_sidebar_items()
				domain.setup_desktop_icons()
				domain.set_default_portal_role()
	except frappe.LinkValidationError:
		pass
Exemplo n.º 2
0
def enable_all_roles_and_domains():
	""" enable all roles and domain for testing """
	# add all roles to users
	domains = frappe.get_all("Domain")
	if not domains:
		return

	from frappe.desk.page.setup_wizard.setup_wizard import add_all_roles_to
	frappe.get_single('Domain Settings').set_active_domains(\
		[d.name for d in domains])
	add_all_roles_to('Administrator')
Exemplo n.º 3
0
	def test_prepaid_subscriptions_with_prorate_true(self):
		settings = frappe.get_single('Subscription Settings')
		to_prorate = settings.prorate
		settings.prorate = 1
		settings.save()

		subscription = frappe.new_doc('Subscription')
		subscription.customer = '_Test Customer'
		subscription.generate_invoice_at_period_start = True
		subscription.append('plans', {'plan': '_Test Plan Name', 'qty': 1})
		subscription.save()
		subscription.cancel_subscription()

		self.assertEqual(len(subscription.invoices), 1)

		current_inv = subscription.get_current_invoice()
		self.assertEqual(current_inv.status, "Unpaid")

		diff = flt(date_diff(nowdate(), subscription.current_invoice_start) + 1)
		plan_days = flt(date_diff(subscription.current_invoice_end, subscription.current_invoice_start) + 1)
		prorate_factor = flt(diff / plan_days)

		self.assertEqual(flt(current_inv.grand_total, 2), flt(prorate_factor * 900, 2))

		settings.prorate = to_prorate
		settings.save()

		subscription.delete()
Exemplo n.º 4
0
def backup_to_s3():
	from frappe.utils.backups import new_backup
	from frappe.utils import get_backups_path

	doc = frappe.get_single("S3 Backup Settings")
	bucket = doc.bucket

	conn = boto3.client(
			's3',
			aws_access_key_id=doc.access_key_id,
			aws_secret_access_key=doc.get_password('secret_access_key'),
			endpoint_url=doc.endpoint_url or 'https://s3.amazonaws.com'
			)

	backup = new_backup(ignore_files=False, backup_path_db=None,
						backup_path_files=None, backup_path_private_files=None, force=True)
	db_filename = os.path.join(get_backups_path(), os.path.basename(backup.backup_path_db))
	files_filename = os.path.join(get_backups_path(), os.path.basename(backup.backup_path_files))
	private_files = os.path.join(get_backups_path(), os.path.basename(backup.backup_path_private_files))
	folder = os.path.basename(db_filename)[:15] + '/'
	# for adding datetime to folder name

	upload_file_to_s3(db_filename, folder, conn, bucket)
	upload_file_to_s3(private_files, folder, conn, bucket)
	upload_file_to_s3(files_filename, folder, conn, bucket)
	delete_old_backups(doc.backup_limit, bucket)
Exemplo n.º 5
0
	def test_subscription_cancellation_invoices(self):
		settings = frappe.get_single('Subscription Settings')
		to_prorate = settings.prorate
		settings.prorate = 1
		settings.save()

		subscription = frappe.new_doc('Subscription')
		subscription.customer = '_Test Customer'
		subscription.append('plans', {'plan': '_Test Plan Name', 'qty': 1})
		subscription.save()

		self.assertEqual(subscription.status, 'Active')

		subscription.cancel_subscription()
		# Invoice must have been generated
		self.assertEqual(len(subscription.invoices), 1)

		invoice = subscription.get_current_invoice()
		diff = flt(date_diff(nowdate(), subscription.current_invoice_start) + 1)
		plan_days = flt(date_diff(subscription.current_invoice_end, subscription.current_invoice_start) + 1)
		prorate_factor = flt(diff/plan_days)

		self.assertEqual(
			flt(
				get_prorata_factor(subscription.current_invoice_end, subscription.current_invoice_start),
				2),
			flt(prorate_factor, 2)
		)
		self.assertEqual(flt(invoice.grand_total, 2), flt(prorate_factor * 900, 2))
		self.assertEqual(subscription.status, 'Cancelled')

		subscription.delete()
		settings.prorate = to_prorate
		settings.save()
Exemplo n.º 6
0
	def test_subscription_is_past_due_doesnt_change_within_grace_period(self):
		settings = frappe.get_single('Subscription Settings')
		grace_period = settings.grace_period
		settings.grace_period = 1000
		settings.save()

		subscription = frappe.new_doc('Subscription')
		subscription.customer = '_Test Customer'
		subscription.append('plans', {'plan': '_Test Plan Name', 'qty': 1})
		subscription.start = '2018-01-01'
		subscription.insert()
		subscription.process()		# generate first invoice

		self.assertEqual(subscription.status, 'Past Due Date')

		subscription.process()
		# Grace period is 1000 days so status should remain as Past Due Date
		self.assertEqual(subscription.status, 'Past Due Date')

		subscription.process()
		self.assertEqual(subscription.status, 'Past Due Date')

		subscription.process()
		self.assertEqual(subscription.status, 'Past Due Date')

		settings.grace_period = grace_period
		settings.save()
		subscription.delete()
Exemplo n.º 7
0
	def test_subscription_unpaid_back_to_active(self):
		settings = frappe.get_single('Subscription Settings')
		default_grace_period_action = settings.cancel_after_grace
		settings.cancel_after_grace = 0
		settings.save()

		subscription = frappe.new_doc('Subscription')
		subscription.customer = '_Test Customer'
		subscription.append('plans', {'plan': '_Test Plan Name', 'qty': 1})
		subscription.start = '2018-01-01'
		subscription.insert()
		subscription.process()		# generate first invoice

		self.assertEqual(subscription.status, 'Past Due Date')

		subscription.process()
		# This should change status to Cancelled since grace period is 0
		self.assertEqual(subscription.status, 'Unpaid')

		invoice = subscription.get_current_invoice()
		invoice.db_set('outstanding_amount', 0)
		invoice.db_set('status', 'Paid')

		subscription.process()
		self.assertEqual(subscription.status, 'Active')

		# A new invoice is generated
		subscription.process()
		self.assertEqual(subscription.status, 'Past Due Date')

		settings.cancel_after_grace = default_grace_period_action
		settings.save()
		subscription.delete()
Exemplo n.º 8
0
	def test_subcription_cancellation_and_process(self):
		settings = frappe.get_single('Subscription Settings')
		default_grace_period_action = settings.cancel_after_grace
		settings.cancel_after_grace = 1
		settings.save()

		subscription = frappe.new_doc('Subscription')
		subscription.customer = '_Test Customer'
		subscription.append('plans', {'plan': '_Test Plan Name', 'qty': 1})
		subscription.start = '2018-01-01'
		subscription.insert()
		subscription.process()	# generate first invoice
		invoices = len(subscription.invoices)

		self.assertEqual(subscription.status, 'Past Due Date')
		self.assertEqual(len(subscription.invoices), invoices)

		subscription.cancel_subscription()
		self.assertEqual(subscription.status, 'Cancelled')
		self.assertEqual(len(subscription.invoices), invoices)

		subscription.process()
		self.assertEqual(subscription.status, 'Cancelled')
		self.assertEqual(len(subscription.invoices), invoices)

		subscription.process()
		self.assertEqual(subscription.status, 'Cancelled')
		self.assertEqual(len(subscription.invoices), invoices)

		settings.cancel_after_grace = default_grace_period_action
		settings.save()
		subscription.delete()
Exemplo n.º 9
0
def execute():
	"""
	The motive of this patch is to increase the overall security in frappe framework

	Existing passwords won't be affected, however, newly created accounts
	will have to adheare to the new password policy guidelines. Once can always
	loosen up the security by modifying the values in System Settings, however,
	we strongly advice against doing so!

	Security is something we take very seriously at frappe,
	and hence we chose to make security tighter by default.
	"""
	doc = frappe.get_single('System Settings')

	# Enforce a Password Policy
	if cint(doc.enable_password_policy) == 0:
		doc.enable_password_policy = 1

	# Enforce a password score as calculated by zxcvbn
	if cint(doc.minimum_password_score) <= 2:
		doc.minimum_password_score = 2

	# Disallow more than 3 consecutive login attempts in a span of 60 seconds
	if cint(doc.allow_consecutive_login_attempts) <= 3:
		doc.allow_consecutive_login_attempts = 3

	doc.flags.ignore_mandatory = True
	doc.save()
Exemplo n.º 10
0
	def validate_overlap(self, data):
		settings = frappe.get_single('Projects Settings')
		if self.work_order:
			self.validate_overlap_for("workstation", data, data.workstation, settings.ignore_workstation_time_overlap)
		else:
			self.validate_overlap_for("user", data, self.user, settings.ignore_user_time_overlap)
			self.validate_overlap_for("employee", data, self.employee, settings.ignore_employee_time_overlap)
Exemplo n.º 11
0
	def set_odometer(self):
		fleet_settings = frappe.get_single("Fleet Settings")

		if fleet_settings.distance == "km" and self.odometer_km:
			self.odometer_mile = self.odometer_km * 0.6214

		if fleet_settings.distance == "mile" and self.odometer_mile:
			self.odometer_km = self.odometer_mile * 1.6093
Exemplo n.º 12
0
def set_default_settings(args):
	# enable default currency
	frappe.db.set_value("Currency", args.get("currency"), "enabled", 1)

	global_defaults = frappe.get_doc("Global Defaults", "Global Defaults")
	global_defaults.update({
		'current_fiscal_year': get_fy_details(args.get('fy_start_date'), args.get('fy_end_date')),
		'default_currency': args.get('currency'),
		'default_company':args.get('company_name')	,
		"country": args.get("country"),
	})

	global_defaults.save()

	system_settings = frappe.get_doc("System Settings")
	system_settings.email_footer_address = args.get("company_name")
	system_settings.save()

	domain_settings = frappe.get_single('Domain Settings')
	domain_settings.set_active_domains(args.get('domains'))
	domain_settings.save()

	stock_settings = frappe.get_doc("Stock Settings")
	stock_settings.item_naming_by = "Item Code"
	stock_settings.valuation_method = "FIFO"
	stock_settings.default_warehouse = frappe.db.get_value('Warehouse', {'warehouse_name': _('Stores')})
	stock_settings.stock_uom = _("Nos")
	stock_settings.auto_indent = 1
	stock_settings.auto_insert_price_list_rate_if_missing = 1
	stock_settings.automatically_set_serial_nos_based_on_fifo = 1
	stock_settings.set_qty_in_transactions_based_on_serial_no_input = 1
	stock_settings.save()

	selling_settings = frappe.get_doc("Selling Settings")
	selling_settings.cust_master_name = "Customer Name"
	selling_settings.so_required = "No"
	selling_settings.dn_required = "No"
	selling_settings.allow_multiple_items = 1
	selling_settings.save()

	buying_settings = frappe.get_doc("Buying Settings")
	buying_settings.supp_master_name = "Supplier Name"
	buying_settings.po_required = "No"
	buying_settings.pr_required = "No"
	buying_settings.maintain_same_rate = 1
	buying_settings.allow_multiple_items = 1
	buying_settings.save()

	notification_control = frappe.get_doc("Notification Control")
	notification_control.quotation = 1
	notification_control.sales_invoice = 1
	notification_control.purchase_order = 1
	notification_control.save()

	hr_settings = frappe.get_doc("HR Settings")
	hr_settings.emp_created_by = "Naming Series"
	hr_settings.save()
Exemplo n.º 13
0
def register_users(user_list):
	user_list = json.loads(user_list)

	settings = frappe.get_single('Marketplace Settings')

	for user in user_list:
		settings.add_hub_user(user)

	return user_list
Exemplo n.º 14
0
def create(kind, owner, users = None, name = None):
	authenticate(owner)

	users  = safe_json_loads(users)
	create = True

	if kind == 'Visitor':
		room = squashify(frappe.db.sql("""
			SELECT name
			FROM   `tabChat Room`
			WHERE  owner = "{owner}"
		""".format(owner = owner), as_dict = True))

		if room:
			room   = frappe.get_doc('Chat Room', room.name)
			create = False

	if create:
		room  		   = frappe.new_doc('Chat Room')
		room.type 	   = kind
		room.owner	   = owner
		room.room_name = name

	dusers = [ ]

	if kind != 'Visitor':
		if users:
			users  = listify(users)
			for user in users:
				duser 	   = frappe.new_doc('Chat Room User')
				duser.user = user
				dusers.append(duser)

			room.users = dusers
	else:
		dsettings	   = frappe.get_single('Website Settings')
		room.room_name = dsettings.chat_room_name

		users          = [user for user in room.users] if hasattr(room, 'users') else [ ]

		for user in dsettings.chat_operators:
			if user.user not in users:
				# appending user to room.users will remove the user from chat_operators
				# this is undesirable, create a new Chat Room User instead
				chat_room_user = {"doctype": "Chat Room User", "user": user.user}
				room.append('users', chat_room_user)

	room.save(ignore_permissions = True)

	room  = get(owner, rooms = room.name)
	users = [room.owner] + [u for u in room.users]

	for u in users:
		frappe.publish_realtime('frappe.chat.room:create', room, user = u, after_commit = True)

	return room
Exemplo n.º 15
0
	def is_past_grace_period(self):
		"""
		Returns `True` if the grace period for the `Subscription` has passed
		"""
		current_invoice = self.get_current_invoice()
		if self.current_invoice_is_past_due(current_invoice):
			subscription_settings = frappe.get_single('Subscription Settings')
			grace_period = cint(subscription_settings.grace_period)

			return getdate(nowdate()) > add_days(current_invoice.due_date, grace_period)
Exemplo n.º 16
0
def get_items(text, start, limit):
	hub = frappe.get_single("Hub Settings")
	response = requests.get(hub.hub_url + "/api/method/hub.hub.api.get_items", params={
		"access_token": hub.access_token,
		"text": text,
		"start": start,
		"limit": limit
	})
	response.raise_for_status()
	return response.json().get("message")
Exemplo n.º 17
0
	def set_status_grace_period(self):
		"""
		Sets the `Subscription` `status` based on the preference set in `Subscription Settings`.

		Used when the `Subscription` needs to decide what to do after the current generated
		invoice is past it's due date and grace period.
		"""
		subscription_settings = frappe.get_single('Subscription Settings')
		if self.status == 'Past Due Date' and self.is_past_grace_period():
			self.status = 'Cancelled' if cint(subscription_settings.cancel_after_grace) else 'Unpaid'
def execute():
	frappe.reload_doctype('System Settings')
	doc = frappe.get_single('System Settings')
	doc.enable_chat = 1

	# Changes prescribed by Nabin Hait ([email protected])
	doc.flags.ignore_mandatory   = True
	doc.flags.ignore_permissions = True

	doc.save()
Exemplo n.º 19
0
def validate_request_header():
	key_header = frappe.get_request_header("awfis-api-key")
	key_local = frappe.get_single("Awfis Settings").api_key_knowlarity

	if key_header == "":
		return -1 #"Key header is blank"
	elif key_header != key_local:
		return 0 #"{0} != {1} : Key header does not match local key".format(key_header, key_local)
	else:
		return 1 #""
Exemplo n.º 20
0
def get_website_settings():
	hooks = frappe.get_hooks()
	context = frappe._dict({
		'top_bar_items': get_items('top_bar_items'),
		'footer_items': get_items('footer_items'),
		"post_login": [
			{"label": _("My Account"), "url": "/me"},
#			{"class": "divider"},
			{"label": _("Logout"), "url": "/?cmd=web_logout"}
		]
	})

	settings = frappe.get_single("Website Settings")
	for k in ["banner_html", "brand_html", "copyright", "twitter_share_via",
		"facebook_share", "google_plus_one", "twitter_share", "linked_in_share",
		"disable_signup", "hide_footer_signup", "head_html", "title_prefix",
		"navbar_search"]:
		if hasattr(settings, k):
			context[k] = settings.get(k)

	if settings.address:
		context["footer_address"] = settings.address

	for k in ["facebook_share", "google_plus_one", "twitter_share", "linked_in_share",
		"disable_signup"]:
		context[k] = int(context.get(k) or 0)

	if frappe.request:
		context.url = quote(str(get_request_site_address(full_address=True)), safe="/:")

	context.encoded_title = quote(encode(context.title or ""), str(""))

	for update_website_context in hooks.update_website_context or []:
		frappe.get_attr(update_website_context)(context)

	context.web_include_js = hooks.web_include_js or []

	context.web_include_css = hooks.web_include_css or []

	via_hooks = frappe.get_hooks("website_context")
	for key in via_hooks:
		context[key] = via_hooks[key]
		if key not in ("top_bar_items", "footer_items", "post_login") \
			and isinstance(context[key], (list, tuple)):
			context[key] = context[key][-1]

	add_website_theme(context)

	if not context.get("favicon"):
		context["favicon"] = "/assets/frappe/images/favicon.png"

	if settings.favicon and settings.favicon != "attach_files:":
		context["favicon"] = settings.favicon

	return context
Exemplo n.º 21
0
	def setUp(self):
		create_driver()
		create_vehicle()
		create_delivery_notification()
		create_test_contact_and_address()

		settings = frappe.get_single("Google Maps Settings")
		settings.home_address = frappe.get_last_doc("Address").name
		settings.save()

		self.delivery_trip = create_delivery_trip()
Exemplo n.º 22
0
def get_hub_connection():
	settings = frappe.get_single('Marketplace Settings')
	marketplace_url = settings.marketplace_url
	hub_user = settings.get_hub_user(frappe.session.user)

	if hub_user:
		password = hub_user.get_password()
		hub_connection = FrappeClient(marketplace_url, hub_user.user, password)
		return hub_connection
	else:
		read_only_hub_connection = FrappeClient(marketplace_url)
		return read_only_hub_connection
Exemplo n.º 23
0
def create_delivery_notification():
	if not frappe.db.exists("Email Template", "Delivery Notification"):
		dispatch_template = frappe.get_doc({
			'doctype': 'Email Template',
			'name': 'Delivery Notification',
			'response': 'Test Delivery Trip',
			'subject': 'Test Subject',
			'owner': frappe.session.user
		})
		dispatch_template.insert()

	delivery_settings = frappe.get_single("Delivery Settings")
	delivery_settings.dispatch_template = 'Delivery Notification'
	delivery_settings.save()
Exemplo n.º 24
0
def register_marketplace(company, company_description):
	validate_registerer()

	settings = frappe.get_single('Marketplace Settings')
	message = settings.register_seller(company, company_description)

	if message.get('hub_seller_name'):
		settings.registered = 1
		settings.hub_seller_name = message.get('hub_seller_name')
		settings.save()

		settings.add_hub_user(frappe.session.user)

	return { 'ok': 1 }
Exemplo n.º 25
0
	def calculate_distance(self):
		fleet_settings = frappe.get_single("Fleet Settings")

		if fleet_settings.distance == "km":
			self.arrival_odometer_mile = self.arrival_odometer_km * 0.6214
			self.departure_odometer_mile = self.departure_odometer_km * 0.6214
			self.distance_km = self.arrival_odometer_km - self.departure_odometer_km
			self.distance_mile = self.distance_km * 0.6214

		if fleet_settings.distance == "mile" and self.odometer_mile:
			self.arrival_odometer_km = self.arrival_odometer_mile * 1.6093
			self.departure_odometer_km = self.departure_odometer_mile * 1.6093
			self.distance_mile = self.arrival_odometer_mile - self.departure_odometer_mile
			self.distance_km = self.distance_km * 1.6093
Exemplo n.º 26
0
	def test_clean_html(self):
		settings = frappe.get_single('Stock Settings')
		settings.clean_description_html = 1
		settings.save()

		item = frappe.get_doc(dict(
			doctype = 'Item',
			item_code = 'Item for description test',
			item_group = 'Products',
			description = '<p><span style="font-size: 12px;">Drawing No. 07-xxx-PO132<br></span><span style="font-size: 12px;">1800 x 1685 x 750<br></span><span style="font-size: 12px;">All parts made of Marine Ply<br></span><span style="font-size: 12px;">Top w/ Corian dd<br></span><span style="font-size: 12px;">CO, CS, VIP Day Cabin</span></p>'
		)).insert()

		self.assertEquals(item.description, '<p>Drawing No. 07-xxx-PO132<br>1800 x 1685 x 750<br>All parts made of Marine Ply<br>Top w/ Corian dd<br>CO, CS, VIP Day Cabin</p>')

		item.delete()
Exemplo n.º 27
0
	def set_subscription_status(self):
		"""
		Sets the status of the `Subscription`
		"""
		if self.is_trialling():
			self.status = 'Trialling'
		elif self.status == 'Past Due Date' and self.is_past_grace_period():
			subscription_settings = frappe.get_single('Subscription Settings')
			self.status = 'Cancelled' if cint(subscription_settings.cancel_after_grace) else 'Unpaid'
		elif self.status == 'Past Due Date' and not self.has_outstanding_invoice():
			self.status = 'Active'
		elif self.current_invoice_is_past_due():
			self.status = 'Past Due Date'
		elif self.is_new_subscription():
			self.status = 'Active'
			# todo: then generate new invoice
		self.save()
Exemplo n.º 28
0
	def validate_last_fillup(self):
		last_fillup = frappe.get_list("Fill Up Record",
			fields=["odometer_km","odometer_mile"],
			filters = {
				"vehicle": self.vehicle,
				"docstatus": 1
			})
		
		fleet_settings = frappe.get_single("Fleet Settings")

		if fleet_settings.distance == "km":
			if last_fillup and last_fillup[0].odometer_km > self.odometer_km:
				frappe.throw(_("Odometer was showing higher number in previous transaction"))

		if fleet_settings.distance == "mile":
			if last_fillup and last_fillup[0].odometer_mile > self.odometer_mile:
				frappe.throw(_("Odometer was showing higher number in previous transaction"))
Exemplo n.º 29
0
def get_tax_data(doc):
	from shipment_management.utils import get_state_code
	taxjar_settings = frappe.get_single("TaxJar Settings")

	client = get_client()
	if not (taxjar_settings.api_key or taxjar_settings.tax_account_head):
		return

	client = taxjar.Client(api_key=taxjar_settings.get_password("api_key"))

	company_address = frappe.get_doc("Address", {"is_your_company_address": 1})
	if company_address and doc.shipping_address_name:
		shipping_address = frappe.get_doc("Address", doc.shipping_address_name)
	else:
		return

	if not shipping_address.country == "United States":
		return

	shipping = 0
	for tax in doc.taxes:
		if tax.account_head == "Freight and Forwarding Charges - JA":
			shipping = tax.tax_amount

	tax_dict = {
		'to_country': 'US',
		'to_zip': shipping_address.pincode,
		'to_city': shipping_address.city,
		'to_state': get_state_code(shipping_address),
		'shipping': shipping,
		'line_items': []
	}

	index = 1
	for item in doc.items:
		tax_dict["line_items"].append({
			"id": index,
			"description": item.item_name[:255],
			"unit_price": item.price_list_rate,
			"quantity": item.qty,
			"discount": (item.discount_percentage / 100) * item.price_list_rate * item.qty
		})

		index = index + 1

	return tax_dict
Exemplo n.º 30
0
	def test_subscription_cancellation_invoices_with_prorata_false(self):
		settings = frappe.get_single('Subscription Settings')
		to_prorate = settings.prorate
		settings.prorate = 0
		settings.save()

		subscription = frappe.new_doc('Subscription')
		subscription.customer = '_Test Customer'
		subscription.append('plans', {'plan': '_Test Plan Name', 'qty': 1})
		subscription.save()
		subscription.cancel_subscription()
		invoice = subscription.get_current_invoice()

		self.assertEqual(invoice.grand_total, 900)

		settings.prorate = to_prorate
		settings.save()

		subscription.delete()
Exemplo n.º 31
0
    def validate_last_fillup(self):
        last_fillup = frappe.get_list("Fill Up Record",
                                      fields=["odometer_km", "odometer_mile"],
                                      filters={
                                          "vehicle": self.vehicle,
                                          "docstatus": 1
                                      })

        fleet_settings = frappe.get_single("Fleet Settings")

        if fleet_settings.distance == "km":
            if last_fillup and last_fillup[0].odometer_km > self.odometer_km:
                frappe.throw(
                    _("Odometer was showing higher number in previous transaction"
                      ))

        if fleet_settings.distance == "mile":
            if last_fillup and last_fillup[
                    0].odometer_mile > self.odometer_mile:
                frappe.throw(
                    _("Odometer was showing higher number in previous transaction"
                      ))
Exemplo n.º 32
0
def create_demande(doc, method):
    if (doc.creer_demande_materiel == 1):
        stock_settings = frappe.get_single('Stock Settings')
        req = make_material_request(doc.name)
        req.schedule_date = doc.delivery_date
        req.material_request_type = "Material Transfer"
        req.title = _("{0}").format(req.material_request_type)
        user = stock_settings.compte_assigner_stock
        req.save()
        req.title = _("{0}").format(req.material_request_type)
        doc.demande_associe = req.name
        for line in doc.items:
            line.qts_prepares = line.qty
        doc.save()
        req.submit()
        assign_to.add({
            "assign_to": user,
            "doctype": "Material Request",
            "name": req.name,
            "description": "Transfert" + " - " + doc.name
        })
        frappe.msgprint("Demande materiel cree !")
Exemplo n.º 33
0
def after_install():
	# create the wiki homepage
	page = frappe.new_doc("Wiki Page")
	page.title = "Home"
	page.route = "home"
	page.content = "Welcome to the homepage of your wiki!"
	page.published = True
	page.insert()

	# create the wiki sidebar
	sidebar = frappe.new_doc("Wiki Sidebar")
	sidebar.title = "Wiki"
	sidebar.route = "wiki"
	sidebar.append(
		"sidebar_items", {"item": page.name}
	)
	sidebar.insert()

	# set the sidebar in settings
	settings = frappe.get_single("Wiki Settings")
	settings.sidebar = sidebar.name
	settings.save()
Exemplo n.º 34
0
	def test_subscription_unpaid_after_grace_period(self):
		settings = frappe.get_single('Subscription Settings')
		default_grace_period_action = settings.cancel_after_grace
		settings.cancel_after_grace = 0
		settings.save()

		subscription = frappe.new_doc('Subscription')
		subscription.customer = '_Test Customer'
		subscription.append('plans', {'plan': '_Test Plan Name', 'qty': 1})
		subscription.start = '2018-01-01'
		subscription.insert()
		subscription.process()		# generate first invoice

		self.assertEqual(subscription.status, 'Past Due Date')

		subscription.process()
		# This should change status to Cancelled since grace period is 0
		self.assertEqual(subscription.status, 'Unpaid')

		settings.cancel_after_grace = default_grace_period_action
		settings.save()
		subscription.delete()
Exemplo n.º 35
0
    def test_settings(self):
        item = frappe.get_doc(
            dict(
                doctype='Item',
                item_code='Item for description test',
                item_group='Products',
                description=
                '<p><span style="font-size: 12px;">Drawing No. 07-xxx-PO132<br></span><span style="font-size: 12px;">1800 x 1685 x 750<br></span><span style="font-size: 12px;">All parts made of Marine Ply<br></span><span style="font-size: 12px;">Top w/ Corian dd<br></span><span style="font-size: 12px;">CO, CS, VIP Day Cabin</span></p>'
            )).insert()

        settings = frappe.get_single('Stock Settings')
        settings.clean_description_html = 1
        settings.save()

        item.reload()

        self.assertEqual(
            item.description,
            '<p>Drawing No. 07-xxx-PO132<br>1800 x 1685 x 750<br>All parts made of Marine Ply<br>Top w/ Corian dd<br>CO, CS, VIP Day Cabin</p>'
        )

        item.delete()
Exemplo n.º 36
0
def settings(fields = None):
    fields    = safe_json_loads(fields)

    dsettings = frappe.get_single('Website Settings')
    response  = dict(
        socketio         = dict(
            port         = frappe.conf.socketio_port
        ),
        enable           = bool(dsettings.chat_enable),
        enable_from      = dsettings.chat_enable_from,
        enable_to        = dsettings.chat_enable_to,
        room_name        = dsettings.chat_room_name,
        welcome_message  = dsettings.chat_welcome_message,
        operators        = [
            duser.user for duser in dsettings.chat_operators
        ]
    )

    if fields:
        response = filter_dict(response, fields)

    return response
Exemplo n.º 37
0
    def settings_data(self):
        profile = frappe.db.get_value("User", frappe.session.user,
                                      "role_profile_name")
        restaurant_settings = frappe.get_single("Restaurant Settings")

        return dict(
            pos=self.pos_profile_data(),
            permissions=dict(
                invoice=frappe.permissions.get_doc_permissions(
                    frappe.new_doc("Sales Invoice")),
                order=frappe.permissions.get_doc_permissions(
                    frappe.new_doc("Table Order")),
                restaurant_object=frappe.permissions.get_doc_permissions(
                    frappe.new_doc("Restaurant Object")),
            ),
            restrictions=restaurant_settings,
            exceptions=[
                item for item in restaurant_settings.restaurant_permissions
                if item.role_profile == profile
            ],
            geo_data=frappe.session,
            test_data=frappe.get_doc("User", frappe.session.user))
Exemplo n.º 38
0
    def test_batch_name_with_naming_series(self):
        stock_settings = frappe.get_single("Stock Settings")
        use_naming_series = cint(stock_settings.use_naming_series)

        if not use_naming_series:
            frappe.set_value("Stock Settings", "Stock Settings",
                             "use_naming_series", 1)

        batch = self.make_new_batch("_Test Stock Item For Batch Test1")
        batch_name = batch.name

        self.assertTrue(batch_name.startswith("BATCH-"))

        batch.delete()
        batch = self.make_new_batch("_Test Stock Item For Batch Test2")

        self.assertEqual(batch_name, batch.name)

        # reset Stock Settings
        if not use_naming_series:
            frappe.set_value("Stock Settings", "Stock Settings",
                             "use_naming_series", 0)
Exemplo n.º 39
0
def before_save(doc, method):
    settings = frappe.get_single("Optical Store Settings")
    frames = mapf(lambda x: x.item_group, settings.frames)
    lenses = mapf(lambda x: x.item_group, settings.lens)

    validate_item_group = _validate_item_group(frames, lenses)
    frame, lens_right, lens_left = get_parts(doc.items)
    for item in doc.items:
        if item.os_spec_part:
            validate_item_group(item)
        else:
            if not frame and item.item_group in frames:
                item.os_spec_part = "Frame"
                frame = item
            elif not lens_right and item.item_group in lenses:
                item.os_spec_part = "Lens Right"
                lens_right = item
            elif not lens_left and item.item_group in lenses:
                item.os_spec_part = "Lens Left"
                lens_left = item

    _validate_spec_parts(doc.items)
Exemplo n.º 40
0
def delete_expired_prepared_reports():
    system_settings = frappe.get_single('System Settings')
    enable_auto_deletion = system_settings.enable_prepared_report_auto_deletion
    if enable_auto_deletion:
        expiry_period = system_settings.prepared_report_expiry_period
        prepared_reports_to_delete = frappe.get_all(
            'Prepared Report',
            filters={
                'creation': [
                    '<',
                    frappe.utils.add_days(frappe.utils.now(), -expiry_period)
                ]
            })

        batches = frappe.utils.create_batch(prepared_reports_to_delete, 100)
        for batch in batches:
            args = {
                'reports': batch,
            }
            enqueue(method=delete_prepared_reports,
                    job_name="delete_prepared_reports",
                    **args)
Exemplo n.º 41
0
def execute():
    frappe.reload_doc('shopping_cart', 'doctype', 'Shopping Cart Settings')
    frappe.reload_doc('accounts', 'doctype', 'Payment Gateway Account')
    frappe.reload_doc('shopping_cart', 'doctype',
                      'Shopping Cart Payment Gateway')

    cart_settings = frappe.get_single("Shopping Cart Settings")

    if cart_settings.get("payment_gateway_account"):
        payment_gateway = frappe.db.get_value(
            "Payment Gateway Account",
            cart_settings.get("payment_gateway_account"), "payment_gateway")

        default_gateway = {
            "payment_gateway_account": cart_settings.payment_gateway_account,
            "payment_gateway": payment_gateway,
            "label": payment_gateway,
            "is_default": 1
        }

        cart_settings.append("gateways", default_gateway)
        cart_settings.save()
Exemplo n.º 42
0
def execute():
    settings = frappe.get_single("Optical Store Settings")
    frames = map(lambda x: x.item_group, settings.frames)
    lenses = map(lambda x: x.item_group, settings.lens)

    for doctype in ["Sales Order", "Sales Invoice"]:
        for doc in _get_docs(doctype):
            frame, lens_right, lens_left = get_parts(doc.items)
            for item in doc.items:
                if not item.os_spec_part:
                    if not frame and item.item_group in frames:
                        frappe.db.set_value(item.doctype, item.name,
                                            "os_spec_part", "Frame")
                        frame = item
                    elif not lens_right and item.item_group in lenses:
                        frappe.db.set_value(item.doctype, item.name,
                                            "os_spec_part", "Lens Right")
                        lens_right = item
                    elif not lens_left and item.item_group in lenses:
                        frappe.db.set_value(item.doctype, item.name,
                                            "os_spec_part", "Lens Left")
                        lens_left = item
Exemplo n.º 43
0
    def test_batch_name_with_naming_series(self):
        stock_settings = frappe.get_single('Stock Settings')
        use_naming_series = cint(stock_settings.use_naming_series)

        if not use_naming_series:
            frappe.set_value('Stock Settings', 'Stock Settings',
                             'use_naming_series', 1)

        batch = self.make_new_batch('_Test Stock Item For Batch Test1')
        batch_name = batch.name

        self.assertTrue(batch_name.startswith('BATCH-'))

        batch.delete()
        batch = self.make_new_batch('_Test Stock Item For Batch Test2')

        self.assertEqual(batch_name, batch.name)

        # reset Stock Settings
        if not use_naming_series:
            frappe.set_value('Stock Settings', 'Stock Settings',
                             'use_naming_series', 0)
Exemplo n.º 44
0
def setup_items():
    print("Items Setup...")

    for filename in ["item_groups", "items", "prices"]:
        data = json.loads(
            open(frappe.get_app_path('tierslieux', 'data',
                                     f'{filename}.json')).read())
        for item in data:
            doc = frappe.get_doc(item)
            try:
                doc.insert()
            except frappe.DuplicateEntryError:
                continue
            except ItemPriceDuplicateItem:
                continue
        frappe.db.commit()

    venue_settings = frappe.get_single("Venue Settings")
    venue_settings.item_group = "Coworking"
    venue_settings.stock_uom = "Unité"
    venue_settings.minute_uom = "Minute"
    venue_settings.save()
Exemplo n.º 45
0
    def test_subscription_cancellation_invoices(self):
        settings = frappe.get_single('Subscription Settings')
        to_prorate = settings.prorate
        settings.prorate = 1
        settings.save()

        subscription = frappe.new_doc('Subscription')
        subscription.customer = '_Test Customer'
        subscription.append('plans', {'plan': '_Test Plan Name', 'qty': 1})
        subscription.save()

        self.assertEqual(subscription.status, 'Active')

        subscription.cancel_subscription()
        # Invoice must have been generated
        self.assertEqual(len(subscription.invoices), 1)

        invoice = subscription.get_current_invoice()
        diff = flt(
            date_diff(nowdate(), subscription.current_invoice_start) + 1)
        plan_days = flt(
            date_diff(subscription.current_invoice_end,
                      subscription.current_invoice_start) + 1)
        prorate_factor = flt(diff / plan_days)

        self.assertEqual(
            flt(
                get_prorata_factor(
                    subscription.current_invoice_end,
                    subscription.current_invoice_start,
                    subscription.generate_invoice_at_period_start), 2),
            flt(prorate_factor, 2))
        self.assertEqual(flt(invoice.grand_total, 2),
                         flt(prorate_factor * 900, 2))
        self.assertEqual(subscription.status, 'Cancelled')

        subscription.delete()
        settings.prorate = to_prorate
        settings.save()
def update_linked_doctypes(doctype, cancelled_doc_names):
    single_doctypes = get_single_doctypes()

    for linked_dt, field in get_linked_doctypes().get(doctype, []):
        if linked_dt not in single_doctypes:
            frappe.db.sql(
                """
				update
					`tab{linked_dt}`
				set
					`{column}`=CONCAT(`{column}`, '-CANC')
				where
					`{column}` in %(cancelled_doc_names)s;
			""".format(linked_dt=linked_dt, column=field),
                {'cancelled_doc_names': cancelled_doc_names})
        else:
            doc = frappe.get_single(linked_dt)
            if getattr(doc, field) in cancelled_doc_names:
                setattr(doc, field, getattr(doc, field) + '-CANC')
                doc.flags.ignore_mandatory = True
                doc.flags.ignore_validate = True
                doc.save(ignore_permissions=True)
Exemplo n.º 47
0
def update_global_search_doctypes():
	global_search_doctypes = []
	show_message(1, _("Fetching default Global Search documents."))

	installed_apps = [app for app in frappe.get_installed_apps() if app]
	active_domains = [domain for domain in frappe.get_active_domains() if domain]
	active_domains.append("Default")

	for app in installed_apps:
		search_doctypes = frappe.get_hooks(hook="global_search_doctypes", app_name=app)
		if not search_doctypes:
			continue

		for domain in active_domains:
			if search_doctypes.get(domain):
				global_search_doctypes.extend(search_doctypes.get(domain))

	doctype_list = set([dt.name for dt in frappe.get_list("DocType")])
	allowed_in_global_search = []

	for dt in global_search_doctypes:
		if dt.get("index") is not None:
			allowed_in_global_search.insert(dt.get("index"), dt.get("doctype"))
			continue

		allowed_in_global_search.append(dt.get("doctype"))

	show_message(2, _("Setting up Global Search documents."))
	global_search_settings = frappe.get_single("Global Search Settings")
	global_search_settings.allowed_in_global_search = []
	for dt in allowed_in_global_search:
		if dt not in doctype_list:
			continue

		global_search_settings.append("allowed_in_global_search", {
			"document_type": dt
		})
	global_search_settings.save(ignore_permissions=True)
	show_message(3, "Global Search Documents have been reset.")
Exemplo n.º 48
0
    def form_route_list(self, optimize):
        """
		Form a list of address routes based on the delivery stops. If locks
		are present, and the routes need to be optimized, then they will be
		split into sublists at the specified lock position(s).

		Args:
			optimize (bool): `True` if route needs to be optimized, else `False`

		Returns:
			(list of list of str): List of address routes split at locks, if optimize is `True`
		"""

        settings = frappe.get_single("Google Maps Settings")
        home_address = get_address_display(
            frappe.get_doc("Address", settings.home_address).as_dict())

        route_list = []
        # Initialize first leg with origin as the home address
        leg = [home_address]

        for stop in self.delivery_stops:
            leg.append(stop.customer_address)

            if optimize and stop.lock:
                route_list.append(leg)
                leg = [stop.customer_address]

        # For last leg, append home address as the destination
        # only if lock isn't on the final stop
        if len(leg) > 1:
            leg.append(home_address)
            route_list.append(leg)

        route_list = [[sanitize_address(address) for address in route]
                      for route in route_list]

        return route_list
Exemplo n.º 49
0
def add_standard_navbar_items():
    navbar_settings = frappe.get_single("Navbar Settings")

    erpnext_navbar_items = [{
        'item_label': 'Documentation',
        'item_type': 'Route',
        'route': 'https://erpnext.com/docs/user/manual',
        'is_standard': 1
    }, {
        'item_label': 'User Forum',
        'item_type': 'Route',
        'route': 'https://discuss.erpnext.com',
        'is_standard': 1
    }, {
        'item_label': 'Report an Issue',
        'item_type': 'Route',
        'route': 'https://github.com/frappe/erpnext/issues',
        'is_standard': 1
    }]

    current_nabvar_items = navbar_settings.help_dropdown
    navbar_settings.set('help_dropdown', [])

    for item in erpnext_navbar_items:
        navbar_settings.append('help_dropdown', item)

    for item in current_nabvar_items:
        navbar_settings.append(
            'help_dropdown', {
                'item_label': item.item_label,
                'item_type': item.item_type,
                'route': item.route,
                'action': item.action,
                'is_standard': item.is_standard,
                'hidden': item.hidden
            })

    navbar_settings.save()
Exemplo n.º 50
0
def backup_to_s3():
	from frappe.utils.backups import new_backup
	from frappe.utils import get_backups_path

	doc = frappe.get_single("S3 Backup Settings")
	bucket = doc.bucket
	backup_files = cint(doc.backup_files)

	conn = boto3.client(
			's3',
			aws_access_key_id=doc.access_key_id,
			aws_secret_access_key=doc.get_password('secret_access_key'),
			endpoint_url=doc.endpoint_url or 'https://s3.amazonaws.com'
			)

	if frappe.flags.create_new_backup:
		backup = new_backup(ignore_files=False, backup_path_db=None,
						backup_path_files=None, backup_path_private_files=None, force=True)
		db_filename = os.path.join(get_backups_path(), os.path.basename(backup.backup_path_db))
		site_config = os.path.join(get_backups_path(), os.path.basename(backup.site_config_backup_path))
		if backup_files:
			files_filename = os.path.join(get_backups_path(), os.path.basename(backup.backup_path_files))
			private_files = os.path.join(get_backups_path(), os.path.basename(backup.backup_path_private_files))
	else:
		if backup_files:
			db_filename, site_config, files_filename, private_files = get_latest_backup_file(with_files=backup_files)
		else:
			db_filename, site_config = get_latest_backup_file()

	folder = os.path.basename(db_filename)[:15] + '/'
	# for adding datetime to folder name

	upload_file_to_s3(db_filename, folder, conn, bucket)
	upload_file_to_s3(site_config, folder, conn, bucket)
	if backup_files:
		upload_file_to_s3(private_files, folder, conn, bucket)
		upload_file_to_s3(files_filename, folder, conn, bucket)
	delete_old_backups(doc.backup_limit, bucket)
Exemplo n.º 51
0
	def test_subscription_cancel_after_grace_period(self):
		settings = frappe.get_single("Subscription Settings")
		default_grace_period_action = settings.cancel_after_grace
		settings.cancel_after_grace = 1
		settings.save()

		subscription = frappe.new_doc("Subscription")
		subscription.party_type = "Customer"
		subscription.party = "_Test Customer"
		subscription.append("plans", {"plan": "_Test Plan Name", "qty": 1})
		subscription.start_date = "2018-01-01"
		subscription.insert()

		self.assertEqual(subscription.status, "Active")

		subscription.process()  # generate first invoice
		# This should change status to Cancelled since grace period is 0
		# And is backdated subscription so subscription will be cancelled after processing
		self.assertEqual(subscription.status, "Cancelled")

		settings.cancel_after_grace = default_grace_period_action
		settings.save()
		subscription.delete()
Exemplo n.º 52
0
def set_item_price_from_bin(bin):
    settings = frappe.get_single("POS Bahrain Settings")
    if settings.valuation_price_list and settings.valuation_warehouse == bin.warehouse:
        item_price = frappe.db.exists(
            "Item Price",
            {
                "item_code": bin.item_code,
                "price_list": settings.valuation_price_list
            },
        )
        valuation_rate = bin.valuation_rate or 0
        if item_price:
            if (frappe.db.get_value("Item Price", item_price,
                                    "price_list_rate") != bin.valuation_rate):
                frappe.db.set_value("Item Price", item_price,
                                    "price_list_rate", valuation_rate)
        else:
            frappe.get_doc({
                "doctype": "Item Price",
                "item_code": bin.item_code,
                "price_list": settings.valuation_price_list,
                "price_list_rate": valuation_rate,
            }).insert(ignore_permissions=True)
Exemplo n.º 53
0
 def setUp(self):
     dt = create_custom_doctype()
     settings = frappe.get_single("Patient History Settings")
     settings.append("custom_doctypes", {
         "document_type": dt.name,
         "date_fieldname": "date",
         "selected_fields": json.dumps([{
                     "label": "Date",
                     "fieldname": "date",
                     "fieldtype": "Date"
                     },
             {
             "label": "Rating",
             "fieldname": "rating",
             "fieldtype": "Rating"
         },
             {
             "label": "Feedback",
             "fieldname": "feedback",
             "fieldtype": "Small Text"
         }])
     })
     settings.save()
Exemplo n.º 54
0
	def test_subscription_cancel_after_grace_period(self):
		settings = frappe.get_single('Subscription Settings')
		default_grace_period_action = settings.cancel_after_grace
		settings.cancel_after_grace = 1
		settings.save()

		subscription = frappe.new_doc('Subscription')
		subscription.party_type = 'Customer'
		subscription.party = '_Test Customer'
		subscription.append('plans', {'plan': '_Test Plan Name', 'qty': 1})
		subscription.start_date = '2018-01-01'
		subscription.insert()

		self.assertEqual(subscription.status, 'Active')

		subscription.process()		# generate first invoice
		# This should change status to Cancelled since grace period is 0
		# And is backdated subscription so subscription will be cancelled after processing
		self.assertEqual(subscription.status, 'Cancelled')

		settings.cancel_after_grace = default_grace_period_action
		settings.save()
		subscription.delete()
Exemplo n.º 55
0
def on_submit(doc, method):
    excess_qty_items = []
    short_qty_items = []
    rejected_qty_items = []

    for item in doc.items:
        if item.custom_rejected_qty > 0:
            rejected_qty_items.append(item)
        if item.excess_quantity > 0:
            excess_qty_items.append(item)
        elif item.short_quantity > 0:
            short_qty_items.append(item)

    get_warehouse = frappe.get_single('MedTech Settings')
    if len(excess_qty_items) > 0:
        target_warehouse = get_warehouse.excess_warehouse
        make_material_receipt(excess_qty_items, doc, target_warehouse)
    if len(short_qty_items) > 0:
        target_warehouse = get_warehouse.short_warehouse
        make_material_issue(short_qty_items, doc, target_warehouse)
    if len(rejected_qty_items) > 0:
        target_warehouse = get_warehouse.rejected_warehouse
        make_material_transfer(rejected_qty_items, doc, target_warehouse)
Exemplo n.º 56
0
def get_enrollment(master, document, student):
    current_year = frappe.get_single("Education Settings").get(
        "current_academic_year")
    if master == 'program':
        enrollments = frappe.get_all("Program Enrollment",
                                     filters={
                                         'student': student,
                                         'program': document,
                                         'docstatus': 1
                                     })
    #enrollments = frappe.get_all("Program Enrollment", filters={'student':student, 'program': document, 'docstatus': 1, 'academic_year':  current_year})
    if master == 'course':
        enrollments = frappe.get_all("Course Enrollment",
                                     filters={
                                         'student': student,
                                         'course': document,
                                         'academic_year': current_year
                                     })

    if enrollments:
        return enrollments[0].name
    else:
        return None
Exemplo n.º 57
0
def delete_old_backups(limit, bucket):
    all_backups = list()
    doc = frappe.get_single("S3 Backup Settings")
    backup_limit = int(limit)

    s3 = boto3.resource(
        's3',
        aws_access_key_id=doc.access_key_id,
        aws_secret_access_key=doc.get_password('secret_access_key'),
    )
    bucket = s3.Bucket(bucket)
    objects = bucket.meta.client.list_objects_v2(Bucket=bucket.name,
                                                 Delimiter='/')
    for obj in objects.get('CommonPrefixes'):
        all_backups.append(obj.get('Prefix'))

    oldest_backup = sorted(all_backups)[0]

    if len(all_backups) > backup_limit:
        print "Deleting Backup: {0}".format(oldest_backup)
        for obj in bucket.objects.filter(Prefix=oldest_backup):
            # delete all keys that are inside the oldest_backup
            s3.Object(bucket.name, obj.key).delete()
Exemplo n.º 58
0
	def jv_accounts_paid(self):
		accounts = []
		recruitment_defaults = frappe.get_single("Recruitment Settings").__dict__

		if not recruitment_defaults['default_expense_account']:
			frappe.throw("Please set Default Expense Account in Recruitment Settings")

		accounts.append({
			'account': recruitment_defaults['default_expense_account'],
			'debit_in_account_currency': self.unit_price,
			'credit_in_account_currency': 0,
		})
		mop = frappe.db.sql(""" SELECT * FROM `tabMode of Payment Account` WHERE parent=%s """,
								 (recruitment_defaults['mode_of_payment']), as_dict=1)
		if len(mop) == 0:
			frappe.throw("Please set Mode of Payment in Recruitment Settings")

		accounts.append({
			'account': mop[0].default_account,
			'debit_in_account_currency': 0,
			'credit_in_account_currency': self.unit_price
		})
		return accounts
Exemplo n.º 59
0
def get_context(context):

	frappe.form_dict.revisions = True
	wiki_settings = frappe.get_single("Wiki Settings")
	context.banner_image = wiki_settings.logo
	context.script = wiki_settings.javascript
	context.docs_search_scope = ""
	can_edit = frappe.session.user != "Guest"
	context.can_edit = can_edit
	context.show_my_account = False

	revisions = frappe.db.get_all(
		"Wiki Page Revision",
		filters={"wiki_page": frappe.form_dict.wiki_page},
		fields=["message", "creation", "owner", "name", "raised_by"],
	)
	context.revisions = revisions
	context.no_cache = 1
	context.doc = frappe.get_doc('Wiki Page', frappe.form_dict.wiki_page)
	context.title = "Revisions: " + context.doc.title

	context.doc.set_breadcrumbs(context)
	return context
Exemplo n.º 60
0
	def test_subscription_cancellation_invoices_with_prorata_true(self):
		settings = frappe.get_single('Subscription Settings')
		to_prorate = settings.prorate
		settings.prorate = 1
		settings.save()

		subscription = frappe.new_doc('Subscription')
		subscription.customer = '_Test Customer'
		subscription.append('plans', {'plan': '_Test Plan Name', 'qty': 1})
		subscription.save()
		subscription.cancel_subscription()

		invoice = subscription.get_current_invoice()
		diff = flt(date_diff(nowdate(), subscription.current_invoice_start) + 1)
		plan_days = flt(date_diff(subscription.current_invoice_end, subscription.current_invoice_start) + 1)
		prorate_factor = flt(diff / plan_days)

		self.assertEqual(flt(invoice.grand_total, 2), flt(prorate_factor * 900, 2))

		settings.prorate = to_prorate
		settings.save()

		subscription.delete()