Monday, 30 November 2015

working with frappe page

creating own report and add filter access fields on page

sample code

js code
frappe.provide('frappe.pages');
frappe.provide('frappe.views');
frappe.provide('sample_register');

var cur_page = null;
frappe.pages['jobcard'].on_page_load = function(wrapper) {
    var page = frappe.ui.make_app_page({
        parent: wrapper,
        title: 'Job Card Creation',
        single_column: true
    });
    var options = {
        doctype: "Sample",
        parent: page
    };
    $("<table width='100%>\
  <tr>\
    <td valign='top' width='50%'>\
      <div id='myGrid' style='width:600px;height:500px;''></div>\
    </td>\
  </tr>\
</table>").appendTo($(wrapper).find('.layout-main-section'));
    setTimeout(function(){
        new new sample_register.JobCard(options, wrapper, page);   
    }, 1)
    frappe.breadcrumbs.add("Sample Register");

}

sample_register.JobCard = Class.extend({
    init: function(opts, wrapper,page) {
        $.extend(this, opts);
        this.make_filters(wrapper);
        this.prepare_data();
            this.page.main.find(".page").css({"padding-top": "0px"});
    //this.page.add_menu_item(__("Create Job"), function() {this.create_job();    }, true);
    },
    make_fun: function(){
            this.page.set_title(__("Dashboard") + " - " + __("Job Card Creation"));

     },
    make: function(){
        this._super();
        this.make_fun();
    },
    make_filters: function(wrapper){
        var me = this;
        this.page = wrapper.page;

        this.page.set_primary_action(__("Refresh"),
            function() { me.refresh(); }, "icon-refresh")

        this.department = this.page.add_field({fieldtype:"Link", label:"Sample Entry Register",
            fieldname:"sample_entry_register", options:"Sample"});
    },
    create_job: function(){
        frappe.msgprint("Creating job in JobCard")
     },

    filters: [

        //{fieldtype:"Link", label: __("Sample"),options:"Sample Entry Register"}
    ],

    setup_columns: function() {
        var std_columns = [
    {id: "check", name: "Check", field: "_check", width: 30, formatter: this.check_formatter},
    {id: "sample_id", name: "Sample Id", field: "sampleid"},
    {id: "customer", name: "Customer", field: "customer"},
    {id: "type", name: "Type", field: "type"},
    {id: "priority", name: "Priority", field: "priority"},
    {id: "standard", name: "Standard", field: "standard"},
    {id: "test_group", name: "Test Group", field: "test_group"}

        ];
        //this.make_date_range_columns();
        //this.columns = std_columns;
    },
    check_formatter: function(row, cell, value, columnDef, dataContext) {
        return repl('<input type="checkbox" data-id="%(id)s" \
            class="plot-check" %(checked)s>', {
                "id": dataContext.id,
                "checked": dataContext.checked ? 'checked="checked"' : ""
            })
    },
    refresh: function(){
        //this.check_mandatory_fields()
        var me = this;
        //this.waiting.toggle(true);
        msgprint("refresh clicked");
        msgprint(this.page.fields_dict.sample_entry_register.get_parsed_value())

    },

    prepare_data: function() {
        // add Opening, Closing, Totals rows
        // if filtered by account and / or voucher
        var me = this;
    //slick start
            function requiredFieldValidator(value) {
                if (value == null || value == undefined || !value.length) {
                    return {valid: false, msg: "This is a required field"};
                } else {
                    return {valid: true, msg: null};
                }
            }
    var grid;
    var sam="sam";
    var columns = [
    {id: "check", name: "Check", field: "check", width: 30, formatter: this.check_formatter},
    {id: "sample_id", name: "Sample Id", field: "sampleid"},
    {id: "customer", name: "Customer", field: "customer"},
    {id: "type", name: "Type", field: "type"},
    {id: "priority", name: "Priority", field: "priority"},
    {id: "standard", name: "Standard", field: "standard"},
    {id: "test_group", name: "Test Group", field: "test_group"}
  ];
  var options = {
    enableCellNavigation: true,
    enableColumnReorder: false
  };



          var data=[];
         frappe.call({
            method: "appname.module.page.dashboard.dashboard.get_sample_data",
            type: "GET",
            args: {
                args:{

                }
            },
            callback: function(r){
                if(r.message){
                    me.data = r.message;
                    //me.waiting.toggle(false);
                      $(function () {
                    var data = [];

                    for (var i = 0; i<r.message.get_sample_data.length; i++) {
                      data[i] = {
                          checked:false,
                        sampleid: r.message.get_sample_data[i][1],
                        customer: r.message.get_sample_data[i][2],
                        type: r.message.get_sample_data[i][3],
                        priority: 1,
                        standard: "1",
                        test_group: 1
                      };
                    }
                    grid = new Slick.Grid("#myGrid", data, columns, options);


                  })
                }
            }
        });

 //this.wrapper.find('[type="checkbox"]').attr(data-id, '3');
//$(".plot-check").hide()
  //slick end

   

        //this.data = [total_tickets, days_to_close, hours_to_close, hours_to_respond];
    },



});


python code to fetch data:
@frappe.whitelist()
def get_sample_data():
    return {
    "get_sample_data": frappe.db.sql("""select false, name, customer, type from `tabSample`  order by name""", as_list=1)
    }

Thursday, 26 November 2015

Solution similar to Select Serial Number in Delivery Note

Solution similar to Select Serial Number in Delivery Note:

1) create New Doctype
2) add custom button on New Doctype Table
3) write following script
4) it will filter test records for selcted group and you can add this test record into [New Doctype Table].[Field Name] (like serial number)


frappe.ui.form.on("DocType Item", "custom_button", function(frm, cdt, cdn) {
    var test_details = frappe.get_doc(cdt, cdn);
    var grid_row = cur_frm.open_grid_row();
    //if (job.item_code == "Artwork") {
    //  job.job_type="New";
    //  refresh_field("job_type", job.name, job.parentfield);
    //}
    var d = new frappe.ui.Dialog({
        title: __("Add Serial No"),
        fields: [
            {
                "fieldtype": "Link",
                "options": "Test Name",
                "label": __("Test Name"),
                "get_query": function () {
                    return {
                        filters: {
                            test_group:grid_row.doc.test_group
                        }
                    }
                }
            },
            {
                "fieldtype": "Button",
                "label": __("Add")
            }
        ]
    });

    d.get_input("add").on("click", function() {
        var test_name = d.get_value("test_name");
        if(test_name) {
            var val = (grid_row.doc.test || "").split("\n").concat([test_name]).join("\n");
            grid_row.fields_dict.test.set_model_value(val.trim());
        }
        d.hide();
        return false;
    });

    d.show();
//select test finish
})

Tuesday, 24 November 2015

check user role from python and client side script

To check user role from client side

@frappe.whitelist(allow_guest=True)
def validate_role(self, method):
        user="kolate.sambhaji@gmail.com"
        frappe.msgprint(_("In role validate function"))
        role_list = frappe.db.sql("""select name,owner,parent,idx,role from tabUserRole where parent=%s and role='Blogger'""",
                user)
        if len(role_list) > 0:
            frappe.msgprint("user is blogger")
        frappe.msgprint(role_list) #this will test user role blogger
This will print  -1 if user role Account Manager is not present
If user role Account Manager is present, then first msgprint will print value greater than one

To check user role from python
1) frappe.get_roles() will give you all roles of current  user

2) to check other user role
You can use following(python) code to check particular user roles.


@frappe.whitelist(allow_guest=True)
def validate_role(self, method):
        user="kolate.sambhaji@gmail.com"
        frappe.msgprint(_("In role validate function"))
        role_list = frappe.db.sql("""select name,owner,parent,idx,role from tabUserRole where parent=%s and role='Blogger'""",
                user)
        frappe.msgprint(role_list) #this will test user role blogger

Above script will check user role for 'kolate.sambhaji@gmail.com', you can pass any user id to check its roles.