Tuesday, 27 March 2018

how to generate new document of form from popup value


@frappe.whitelist()
def add_interaction(doc):
        doc_json=json.loads(doc)
        doc = frappe.get_doc(doc_json)
        doc.date = utils.now()
        if doc.doctype != "Interaction":
                frappe.throw(_("This method can only be used to create a Interaction Master"), frappe.PermissionError)
        doc.insert(ignore_permissions = True)
        return doc.as_dict()

How to create custom button and generate popup and get value of that popup and call python function and create new doctype


frappe.ui.form.on("Quotation", "refresh", function(frm, doctype, name) {
cur_frm.add_custom_button(__('Add Interaction'), function() {
var d = frappe.prompt([
    {'fieldname': 'person_interacted_with', 'fieldtype': 'Data', 'label': 'Person Interacted with', 'reqd': 0},   
    {'fieldname': 'type_of_interaction', 'fieldtype': 'Link', options:"Interaction Type",'label': 'Type of Interaction', 'reqd': 0},
    {'fieldname': 'result', 'fieldtype': 'Link', options:"Interaction Result",'label': 'Result', 'reqd': 0},
    {'fieldname': 'responsible', 'fieldtype': 'Link', options:"User", 'default': user, 'label': 'Responsible', 'reqd': 0},
    {'fieldname': 'create_task', 'fieldtype': 'Check', 'default': true, 'label': 'Create Task'},
    {fieldtype: "Column Break"},

    {'fieldname': 'next_date', 'fieldtype': 'Date',
    'label': 'Next Action Date', 'default': frappe.datetime.add_days(frappe.datetime.nowdate(),7), 'reqd': 0},
    {'fieldname': 'next_action_by', 'fieldtype': 'Link', options:"User", 'default': user,'label': 'Next Action By', 'reqd': 0},
    {'fieldname': 'comment', 'fieldtype': 'Text', 'label': 'Next Action Task', 'reqd': 1},
    {fieldtype: "Section Break"},

    {'fieldname': 'remarks', 'fieldtype': 'Text Editor', 'label': 'Remarks', 'reqd': 1}
],
function(values){
    // How to get popup value
    var c = d.get_values()
    var cmnt = "Person Interacted with: "+ c.person_interacted_with
               +"<br>Type of Interaction: "+ c.type_of_interaction
               +"<br>Result: "+ c.result
             
               // call the python fuction and pass the argument
    var me = frm.doc
       frappe.call({
            method: "dpicrm.custom_method.add_interaction",
            args: {
                doc:{
                    doctype: "Interaction",
                    reference_doctype: frm.doc.doctype,
                    reference_name: frm.doc.name,
                    result: c.result,
                    person_interacted_with: c.person_interacted_with,
                    next_action_date: c.next_date,
                    type_of_interaction: c.type_of_interaction,
                    // result: c.result,
                    next_action_by: c.next_action_by,
                    next_action_task: c.comment,
                    remarks: c.remarks,
                    responsible: c.responsible
                    // next_date
                }
            },
            callback: function(r) {
                        msgprint("Interaction master record created");
            }
        });
 
},
'Submit','Add Interaction', "btn-default"
)
});

});


python code


@frappe.whitelist()
def add_interaction(doc):
        doc_json=json.loads(doc)
        doc = frappe.get_doc(doc_json)
        doc.date = utils.now()
        if doc.doctype != "Interaction":
                frappe.throw(_("This method can only be used to create a Interaction Master"), frappe.PermissionError)
        doc.insert(ignore_permissions = True)
        return doc.as_dict()

How to remove and hide button

frappe.ui.form.on("doctype_name", {
refresh: function(frm) {
            $('.row.form-section.form-dashboard.visible-section').hide();
            $( ":button.btn.btn-default.btn-xs:contains(Accounting Ledger)" ).hide();
            $( ":button.btn.btn-default.btn-xs:contains(Accounts Receivable)" ).hide();
            $("ul.dropdown-menu li:contains('Links')").remove();
            $("ul.dropdown-menu li:contains('Customize')").remove();
            $("ul.dropdown-menu li:contains('Print')").remove();
    }
});

How to write query in frappe to generate get attendance api

we are to collect enroll no from if shift schedule employee and employee list employee_id is same then only get enroll no
Note-: we are create api on get shift schedule(table) but we want to get enroll no from employee(table).



select  employee_name,
employee_id,
case when (1=1)
then (select enroll_number from `tabEmployee`
where `tabEmployee`.name = `tabShift Schedule`.employee_id)
else 0
end as enroll_number,
leave_type, attendance_date, company, store, shift_time, start_time, end_time, amended_from\
    FROM `tabShift Schedule`
    WHERE attendance_date='{0}'""".format(attendance_date),as_dict=1)

create api

http://asdf.com/api/method/asd.api.api.create_attendance?
employee=EMP/asdfghjk&&
attendance_date=201&&in_store=test&&out_store=test1&&
in_time=test&&out_time=test&&company=demo%20-%20asdffg%20Co.%20xyz.



@frappe.whitelist(allow_guest=True)
def create_attendance(employee=None, attendance_date='',in_store='',out_store='',in_time='',out_time='',company=''):

attendance_doc = frappe.new_doc("Attendance")
attendance_doc.employee = employee
attendance_doc.attendance_date = attendance_date
attendance_doc.in_store = in_store
attendance_doc.out_store = out_store
attendance_doc.in_time = in_time
attendance_doc.out_time = out_time
attendance_doc.company = company
attendance_doc.insert(ignore_permissions=True)
attendance_doc.save(ignore_permissions=True)
frappe.db.commit()
return { "message":"New Attendance {0} Is Created".format(employee),
"status": "success","user_message":"New Attendance {0} Is Created".format(employee)}

Get list api in frappe


http://0.0.0.0:8000/api/method/bnd.api.mahesh.get_leave_application?employee=EMP/0003&&from_date=2018-03-29
here bnd is application name , api is directory, mahesh is python file under api directory, get_leave_application is method 

@frappe.whitelist(allow_guest=True)
def get_leave_application(employee='',from_date=''):
leave_list = ''

if employee and from_date:
leave_list = frappe.db.sql("""select employee,status, leave_type,leave_balance, from_date, to_date, total_leave_days ,description, leave_approver, posting_date, company, half_day_date
from `tabLeave Application` WHERE employee='{0}' and from_date='{1}' """.format(employee,from_date),as_dict=1)
elif employee :
leave_list = frappe.db.sql("""select employee, status,leave_type, leave_balance, from_date, to_date, total_leave_days ,description, leave_approver, posting_date, company, half_day_date
from `tabLeave Application` WHERE employee='{0}'""".format(employee),as_dict=1)

return leave_list

Thursday, 15 March 2018

Write Api in Frapee with python(first api)

from __future__ import unicode_literals
import frappe, os, json


@frappe.whitelist(allow_guest=True)
def ping():
return "pong"



@frappe.whitelist(allow_guest=True)
def get_device_list():
device_list = frappe.db.sql("select name from `tabDevice`", as_dict=1)

return device_list

How to convert Amount in arebic

Hooks.py


doc_events = {
"Sales Invoice": {
"validate": "modag.api.arebic_amount"

},
"Sales Order": {
"validate": "modag.api.arebic_amount"

},
"Sales Quotation": {
"validate": "modag.api.arebic_amount"

}
}



api.py

from   frappe.model.document import Document
import frappe
from num2words import num2words
# def arebic_amount(self):
# frappe.msgprint("Test")

@frappe.whitelist()
def arebic_amount(doc,method):
num2words(10100,lang='ar')
doc.amount_in_words_arebic = num2words( doc.grand_total,lang='ar')
frappe.msgprint("arebic conversion is success")

Wednesday, 14 March 2018

Auto Fetch field

cur_frm.add_fetch('employee', 'employee_name', 'employee_name');
cur_frm.add_fetch('employee', 'employee', 'employee_id');

When select device rest field auto fetch

cur_frm.add_fetch('device_name', 'device_model', 'device_model');
cur_frm.add_fetch('device_name', 'device_no', 'device_no');
cur_frm.add_fetch('device_name', 'ip_address', 'ip_address');

Add page break after every 8 element in print format

   {% if loop.index % 8==0 -%}
            </tbody>
            </table>
        <div class="page-break"></div>
        <table class="table table-condensed table-bordered tableCentered">
        <tr>
            <th>{{ _("Item Code") }}</th>
            <th>{{ _("Description") }}</th>
            <th>{{ _("Unit") }}</th>
            <th>{{ _("Quantity") }}</th>
            <th>{{ _("Price") }}</th>
            <th>{{ _("Discount") }}</th>
            <th>{{ _("Sub Total") }}</th>
            <th>{{ _("Tax") }}</th>
        </tr>
        {%- endif %}
 
        {% if row.page_break -%}
            </tbody>
            </table>
        <div class="page-break"></div>

        <table class="table table-condensed table-bordered tableCentered tableLogo">
            <tr style="border:none !important;">
              <td rowspan="2" style="border:none !important;">
                <img src="/files/images.jpg" alt = "Levis Logo" style="width:150px !important;">
              </td>
              <td class="lineSpace" rowspan="2" style="border:none !important;">
                    <p class = "line_height" style="font-size:16px; padding-top:5px !important;"><label>{{ doc.company or "" }}</label></p>
                    {% set company = frappe.get_doc("Company", doc.company) %}
                   
              </td>
             
            </tr> 
           
            </tr>
        </table>

Tuesday, 6 March 2018

Calculating Values in Child Tables

frappe.ui.form.on("[CHILD TABLE DOCTYPE]", {
 [CHILDTABLEMULTIPLE1]: function(frm, cdt, cdn) {
  var d = locals[cdt][cdn];
  var total = 0;
  frappe.model.set_value(d.doctype, d.name, "[CHILDTABLEPRODUCT]", d.[CHILDTABLEMULTIPLE1] * d.[CHILDTABLEMULTIPLE2]);
        frm.doc.[CHILDTABLEFIELDINPARENT].forEach(function(d) { total += d.[CHILDTABLEPRODUCT]; });
        frm.set_value('[PARENTDOCTYPETOTALFIELD]', total);
 }
});
frappe.ui.form.on("[CHILD TABLE DOCTYPE]", {
 [CHILDTABLEMULTIPLE2]: function(frm, cdt, cdn) {
  var d = locals[cdt][cdn];
  var total = 0;
  frappe.model.set_value(d.doctype, d.name, "[CHILDTABLEPRODUCT]", d.[CHILDTABLEMULTIPLE1] * d.[CHILDTABLEMULTIPLE2]);
        frm.doc.[CHILDTABLEFIELDINPARENT].forEach(function(d) { total += d.[CHILDTABLEPRODUCT]; });
        frm.set_value('[PARENTDOCTYPETOTALFIELD]', total);
 }
});

Push Changes to a document from another document

//Replace "DocType" with the source DocType
frappe.ui.form.on("DocType", {
 //The trigger can be changed, but refresh must be used to use a button
 refresh: function(frm) {
  //The following line creates a button.
  frm.add_custom_button(__("Update"),
   //The function below is triggered when the button is pressed.
   function() {
    frappe.call({
     "method": "frappe.client.set_value",
     "args": {
      //replace "Target DocType" with the actual target doctype
      "doctype": "Target DocType",
      //replace target_doctype_link with a link to the document to be changed
      "name": frm.doc.target_doctype_link,
      "fieldname": {
       //You can update as many fields as you want.  
       "target_field_1": frm.doc.source_field_1,
       "target_field_2": frm.doc.source_field_2,
       "target_field_3": frm.doc.source_field_3,
       "target_field_4": frm.doc.source_field_4,
       "target_field_5": frm.doc.source_field_5  //Make sure that you do not put a comma over the last value
      },
     }
    });
  });
 }
});

Fetch fields from another DocType into a child table

frappe.ui.form.on("[PARENT_DOCTYPE_TARGET]", "refresh", function(frm) {
frappe.ui.form.on("[CHILD_TABLE_TARGET_DOCTYPE]", {
"[CHILD_TABLE_LINK FIELD]": function(frm) {
frm.add_fetch("[CHILD_TABLE_LINK FIELD]", "[SOURCE_CUSTOM_FIELD2]", "[TARGET_CUSTOM_FIELD2]");
}
});

});

Fetch child table


frappe.ui.form.on("DocTypeB", "Trigger", function(frm) {
    frappe.model.with_doc("DocTypeA", frm.doc.trigger, function() {
        var tabletransfer= frappe.model.get_doc("DocTypeA", frm.doc.Trigger)
        $.each(qmtable.ChildTableA, function(index, row){
            d = frm.add_child("ChildTableB");
            d.field1 = row.fielda;
            d.field2 = row.fieldb;
            cur_frm.refresh_field("ChildTableB");
        });
    })
});

Filter the selections of a field in a child document

cur_frm.fields_dict['items'].grid.get_field('item_code').get_query = function(doc, cdt, cdn) {
 return {
  filters:{'default_supplier': doc.supplier}
 }
}

Filter the selections of a field in a parent document

cur_frm.fields_dict['item_code'].get_query = function(doc, cdt, cdn) {
 return {
  filters:{'default_supplier': doc.supplier}
 }
}

Remove a Standard button from Form's toolbar


cur_frm.cscript.custom_refresh = function() {
if(!cur_frm.doc.__islocal && cur_frm.doc.owner === user) {
cur_frm.appframe.buttons.Submit.remove();
}
}

Cancel permission based on grand total

cur_frm.cscript.custom_before_cancel = function(doc) {
 if (user_roles.indexOf("Accounts User")!=-1 && user_roles.indexOf("Accounts Manager")==-1
   && user_roles.indexOf("System Manager")==-1) {
  if (flt(doc.grand_total) > 10000) {
   msgprint("You can not cancel this transaction, because grand total \
    is greater than 10000");
   validated = false;
  }
 }
}

Date Validation: Do not allow past dates in a date field

cur_frm.cscript.custom_validate = function(doc) {
 if (doc.from_date < get_today()) {
  msgprint("You can not select past date in From Date");
  validated = false;
 }
}

Fetching value when field change

Example, get default "cash_bank_account" when mode_of_payment is updated
On client side:
cur_frm.cscript.mode_of_payment = function(doc) {
 cur_frm.call({
  method: "get_bank_cash_account",
  args: { mode_of_payment: doc.mode_of_payment }
 });
}

Get value from server

frappe.call({
    method:"frappe.client.get_value",
    args: {
        doctype:"Delivery Note Item",
        filters: {
            parent:"DN00038",
            item_code:"Ser/003"
        },
        fieldname:["qty", "stock_uom"]
    }, 
    callback: function(r) { 
        console.log(r);

        // set the returned value in a field
        cur_frm.set_value(fieldname, r.message);
    }
})

Apply filter on filed


cur_frm.fields_dict.company.get_query = function(doc) {
  return {filters: { "doctor": doc.doctor}}
}

Hide Field Based on Some condition

cur_frm.cscript.custom_refresh = function(doc) {
    cur_frm.toggle_display("myfield1", doc.myfield2=="some_value");
}
Or
cur_frm.cscript.custom_refresh = function() {
 $('.btn-group[data-label="Make"]').hide();
}

Make Field as Read only

// use the __islocal value of doc, to check if the doc is saved or not
frm.set_df_property("myfield", "read_only", frm.doc.__islocal ? 0 : 1);

Custom script on field

frappe.ui.form.on("Salary Slip", {
  company: function(frm) {
    // this function is called when the value of company is changed.

  }
});

Django rest api - filter

views.py from django_filters.rest_framework import DjangoFilterBackend class PollList(viewsets.ModelViewSet):     queryset = X.objects...