<reponame>EPIsumeet/Accounting-App
# -*- coding: utf-8 -*-
# Copyright (c) 2021, <NAME> and contributors
# For license information, please see license.txt

from __future__ import unicode_literals
# import frappe
import frappe
from frappe.model.document import Document
from datetime import datetime, date
import uuid


class PurchaseInvoice(Document):
         
	def on_submit(self):

		invoice = frappe.db.exists(
			"Purchase Invoice",
			{
			"invoice_id": self.invoice_id
			}
		)

		if invoice:
			frappe.throw("Invoice number already exist, please try again")


		""" For getting total amount from items in the bill """
		amount = 0       
		for each_item in self.item_details:
			amount = float(each_item.price) + float(amount)
		self.amount = amount
		self.date = datetime.now()


		""" Entering value for payment entry for supplier """
		
		payment_entry_for_supplier = frappe.new_doc('Payment Entry For Supplier')
		payment_entry_for_supplier.payment_entry_id = str(uuid.uuid1())
		payment_entry_for_supplier.date = self.date
		payment_entry_for_supplier.invoice_number = self.invoice_id
		payment_entry_for_supplier.party_name = self.party_name
		payment_entry_for_supplier.paid_from = self.assets_to
		payment_entry_for_supplier.paid_to = self.credit_to
		payment_entry_for_supplier.payment_amount = self.amount
		payment_entry_for_supplier.save()
		payment_entry_for_supplier.submit()
	        

		""" Entering values in the Journal for supplier"""

		journal_entry = frappe.new_doc('Journal Entry')
		account_entry = {
			'party_name': self.party_name,
			'account': self.assets_to,
			'party_type': "Supplier",
			"debit": self.amount,
			"credit": 0.00
		}
		
		journal_entry.entry_id = str(uuid.uuid1())
		journal_entry.date = self.date
		journal_entry.append('account_details', account_entry)
		journal_entry.total_debit = self.amount
		journal_entry.total_credit = 0.00
		journal_entry.save()
		journal_entry.submit()


		""" for saving data in the general ledger"""
		
		general_ledger = frappe.new_doc('General Ledger')
		general_ledger.date = date.today()
		general_ledger.account = self.assets_to
		general_ledger.against_account = self.credit_to
		general_ledger.debit = self.amount
		general_ledger.credit = 0.00
		general_ledger.voucher_type = "Purchase Invoice"
		general_ledger.fiscal_year = self.date.year
		general_ledger.transaction_date = self.date
		general_ledger.save()
		general_ledger.submit()
        
        
	
