Need help in Custom App and Custom Script

Hi Everyone,

I have some different setup of item groups and for that I need to generate item code for my defined group. I have seen the code of using case but that will not solve my purpose. What I will do is, the moment someone creates new item and clicks on the generate code button (custom button) in item code, I will show him the next item code to be created in that group.
For that I have done something with the help of my friend.

Custom Script:

frappe.ui.form.on("Item", "generate_code", function(frm, doctype, name) {
     frappe.model.open_mapped_doc({
            method: "library.item_script.generate_document",
            frm: cur_frm
        });
});  

Item_Script.Py:

@frappe.whitelist(allow_guest=True)
def generate_document(code):
    i=frappe.db.sql("""select item_code from tabItem where item_code like %s order by name desc limit 1""","010%")
    frappe.msgprint(i[0][0])

It is just for testing purpose it is not the actual code. Now the issue is if I go to an existing document and click on the button it gives me the code whereas if I goto create a new item code and click the button it give me message and my code fails there.
The message is:
You have unsaved changes in this form. Please save before you continue.

What I want is, I want to pass an item_code or group from the custom script and use the same in my item_script.py and on the basis of that I want to run my code in a new item form.
Can anybody help me?

frappe.model.open_mapped_doc is the wrong method to call.

use frappe.call search existing scripts for examples.