Friday, 19 June 2015

How to write Client Side and Server Side Script in Frappe

Lets see, we have one requirement.
In Purchase Invoice, We need to add Payment Due Date. Payment Due Date is equal to Posting Date + Credit Days.
Also one more requirement, Supplier Invoice No should be unique in all Purchase Invoice.
Steps to achieve this. 1)  Create custom field ‘Credit Days’ and ‘Due Date’ in Purchase Invoice.
To fetch value of Credit Days from supplier into purchase invoice, write this script in Purchase Invoice.

    cur_frm.add_fetch(supplier ,'credit_days','credit_days');

2) To calculate Due Date = Posting Date + Credit Days, write below script in Purchase Invoice.

    frappe.ui.form.on("Purchase Invoice ", " validate ", function(frm) {
        var nos = frm.doc.credit_days* 1;
        var ddate = frappe.datetime.add_days(frm.doc.posting_date,nos);
        cur_frm.set_value("due_date", ddate);

i) doc.field_name will give value of current doc.
ii) cur_frm.set_value("field_name", value) used to set value.

3) To add validation, Supplier Invoice No should be unique in all Purchase Invoice.
(This will explain how to call server side method using hooks.)

In write this code

    doc_events = {
        "Purchase Invoice": {
            "validate": "sf_custom_changes.sf_acc.purchase.validate_bill_no"

In write this code

    def validate_bill_no(self, method):
            if self.bill_no:
                # validate bill no is unique
                bill_list = frappe.db.sql("""select name from `tabPurchase Invoice` where bill_no=%s and docstatus =1""",
                if len(bill_list) > 0:
                    items = [e[0] for e in bill_list if e[0]!]
                    frappe.throw(_("Supplier Invoice Number must be unique. Current Supplier Invoice Number already exists for {0}").format(comma_and(items)))
            if self.bill_date:
                    if getdate(self.bill_date) > getdate(self.posting_date):
                        frappe.throw(_("Supplier Invoice Date cannot be after Purchase Order Date"))

This will help you to write client and server side script. Please ask if you have any doubt in this example.