Exemple #1
0
def execute():
    try:
        frappe.get_last_doc("Task Checklist")
    except DoesNotExistError:
        return

    filters = {'parenttype': ("=", "Task")}
    task_checklist = frappe.get_all("Task Checklist",
                                    filters=filters,
                                    fields="*")

    for checklist_row in task_checklist:
        try:
            task = frappe.get_doc("Task", checklist_row['parent'])
        except DoesNotExistError:
            continue

        task.append(
            'it_management_table', {
                'idx': checklist_row['idx'],
                'note': checklist_row['custom'],
                'dynamic_type': 'Configuration Item',
                'dynamic_name': checklist_row['configuration_item'],
                'checked': checklist_row['check']
            })
        task.save()
Exemple #2
0
    def test_job_card_overlap(self):
        wo2 = make_wo_order_test_record(item="_Test FG Item 2", qty=2)

        jc1 = frappe.get_last_doc("Job Card",
                                  {"work_order": self.work_order.name})
        jc2 = frappe.get_last_doc("Job Card", {"work_order": wo2.name})

        employee = "_T-Employee-00001"  # from test records

        jc1.append(
            "time_logs",
            {
                "from_time": "2021-01-01 00:00:00",
                "to_time": "2021-01-01 08:00:00",
                "completed_qty": 1,
                "employee": employee,
            },
        )
        jc1.save()

        # add a new entry in same time slice
        jc2.append(
            "time_logs",
            {
                "from_time": "2021-01-01 00:01:00",
                "to_time": "2021-01-01 06:00:00",
                "completed_qty": 1,
                "employee": employee,
            },
        )
        self.assertRaises(OverlapError, jc2.save)
Exemple #3
0
    def test_threading(self):
        cleanup(["in", ['*****@*****.**', '*****@*****.**']])

        # send
        sent_name = make(subject="Test",
                         content="test content",
                         recipients="*****@*****.**",
                         sender="*****@*****.**",
                         doctype="ToDo",
                         name=frappe.get_last_doc("ToDo").name,
                         send_email=True)["name"]

        sent_mail = email.message_from_string(
            frappe.get_last_doc("Email Queue").message)

        with open(
                os.path.join(os.path.dirname(__file__), "test_mails",
                             "reply-1.raw"), "r") as f:
            raw = f.read()
            raw = raw.replace("<-- in-reply-to -->",
                              sent_mail.get("Message-Id"))
            test_mails = [raw]

        # parse reply
        email_account = frappe.get_doc("Email Account",
                                       "_Test Email Account 1")
        email_account.receive(test_mails=test_mails)

        sent = frappe.get_doc("Communication", sent_name)

        comm = frappe.get_doc("Communication",
                              {"sender": "*****@*****.**"})
        self.assertEqual(comm.reference_doctype, sent.reference_doctype)
        self.assertEqual(comm.reference_name, sent.reference_name)
Exemple #4
0
	def test_shopping_cart_without_website_item(self):
		if frappe.db.exists("Website Item", {"item_code": "_Test Item Home Desktop 100"}):
			frappe.get_last_doc("Website Item", {"item_code": "_Test Item Home Desktop 100"}).delete()

		quotation = frappe.copy_doc(test_records[0])
		quotation.order_type = "Shopping Cart"
		quotation.valid_till = getdate()
		self.assertRaises(frappe.ValidationError, quotation.validate)
Exemple #5
0
def execute():
    try:
        frappe.get_last_doc("IT Ticket")
    except DoesNotExistError:
        return

    tickets = frappe.get_list("IT Ticket", filters={"title": ("!=", "")})

    for name in tickets:
        ticket = frappe.get_doc("IT Ticket", name)
        ticket.subject = ticket.title
        ticket.save()
def execute():
    try:
        frappe.get_last_doc("Task Checklist")
    except DoesNotExistError:
        return

    tc_list = frappe.get_list("Task Checklist",
                              filters={'parentfield': 'checklist_table'})

    for name in tc_list:
        tl = frappe.get_doc("Task Checklist", name)
        tl.parentfield = 'task_checklist'
        tl.save()
    def test_prevention_of_cancelled_transaction_riv(self):
        frappe.flags.dont_execute_stock_reposts = True

        item = make_item()
        warehouse = "_Test Warehouse - _TC"
        old = make_stock_entry(item_code=item.name,
                               to_warehouse=warehouse,
                               qty=2,
                               rate=5)
        _new = make_stock_entry(item_code=item.name,
                                to_warehouse=warehouse,
                                qty=5,
                                rate=10)

        old.cancel()

        riv = frappe.get_last_doc("Repost Item Valuation", {
            "voucher_type": old.doctype,
            "voucher_no": old.name
        })
        self.assertRaises(frappe.ValidationError, riv.cancel)

        riv.db_set("status", "Skipped")
        riv.reload()
        riv.cancel()  # it should cancel now
    def on_update_BACKUP(self):
        print(' -----------------  ' + inspect.currentframe().f_code.co_name +
              '  ---------------------- ')
        validater(self)

        # theCustomer = frappe.get_doc("Customer", "Abner Victor Manuel Galarza Sosa")
        theCustomer = frappe.get_doc("Customer", "Danilo Zumba")
        print(theCustomer.name)

        theCustomer.append("returnables", {"returnable": "IBCC423"})

        # # assign values to child table row
        # row.field_1 = "Test"
        # row.field_2 = "Test"
        # doc.save()

        # acct = frappe.new_doc("Party Account")
        # acct.company = "Logichem Solutions S. A."
        # acct.account = "1.1.3.01.001 - Cuentas Por Cobrar Clientes - LSSA"

        # print(acct)

        # theCustomer.accounts.append(acct)
        theCustomer.save()

        # returnables = theCustomer.append("returnables", [{
        #   "returnable": "IBCC423"
        # }])
        # print(theCustomer.returnables)
        # print(theCustomer.returnables[0])
        # print(theCustomer.returnables[0].returnable)

        # theCustomer.returnables.append(CST_item)

        # print(json.dumps({'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}},
        #                  sort_keys=True, indent=4))
        # print(json.dumps(theCustomer,
        #                  sort_keys=True, indent=4))

        # customer = frappe.get_doc("Returnable Batch")
        last_batch = frappe.get_last_doc("Returnable Batch")
        print("")
        print("")
        print("last_batch.name")
        print(last_batch.name)

        # doc = frappe.new_doc('Returnable Holder')
        # doc.parent = "Abner Victor Manuel Galarza Sosa"
        # doc.returnable = "IBCC423"
        # doc.batch = last_batch.name
        doc.insert()

        #       name: RTN-CST-000000001
        #  docstatus: 1
        #     parent: Abner Victor Manuel Galarza Sosa
        #        idx: 1
        # returnable: IBCC423
        # batch_item: NULL

        print("  INSERTED ")
 def make_sales_order(self):
     if self.has_placement_test and not frappe.db.exists("Sales Order", {"program_application": self.name}):
         si = frappe.new_doc("Sales Order")
         si.update({
             "customer": self.student_name,
             "transaction_date": frappe.utils.nowdate(),
             "company": self.company,
             "program_application": self.name,
             "currency": self.currency
         })
         si.append("items", {
             "item_code": self.placement_test,
             "qty": 1,
             "rate": self.placement_test_amount,
             "uom": "nos",
             "conversion_factor": 1,
             "item_name": self.placement_test,
             "description": self.placement_test,
             "delivery_date": frappe.utils.nowdate(),
         })
         si.append("payment_schedule", {
             "due_date": frappe.utils.nowdate(),
             "payment_amount": self.placement_test_amount,
             "description": self.placement_test,
         })
         si.save()
         si.submit()
         sales_order = frappe.get_last_doc("Sales Order")
         link = ["""<a href=desk#Form/Sales%20Order/{0}>{0}</a>""".format(sales_order.name)]
         frappe.msgprint(_("Sales Order Created - {0} For Placement Test").format(comma_and(link)))
Exemple #10
0
def get_last_loan():

    headers = ["Access-Control-Allow-Origin: *"]
    frappe.response.headers = headers

    return frappe.get_last_doc("Loan")\
     .as_dict()
def make_inv(customer, customer_name, due_date, courses):
	from frappe import utils
        import json
	count = 0        
	courses = json.loads(courses)
        udoc = frappe.new_doc("Sales Invoice")
        udoc.naming_series = "ACC-SINV-.YYYY.-"
        udoc.customer = customer
        udoc.customer_name = customer_name
        for i in range(len(courses)):	
		fdata = frappe.get_doc('Course', courses[i])		
		if(fdata.item):
			count= count + 1			
			udoc.append('items', {
			'item_code': fdata.item,
			'qty': '1',
			})
	udoc.posting_date = frappe.utils.nowdate()
	udoc.due_date = due_date
	if( count!=0 ):	
		udoc.save()
		return frappe.get_last_doc("Sales Invoice");	
	else:
		msgprint(_("Invoice couldn't be generated : None of your courses have an item group assigned."))
		return			
Exemple #12
0
	def test_print_format(self):
		make(sender="*****@*****.**", recipients="*****@*****.**",
			content="test mail 001", subject="test-mail-002", doctype="Email Account",
			name="_Test Email Account 1", print_format="Standard", send_email=True)

		sent_mail = email.message_from_string(frappe.get_last_doc("Email Queue").message)
		self.assertTrue("test-mail-002" in sent_mail.get("Subject"))
Exemple #13
0
    def test_job_card_partial_material_transfer(self):
        "Test partial material transfer against Job Card"
        self.transfer_material_against = "Job Card"
        self.source_warehouse = "Stores - _TC"

        self.generate_required_stock(self.work_order)

        job_card = frappe.get_last_doc("Job Card",
                                       {"work_order": self.work_order.name})

        # partially transfer
        transfer_entry = make_stock_entry_from_jc(job_card.name)
        transfer_entry.fg_completed_qty = 1
        transfer_entry.get_items()
        transfer_entry.insert()
        transfer_entry.submit()

        job_card.reload()
        self.assertEqual(job_card.transferred_qty, 1)
        self.assertEqual(transfer_entry.items[0].qty, 5)
        self.assertEqual(transfer_entry.items[1].qty, 3)

        # transfer remaining
        transfer_entry_2 = make_stock_entry_from_jc(job_card.name)

        self.assertEqual(transfer_entry_2.fg_completed_qty, 1)
        self.assertEqual(transfer_entry_2.items[0].qty, 5)
        self.assertEqual(transfer_entry_2.items[1].qty, 3)

        transfer_entry_2.insert()
        transfer_entry_2.submit()

        job_card.reload()
        self.assertEqual(job_card.transferred_qty, 2)
Exemple #14
0
	def get_data(self, args):
		self.data = []

		self.receivables = ReceivablePayableReport(self.filters).run(args)[1]

		self.get_party_total(args)

		party_advance_amount = get_partywise_advanced_payment_amount(self.party_type,
			self.filters.report_date, self.filters.company) or {}
		recent_sales_order = frappe.get_last_doc("Sales Order")

		for party, party_dict in iteritems(self.party_total):
			if party_dict.outstanding == 0:
				continue

			row = frappe._dict()

			row.party = party
			if self.party_naming_by == "Naming Series":
				row.party_name = frappe.get_cached_value(self.party_type, party, scrub(self.party_type) + "_name")
			row.territory_turk = recent_sales_order.territory
			row.owner_so = recent_sales_order.owner
			row.cost_center = recent_sales_order.cost_center

			row.update(party_dict)

			# Advance against party
			row.advance = party_advance_amount.get(party, 0)

			# In AR/AP, advance shown in paid columns,
			# but in summary report advance shown in separate column
			row.paid -= row.advance

			self.data.append(row)
Exemple #15
0
 def enroll_in_program(self, program_name):
     try:
         enrollment = frappe.get_doc({
             "doctype":
             "Program Enrollment",
             "student":
             self.name,
             "academic_year":
             frappe.get_last_doc("Academic Year").name,
             "program":
             program_name,
             "enrollment_date":
             frappe.utils.datetime.datetime.now(),
         })
         enrollment.save(ignore_permissions=True)
     except frappe.exceptions.ValidationError:
         enrollment_name = frappe.get_list("Program Enrollment",
                                           filters={
                                               "student": self.name,
                                               "Program": program_name
                                           })[0].name
         return frappe.get_doc("Program Enrollment", enrollment_name)
     else:
         enrollment.submit()
         return enrollment
	def test_outgoing(self):
		frappe.flags.sent_mail = None
		make(subject = "test-mail-000", content="test mail 000", recipients="*****@*****.**",
			send_email=True, sender="*****@*****.**")

		mail = email.message_from_string(frappe.get_last_doc("Bulk Email").message)
		self.assertTrue("test-mail-000" in mail.get("Subject"))
    def test_threading(self):
        frappe.db.sql("""delete from tabCommunication
			where sender in ('*****@*****.**', '*****@*****.**')""")

        # send
        sent_name = make(subject="Test",
                         content="test content",
                         recipients="*****@*****.**",
                         sender="*****@*****.**",
                         send_email=True)

        sent_mail = email.message_from_string(
            frappe.get_last_doc("Bulk Email").message)
        with open(
                os.path.join(os.path.dirname(__file__), "test_mails",
                             "reply-1.raw"), "r") as f:
            raw = f.read()
            raw = raw.replace("<-- in-reply-to -->",
                              sent_mail.get("Message-Id"))
            test_mails = [raw]

        # parse reply
        email_account = frappe.get_doc("Email Account",
                                       "_Test Email Account 1")
        email_account.receive(test_mails=test_mails)

        sent = frappe.get_doc("Communication", sent_name)

        comm = frappe.get_doc("Communication",
                              {"sender": "*****@*****.**"})
        self.assertEquals(comm.reference_doctype, sent.doctype)
        self.assertEquals(comm.reference_name, sent.name)
	def test_outgoing(self):
		frappe.flags.sent_mail = None
		make(subject = "test-mail-000", content="test mail 000", recipients="*****@*****.**",
			send_email=True, sender="*****@*****.**")

		mail = email.message_from_string(frappe.get_last_doc("Bulk Email").message)
		self.assertTrue("test-mail-000" in mail.get("Subject"))
def import_data(filters):
    try:
        last_doc = frappe.get_last_doc('File')
        file = open(frappe.utils.get_site_path("private")+"/files/"+last_doc.file_name, "rb")
        # df = pd.read_excel (file,header=0)
        df = pd.read_excel(file,header=0, engine='openpyxl')
        d= df.to_dict(orient='records')

        # modify Dictonary
        for data in d:
            ss = list(data.items())
            date_data_dict = dict(ss[4:])
            temp_list = []
            temp_list.append(date_data_dict)
            data["Item_data"] = temp_list

        # Import/Update data
        for main_data in d:
            for date_data in main_data.get("Item_data")[0]:
                today_date = date.today()
                date_dt3 = datetime.strptime(date_data, '%d-%m-%Y').date()
                if date_dt3 > today_date:
                    frappe.db.sql("""UPDATE `tabPlanning Master Item` set amount={0}
                                where planning_master_parent='{1}' and date='{2}' and item_code='{3}' and bom='{4}'""".format(main_data.get(date_data),filters,date_dt3,main_data.get("Item_Code"),main_data.get("BOM")),debug=1)
        return "Data Import Done Successfully,Please Click on Reload button."
    except Exception as e:
        raise e
	def test_print_format(self):
		make(sender="*****@*****.**", recipients="*****@*****.**",
			content="test mail 001", subject="test-mail-002", doctype="Email Account",
			name="_Test Email Account 1", print_format="Standard", send_email=True)

		sent_mail = email.message_from_string(frappe.get_last_doc("Email Queue").message)
		self.assertTrue("test-mail-002" in sent_mail.get("Subject"))
	def test_threading(self):
		frappe.db.sql("""delete from tabCommunication
			where sender in ('*****@*****.**', '*****@*****.**')""")

		# send
		sent_name = make(subject = "Test", content="test content",
			recipients="*****@*****.**", sender="*****@*****.**",
			send_email=True)["name"]

		sent_mail = email.message_from_string(frappe.get_last_doc("Bulk Email").message)

		with open(os.path.join(os.path.dirname(__file__), "test_mails", "reply-1.raw"), "r") as f:
			raw = f.read()
			raw = raw.replace("<-- in-reply-to -->", sent_mail.get("Message-Id"))
			test_mails = [raw]

		# parse reply
		email_account = frappe.get_doc("Email Account", "_Test Email Account 1")
		email_account.receive(test_mails=test_mails)

		sent = frappe.get_doc("Communication", sent_name)

		comm = frappe.get_doc("Communication", {"sender": "*****@*****.**"})
		self.assertEquals(comm.reference_doctype, sent.doctype)
		self.assertEquals(comm.reference_name, sent.name)
    def test_private_file_download(self):
        # create new private file
        new_private_file = frappe.get_doc({
            'doctype':
            self.test_doctype,
            'file_name':
            self.file_name,
            'content':
            base64.b64encode(self.test_content.encode('utf-8')),
            'is_private':
            1,
        })
        new_private_file.insert()

        # access the created file
        private_file_link = get_site_url(
            frappe.local.site) + new_private_file.file_url

        try:
            request = requests.post(private_file_link, headers=self.header)
            last_doc = frappe.get_last_doc('Access Log')

            if request.ok:
                # check for the access log of downloaded file
                self.assertEqual(new_private_file.doctype,
                                 last_doc.export_from)
                self.assertEqual(new_private_file.name,
                                 last_doc.reference_document)

        except requests.ConnectionError:
            pass

        # cleanup
        new_private_file.delete()
def execute():
    try:
        frappe.get_last_doc("Configuration Item Table")
    except DoesNotExistError:
        return

    filters = {
        'linked_configuration_item': ("!=", ""),
        'configuration_item': ("=", "")
    }
    cit_list = frappe.get_list("Configuration Item Table", filters=filters)

    for name in cit_list:
        tl = frappe.get_doc("Configuration Item Table", name)
        tl.configuration_item = tl.linked_configuration_item
        tl.save()
    def test_make_export_log(self):
        # export data and delete temp file generated on disk
        export_csv(self.test_doctype, self.file_name)
        os.remove(self.file_name)

        # test if the exported data is logged
        last_doc = frappe.get_last_doc('Access Log')
        self.assertEqual(self.test_doctype, last_doc.export_from)
Exemple #25
0
def get_boot_info(bootinfo):
    holiday_doc = frappe.get_last_doc("Holiday List")

    bootinfo.year_holidays = []

    for holiday in holiday_doc.holidays:
        bootinfo.year_holidays += [holiday.holiday_date]

    bootinfo.general_conf = frappe.get_single("Configuracion General")
Exemple #26
0
    def test_field_autoname_name_sync(self):

        country = frappe.get_last_doc("Country")
        original_name = country.name
        country.country_name = "Not a country"
        country.save()
        country.reload()

        self.assertEqual(country.name, original_name)
        self.assertEqual(country.name, country.country_name)
Exemple #27
0
    def test_outgoing(self):
        make(subject="test-mail-000",
             content="test mail 000",
             recipients="*****@*****.**",
             send_email=True,
             sender="*****@*****.**")

        mail = email.message_from_string(
            frappe.get_last_doc("Email Queue").message)
        self.assertTrue("test-mail-000" in mail.get("Subject"))
    def test_decrease_stock_quantity(self):
        asset_repair = create_asset_repair(stock_consumption=1, submit=1)
        stock_entry = frappe.get_last_doc('Stock Entry')

        self.assertEqual(stock_entry.stock_entry_type, "Material Issue")
        self.assertEqual(stock_entry.items[0].s_warehouse,
                         asset_repair.warehouse)
        self.assertEqual(stock_entry.items[0].item_code,
                         asset_repair.stock_items[0].item)
        self.assertEqual(stock_entry.items[0].qty,
                         asset_repair.stock_items[0].consumed_quantity)
Exemple #29
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()
Exemple #30
0
    def test_transaction_writes_error(self):
        from frappe.database.database import Database

        frappe.db.rollback()

        frappe.db.MAX_WRITES_PER_TRANSACTION = 1
        note = frappe.get_last_doc("ToDo")
        note.description = "changed"
        with self.assertRaises(frappe.TooManyWritesError) as tmw:
            note.save()

        frappe.db.MAX_WRITES_PER_TRANSACTION = Database.MAX_WRITES_PER_TRANSACTION
Exemple #31
0
 def _get_product_bundle_qty_map(
         self, bundles: List[str]) -> Dict[str, Dict[str, float]]:
     # bundle_item_code: Dict[component, qty]
     product_bundle_qty_map = {}
     for bundle_item_code in bundles:
         bundle = frappe.get_last_doc("Product Bundle",
                                      {"new_item_code": bundle_item_code})
         product_bundle_qty_map[bundle_item_code] = {
             item.item_code: item.qty
             for item in bundle.items
         }
     return product_bundle_qty_map
Exemple #32
0
def make_inv(customer, customer_name, due_date, courses, fees):
    count = 0
    #courses and fees are lists that have the docnames from the front end
    courses = json.loads(courses)
    fees = json.loads(fees)
    udoc = frappe.new_doc("Sales Invoice")
    udoc.customer = customer
    udoc.customer_name = customer_name
    #Fees
    if(fees):
        for d in fees:
            #fetch fee_structure, it has the amount for the sales invoice, as well as..
            fee_structure = frappe.get_doc("Fee Structure", d)
            for e in fee_structure.components:
                fee_amount = e.amount
                #The fee category. This is have a new field for 
                #"Items" doctype, which will make sure each
                #course correlates to a proper item for identification
                fetched_item = frappe.get_doc("Fee Category", e.fees_category)
                if(fetched_item.item):
                    udoc.append('items', {
                    'item_code': fetched_item.item,
                    'qty': '1',
                    'rate': fee_amount,
                    'amount': fee_amount,
                    })
                count = count + 1
                #Only for checking if the sales invoice will turn out empty
                #In case none of the fee category or the Course doctypes
                #Have any items listed
    #For course
    if(courses):
        for i in range(len(courses)):
            fdata = frappe.get_doc('Course', courses[i])
            if(fdata.item):
                count= count + 1
                udoc.append('items', {
                'item_code': fdata.item,
                'qty': '1',
                })
    udoc.set_posting_time = True
    udoc.posting_date = due_date
    udoc.due_date = due_date
    udoc.posting_time = None
    udoc.set_taxes()
    #saves only if there is at least one potential tx
    if( count > 0 ):	
        udoc.save()
        return frappe.get_last_doc("Sales Invoice");	
    else:
        msgprint(_("Invoice couldn't be generated : None of your courses or fee structures have an item group assigned."))
        return
Exemple #33
0
    def create_loan(self):
        self.loan_appl = frappe.get_last_doc("Loan Application")
        self.interest_rate = 1.32

        loan = create_loan_from_appl(self.loan_appl)
        loan.mode_of_payment = "Cash"
        loan.party_account = frappe.get_value("Account",
                                              {"account_type": "Receivable"})

        loan.loan_application = pick_one_loan_appl()

        loan.insert()
        self.loan = loan