Merge branch 'master' of github.com:webnotes/erpnext

This commit is contained in:
Nabin Hait 2012-12-07 14:43:40 +05:30
commit 9b924ce695
30 changed files with 565 additions and 419 deletions

View File

@ -179,7 +179,7 @@ def import_vouchers(common_values, data, start_idx, import_type):
def get_common_values(rows):
start = False
common_values = webnotes.DictObj()
common_values = webnotes._dict()
for r in rows:
if start:
@ -200,7 +200,7 @@ def get_data(rows, company_abbr):
if r[0]:
if start_row and i >= start_row:
if not start_row_idx: start_row_idx = i
d, acc_dict = webnotes.DictObj(), webnotes.DictObj()
d, acc_dict = webnotes._dict(), webnotes._dict()
for cidx in xrange(len(columns)):
d[columns[cidx]] = r[cidx]

View File

@ -37,7 +37,7 @@ class TaxController(TransactionController):
{"parentfield": self.fmap.taxes_and_charges})
for base_tax in master_tax_list:
tax = DictObj([[field, base_tax.fields.get(field)]
tax = _dict([[field, base_tax.fields.get(field)]
for field in base_tax.fields
if field not in webnotes.model.default_fields])
tax.update({

View File

@ -17,7 +17,7 @@
from __future__ import unicode_literals
import webnotes
import webnotes.model
from webnotes import _, DictObj
from webnotes import _, _dict
from webnotes.utils import cint
import json
@ -32,7 +32,7 @@ class TransactionController(DocListController):
@property
def precision(self):
if not hasattr(self, "_precision"):
self._precision = DictObj()
self._precision = _dict()
self._precision.main = self.meta.get_precision_map()
self._precision.item = self.meta.get_precision_map(parentfield = \
self.item_table_field)
@ -69,7 +69,7 @@ class TransactionController(DocListController):
if not hasattr(self, "_fmap"):
if self.doc.doctype in ["Lead", "Quotation", "Sales Order", "Sales Invoice",
"Delivery Note"]:
self._fmap = webnotes.DictObj( {
self._fmap = webnotes._dict( {
"exchange_rate": "conversion_rate",
"taxes_and_charges": "other_charges",
"taxes_and_charges_master": "charge",
@ -93,7 +93,7 @@ class TransactionController(DocListController):
"cost_center": "cost_center_other_charges",
})
else:
self._fmap = webnotes.DictObj({
self._fmap = webnotes._dict({
"exchange_rate": "conversion_rate",
"taxes_and_charges": "purchase_tax_details",
"taxes_and_charges_master": "purchase_other_charges",
@ -120,4 +120,4 @@ class TransactionController(DocListController):
"rate": "rate"
})
return self._fmap or webnotes.DictObj()
return self._fmap or webnotes._dict()

View File

@ -52,13 +52,14 @@ cur_frm.cscript.refresh = function(doc,cdt,cdn){
if(doc.__islocal && !in_list(user_roles, "HR User")) {
cur_frm.set_intro("Fill the form and save it")
} else {
if(doc.approval_status=="Draft") {
if(doc.docstatus==0 && doc.approval_status=="Draft") {
if(user==doc.exp_approver) {
cur_frm.set_intro("You are the Expense Approver for this record. Please Update the 'Status' and Save");
cur_frm.toggle_enable("approval_status", true);
} else {
cur_frm.set_intro("Expense Claim is pending approval. Only the Expense Approver can update status.");
cur_frm.toggle_enable("approval_status", false);
if(!doc.__islocal) cur_frm.frm_head.appframe.buttons.Submit.toggle(false);
}
} else {
if(doc.approval_status=="Approved") {
@ -98,6 +99,9 @@ cur_frm.cscript.calculate_total_amount = function(doc,cdt,cdn){
}
cur_frm.cscript.claim_amount = function(doc,cdt,cdn){
cur_frm.cscript.calculate_total(doc,cdt,cdn);
var child = locals[cdt][cdn];
refresh_field("sanctioned_amount", child.name, child.parentfield);
}
cur_frm.cscript.sanctioned_amount = function(doc,cdt,cdn){
cur_frm.cscript.calculate_total(doc,cdt,cdn);

View File

@ -29,8 +29,8 @@ class DocType:
self.doclist = doclist
def validate(self):
if self.doc.exp_approver == self.doc.owner:
webnotes.msgprint("""Self Approval is not allowed.""", raise_exception=1)
# if self.doc.exp_approver == self.doc.owner:
# webnotes.msgprint("""Self Approval is not allowed.""", raise_exception=1)
self.validate_fiscal_year()
self.validate_exp_details()

View File

@ -4,7 +4,7 @@
"docstatus": 0,
"creation": "2012-12-05 16:53:59",
"modified_by": "Administrator",
"modified": "2012-12-06 17:34:37"
"modified": "2012-12-07 13:25:44"
},
{
"is_submittable": 1,
@ -34,14 +34,6 @@
"name": "Expense Claim",
"doctype": "DocType"
},
{
"oldfieldtype": "Section Break",
"doctype": "DocField",
"label": "Details",
"fieldname": "details",
"fieldtype": "Section Break",
"permlevel": 0
},
{
"permlevel": 0,
"no_copy": 1,
@ -67,17 +59,6 @@
"fieldtype": "Select",
"permlevel": 0
},
{
"oldfieldtype": "Date",
"doctype": "DocField",
"label": "Posting Date",
"oldfieldname": "posting_date",
"fieldname": "posting_date",
"fieldtype": "Date",
"reqd": 1,
"permlevel": 0,
"in_filter": 1
},
{
"oldfieldtype": "Column Break",
"doctype": "DocField",
@ -87,17 +68,70 @@
"permlevel": 0
},
{
"reqd": 0,
"no_copy": 1,
"oldfieldtype": "Currency",
"colour": "White:FFF",
"doctype": "DocField",
"label": "Total Claimed Amount",
"oldfieldname": "total_claimed_amount",
"width": "160px",
"fieldname": "total_claimed_amount",
"fieldtype": "Currency",
"permlevel": 1,
"in_filter": 0
},
{
"no_copy": 1,
"oldfieldtype": "Currency",
"colour": "White:FFF",
"doctype": "DocField",
"label": "Total Sanctioned Amount",
"oldfieldname": "total_sanctioned_amount",
"width": "160px",
"fieldname": "total_sanctioned_amount",
"fieldtype": "Currency",
"permlevel": 1,
"in_filter": 0
},
{
"oldfieldtype": "Section Break",
"doctype": "DocField",
"label": "Expense Details",
"fieldname": "expense_details",
"fieldtype": "Section Break",
"permlevel": 0
},
{
"oldfieldtype": "Table",
"allow_on_submit": 0,
"doctype": "DocField",
"label": "Expense Claim Details",
"oldfieldname": "expense_voucher_details",
"options": "Expense Claim Detail",
"fieldname": "expense_voucher_details",
"fieldtype": "Table",
"permlevel": 0
},
{
"doctype": "DocField",
"options": "Simple",
"fieldname": "sb1",
"fieldtype": "Section Break",
"permlevel": 0
},
{
"permlevel": 0,
"oldfieldtype": "Link",
"colour": "White:FFF",
"doctype": "DocField",
"label": "From Employee",
"oldfieldname": "employee",
"permlevel": 0,
"reqd": 1,
"trigger": "Client",
"fieldname": "employee",
"fieldtype": "Link",
"search_index": 1,
"reqd": 1,
"options": "Employee",
"in_filter": 1
},
@ -114,10 +148,51 @@
"in_filter": 1
},
{
"oldfieldtype": "Select",
"doctype": "DocField",
"label": "Fiscal Year",
"oldfieldname": "fiscal_year",
"options": "link:Fiscal Year",
"fieldname": "fiscal_year",
"fieldtype": "Select",
"reqd": 1,
"permlevel": 0,
"in_filter": 1
},
{
"oldfieldtype": "Link",
"doctype": "DocField",
"label": "Company",
"oldfieldname": "company",
"options": "link:Company",
"fieldname": "company",
"fieldtype": "Select",
"reqd": 1,
"permlevel": 0,
"in_filter": 1
},
{
"doctype": "DocField",
"fieldname": "cb1",
"fieldtype": "Column Break",
"permlevel": 0
},
{
"oldfieldtype": "Date",
"doctype": "DocField",
"label": "Posting Date",
"oldfieldname": "posting_date",
"fieldname": "posting_date",
"fieldtype": "Date",
"reqd": 1,
"permlevel": 0,
"in_filter": 1
},
{
"allow_on_submit": 0,
"no_copy": 1,
"oldfieldtype": "Small Text",
"colour": "White:FFF",
"allow_on_submit": 0,
"doctype": "DocField",
"label": "Remark",
"oldfieldname": "remark",
@ -125,6 +200,17 @@
"fieldtype": "Small Text",
"permlevel": 0
},
{
"print_hide": 1,
"oldfieldtype": "Data",
"doctype": "DocField",
"label": "Employees Email Id",
"oldfieldname": "email_id",
"fieldname": "email_id",
"fieldtype": "Data",
"hidden": 1,
"permlevel": 0
},
{
"print_hide": 1,
"no_copy": 1,
@ -153,87 +239,6 @@
"permlevel": 1,
"report_hide": 1
},
{
"oldfieldtype": "Section Break",
"doctype": "DocField",
"label": "Expense Details",
"fieldname": "expense_details",
"fieldtype": "Section Break",
"permlevel": 0
},
{
"oldfieldtype": "Table",
"allow_on_submit": 0,
"doctype": "DocField",
"label": "Expense Claim Details",
"oldfieldname": "expense_voucher_details",
"options": "Expense Claim Detail",
"fieldname": "expense_voucher_details",
"fieldtype": "Table",
"permlevel": 0
},
{
"no_copy": 1,
"oldfieldtype": "Currency",
"colour": "White:FFF",
"doctype": "DocField",
"label": "Total Claimed Amount",
"oldfieldname": "total_claimed_amount",
"width": "160px",
"fieldname": "total_claimed_amount",
"fieldtype": "Currency",
"reqd": 0,
"permlevel": 1,
"in_filter": 0
},
{
"no_copy": 1,
"oldfieldtype": "Currency",
"colour": "White:FFF",
"doctype": "DocField",
"label": "Total Sanctioned Amount",
"oldfieldname": "total_sanctioned_amount",
"width": "160px",
"fieldname": "total_sanctioned_amount",
"fieldtype": "Currency",
"permlevel": 1,
"in_filter": 0
},
{
"print_hide": 1,
"oldfieldtype": "Data",
"doctype": "DocField",
"label": "Employees Email Id",
"oldfieldname": "email_id",
"fieldname": "email_id",
"fieldtype": "Data",
"hidden": 1,
"permlevel": 0
},
{
"oldfieldtype": "Select",
"doctype": "DocField",
"label": "Fiscal Year",
"oldfieldname": "fiscal_year",
"options": "link:Fiscal Year",
"fieldname": "fiscal_year",
"fieldtype": "Select",
"reqd": 1,
"permlevel": 0,
"in_filter": 1
},
{
"oldfieldtype": "Link",
"doctype": "DocField",
"label": "Company",
"oldfieldname": "company",
"options": "link:Company",
"fieldname": "company",
"fieldtype": "Select",
"reqd": 1,
"permlevel": 0,
"in_filter": 1
},
{
"create": 1,
"doctype": "DocPerm",

View File

@ -19,27 +19,34 @@ cur_frm.add_fetch('employee','employee_name','employee_name');
cur_frm.cscript.onload = function(doc, dt, dn) {
if(!doc.posting_date)
set_multiple(dt,dn,{posting_date:get_today()});
if(doc.__islocal) {
cur_frm.set_value("status", "Open")
}
cur_frm.call({
method:"get_approver_list",
callback: function(r) {
cur_frm.set_df_property("leave_approver", "options", r.message);
get_leave_balance(cur_frm.doc);
cur_frm.cscript.get_leave_balance(cur_frm.doc);
}
});
}
cur_frm.cscript.refresh = function(doc, dt, dn) {
if(doc.__islocal) {
cur_frm.set_value("status", "Open")
}
cur_frm.set_intro("");
if(doc.__islocal && !in_list(user_roles, "HR User")) {
cur_frm.set_intro("Fill the form and save it")
} else {
if(doc.status=="Open") {
if(doc.docstatus==0 && doc.status=="Open") {
if(user==doc.leave_approver) {
cur_frm.set_intro("You are the Leave Approver for this record. Please Update the 'Status' and Save");
cur_frm.toggle_enable("status", true);
} else {
cur_frm.set_intro("This Leave Application is pending approval. Only the Leave Apporver can update status.")
cur_frm.toggle_enable("status", false);
if(!doc.__islocal) cur_frm.frm_head.appframe.buttons.Submit.toggle(false);
}
} else {
if(doc.status=="Approved") {
@ -56,21 +63,21 @@ cur_frm.cscript.refresh = function(doc, dt, dn) {
}
cur_frm.cscript.employee = function (doc, dt, dn){
get_leave_balance(doc, dt, dn);
cur_frm.cscript.get_leave_balance(doc, dt, dn);
}
cur_frm.cscript.fiscal_year = function (doc, dt, dn){
get_leave_balance(doc, dt, dn);
cur_frm.cscript.get_leave_balance(doc, dt, dn);
}
cur_frm.cscript.leave_type = function (doc, dt, dn){
get_leave_balance(doc, dt, dn);
cur_frm.cscript.get_leave_balance(doc, dt, dn);
}
cur_frm.cscript.half_day = function(doc, dt, dn) {
if(doc.from_date) {
set_multiple(dt,dn,{to_date:doc.from_date});
calculate_total_days(doc, dt, dn);
cur_frm.cscript.calculate_total_days(doc, dt, dn);
}
}
@ -78,7 +85,7 @@ cur_frm.cscript.from_date = function(doc, dt, dn) {
if(cint(doc.half_day) == 1){
set_multiple(dt,dn,{to_date:doc.from_date});
}
calculate_total_days(doc, dt, dn);
cur_frm.cscript.calculate_total_days(doc, dt, dn);
}
cur_frm.cscript.to_date = function(doc, dt, dn) {
@ -86,11 +93,11 @@ cur_frm.cscript.to_date = function(doc, dt, dn) {
msgprint("To Date should be same as From Date for Half Day leave");
set_multiple(dt,dn,{to_date:doc.from_date});
}
calculate_total_days(doc, dt, dn);
cur_frm.cscript.calculate_total_days(doc, dt, dn);
}
get_leave_balance = function(doc, dt, dn) {
if(doc.employee && doc.leave_type && doc.fiscal_year) {
cur_frm.cscript.get_leave_balance = function(doc, dt, dn) {
if(doc.docstatus==0 && doc.employee && doc.leave_type && doc.fiscal_year) {
cur_frm.call({
method: "get_leave_balance",
args: {
@ -98,16 +105,15 @@ get_leave_balance = function(doc, dt, dn) {
fiscal_year: doc.fiscal_year,
leave_type: doc.leave_type
}
})
});
}
}
calculate_total_days = function(doc, dt, dn) {
cur_frm.cscript.calculate_total_days = function(doc, dt, dn) {
if(doc.from_date && doc.to_date){
if(cint(doc.half_day) == 1) set_multiple(dt,dn,{total_leave_days:0.5});
else{
//d = new DateFn();
//set_multiple(dt,dn,{total_leave_days:d.get_diff(d.str_to_obj(doc.to_date),d.str_to_obj(doc.from_date))+1});
// server call is done to include holidays in leave days calculations
get_server_fields('get_total_leave_days', '', '', doc, dt, dn, 1);
}
}

View File

@ -28,7 +28,21 @@ import datetime
class DocType:
def __init__(self, doc, doclist):
self.doc = doc
self.doclist = doclist
self.doclist = doclist
def validate(self):
# if self.doc.leave_approver == self.doc.owner:
# webnotes.msgprint("""Self Approval is not allowed.""", raise_exception=1)
self.validate_to_date()
self.validate_balance_leaves()
self.validate_leave_overlap()
self.validate_max_days()
def on_submit(self):
if self.doc.status != "Approved":
webnotes.msgprint("""Only Approved Leave Applications can be Submitted.""",
raise_exception=True)
def get_holidays(self):
"""
@ -40,9 +54,7 @@ class DocType:
return tot_hol and flt(tot_hol[0][0]) or 0
def get_total_leave_days(self):
"""
Calculates total leave days based on input and holidays
"""
"""Calculates total leave days based on input and holidays"""
ret = {'total_leave_days' : 0.5}
if not self.doc.half_day:
tot_days = date_diff(self.doc.to_date, self.doc.from_date) + 1
@ -53,24 +65,20 @@ class DocType:
return ret
def validate_to_date(self):
if self.doc.from_date and self.doc.to_date and (getdate(self.doc.to_date) < getdate(self.doc.from_date)):
if self.doc.from_date and self.doc.to_date and \
(getdate(self.doc.to_date) < getdate(self.doc.from_date)):
msgprint("To date cannot be before from date")
raise Exception
def is_lwp(self):
lwp = sql("select is_lwp from `tabLeave Type` where name = %s", self.doc.leave_type)
return lwp and cint(lwp[0][0]) or 0
def validate_balance_leaves(self):
if self.doc.from_date and self.doc.to_date and not self.is_lwp():
bal = get_leave_balance(self.doc.leave_type, self.doc.employee,
self.doc.fiscal_year)
tot_leaves = self.get_total_leave_days()
bal, tot_leaves = bal, tot_leaves
webnotes.conn.set(self.doc, 'leave_balance', flt(bal['leave_balance']))
webnotes.conn.set(self.doc, 'total_leave_days', flt(tot_leaves['total_leave_days']))
if flt(bal['leave_balance']) < flt(tot_leaves['total_leave_days']):
msgprint("Warning : There is not enough leave balance")
if self.doc.from_date and self.doc.to_date and not is_lwp(self.doc.leave_type):
self.doc.leave_balance = get_leave_balance(self.doc.employee,
self.doc.leave_type, self.doc.fiscal_year)["leave_balance"]
self.doc.total_leave_days = self.get_total_leave_days()["total_leave_days"]
if self.doc.leave_balance - self.doc.total_leave_days < 0:
msgprint("There is not enough leave balance for Leave Type: %s" % \
(self.doc.leave_type,), raise_exception=1)
def validate_leave_overlap(self):
for d in sql("""select name, leave_type, posting_date, from_date, to_date
@ -90,36 +98,23 @@ class DocType:
msgprint("Sorry ! You cannot apply for %s for more than %s days" % (self.doc.leave_type, max_days))
raise Exception
def validate(self):
if self.doc.leave_approver == self.doc.owner:
webnotes.msgprint("""Self Approval is not allowed.""", raise_exception=1)
self.validate_to_date()
self.validate_balance_leaves()
self.validate_leave_overlap()
self.validate_max_days()
def on_submit(self):
if self.doc.status != "Approved":
webnotes.msgprint("""Only Approved Leave Applications can be Submitted.""",
raise_exception=True)
@webnotes.whitelist()
def get_leave_balance(employee, leave_type, fiscal_year):
leave_all = webnotes.conn.sql("""select total_leaves_allocated
from `tabLeave Allocation` where employee = %s and leave_type = %s
and fiscal_year = %s and docstatus = 1""", (employee,
leave_type, fiscal_year))
leave_type, fiscal_year), debug=1)
leave_all = leave_all and flt(leave_all[0][0]) or 0
leave_app = webnotes.conn.sql("""select SUM(total_leave_days)
from `tabLeave Application`
where employee = %s and leave_type = %s and fiscal_year = %s
and docstatus = 1""", (employee, leave_type, fiscal_year))
and docstatus = 1""", (employee, leave_type, fiscal_year), debug=1)
leave_app = leave_app and flt(leave_app[0][0]) or 0
ret = {'leave_balance':leave_all - leave_app}
ret = {'leave_balance': leave_all - leave_app}
return ret
@webnotes.whitelist()
@ -130,3 +125,7 @@ def get_approver_list():
webnotes.msgprint("No Leave Approvers. Please assign 'Leave Approver' Role to atleast one user.")
return roles
def is_lwp(leave_type):
lwp = sql("select is_lwp from `tabLeave Type` where name = %s", leave_type)
return lwp and cint(lwp[0][0]) or 0

View File

@ -2,9 +2,9 @@
{
"owner": "Administrator",
"docstatus": 0,
"creation": "2012-12-05 14:11:53",
"creation": "2012-12-07 11:51:20",
"modified_by": "Administrator",
"modified": "2012-12-05 17:38:26"
"modified": "2012-12-07 13:31:40"
},
{
"is_submittable": 1,
@ -39,10 +39,11 @@
"colour": "White:FFF",
"doctype": "DocField",
"label": "Status",
"no_copy": 1,
"options": "Open\nApproved\nRejected",
"fieldname": "status",
"fieldtype": "Select",
"permlevel": 3
"permlevel": 2
},
{
"description": "Leave can be approved by users with Role, \"Leave Approver\"",
@ -57,7 +58,7 @@
"search_index": 1,
"doctype": "DocField",
"label": "Leave Type",
"options": "link:Leave Type",
"options": "\nCasual Leave",
"fieldname": "leave_type",
"fieldtype": "Select",
"reqd": 1,
@ -104,17 +105,10 @@
},
{
"doctype": "DocField",
"label": "Leave Balance",
"fieldname": "leave_balance",
"fieldtype": "Currency",
"permlevel": 1
},
{
"doctype": "DocField",
"label": "Total Leave Days",
"fieldname": "total_leave_days",
"fieldtype": "Currency",
"permlevel": 1
"label": "Reason",
"fieldname": "description",
"fieldtype": "Small Text",
"permlevel": 0
},
{
"search_index": 1,
@ -137,26 +131,28 @@
"in_filter": 1
},
{
"no_copy": 1,
"doctype": "DocField",
"label": "Leave Balance Before Application",
"fieldname": "leave_balance",
"fieldtype": "Currency",
"permlevel": 1
},
{
"no_copy": 1,
"doctype": "DocField",
"label": "Total Leave Days",
"fieldname": "total_leave_days",
"fieldtype": "Currency",
"permlevel": 1
},
{
"doctype": "DocField",
"label": "More Info",
"fieldname": "sb10",
"fieldtype": "Section Break",
"permlevel": 0
},
{
"doctype": "DocField",
"label": "Reason",
"width": "300px",
"fieldname": "description",
"fieldtype": "Text Editor",
"permlevel": 0
},
{
"doctype": "DocField",
"label": "HR Details",
"fieldname": "sb12",
"fieldtype": "Section Break",
"permlevel": 2
},
{
"default": "Today",
"colour": "White:FFF",
@ -172,7 +168,7 @@
"search_index": 0,
"doctype": "DocField",
"label": "Fiscal Year",
"options": "link:Fiscal Year",
"options": "\n2008-2009\n2009-2010\n2010-2011\n2011-2012\n2012-2013\n2013-2014",
"fieldname": "fiscal_year",
"fieldtype": "Select",
"reqd": 1,
@ -180,6 +176,7 @@
"in_filter": 1
},
{
"print_hide": 1,
"doctype": "DocField",
"label": "Letter Head",
"options": "Letter Head",
@ -250,10 +247,5 @@
"role": "Leave Approver",
"cancel": 0,
"permlevel": 2
},
{
"doctype": "DocPerm",
"role": "All",
"permlevel": 3
}
]

View File

@ -0,0 +1,20 @@
[
{
"owner": "Administrator",
"docstatus": 0,
"creation": "2012-12-07 10:14:13",
"modified_by": "Administrator",
"modified": "2012-12-07 10:14:31"
},
{
"name": "__common__",
"ref_doctype": "Sales Order",
"doctype": "Report",
"is_standard": "Yes",
"query": "select \n `tabSales Order`.`name` as \"S.O. No.:Link/Sales Order:120\",\n `tabSales Order`.`transaction_date` as \"S.O. Date\",\n `tabSales Order`.`delivery_date` as \"Expected Delivery Date\",\n `tabSales Order`.`customer` as \"Customer:Link/Customer:120\",\n `tabSales Order Item`.item_code as \"Item Code:Link/Item:120\",\n `tabSales Order Item`.description as \"Description\",\n `tabSales Order Item`.qty as \"Qty:Float\",\n `tabSales Order Item`.delivered_qty as \"Delivered Qty:Float\",\n `tabSales Order`.`po_no` as \"P.O. No.\"\nfrom\n `tabSales Order`, `tabSales Order Item`\nwhere\n `tabSales Order Item`.`parent` = `tabSales Order`.`name`\n and `tabSales Order`.docstatus = 1\n and ifnull(`tabSales Order Item`.delivered_qty,0) < ifnull(`tabSales Order Item`.qty,0)\norder by `tabSales Order`.transaction_date asc"
},
{
"name": "Sales Orders Pending To Be Delivered",
"doctype": "Report"
}
]

View File

@ -25,7 +25,7 @@ from webnotes import msgprint
sql = webnotes.conn.sql
class DocType():
class DocType:
def __init__(self, doc, doclist=[]):
self.doc = doc
self.doclist = doclist
@ -38,9 +38,10 @@ class DocType():
return ret
def on_update(self):
# webpage updates
from website.utils import update_page_name
update_page_name(self.doc, self.doc.item_name)
if self.doc.show_in_website:
# webpage updates
from website.utils import update_page_name
update_page_name(self.doc, self.doc.item_name)
bin = sql("select stock_uom from `tabBin` where item_code = '%s' " % self.doc.item_code)
if bin and cstr(bin[0][0]) != cstr(self.doc.stock_uom):
@ -80,8 +81,10 @@ class DocType():
sql("""delete from `tabStock Ledger Entry`
where item_code=%s and is_cancelled='Yes' """, self.doc.item_code)
self.delete_web_cache(self.doc.page_name)
if self.doc.page_name:
from website.utils import clear_cache
clear_cache(self.doc.page_name)
# Check whether Ref Rate is not entered twice for same Price List and Currency
def check_ref_rate_detail(self):
check_list=[]
@ -192,6 +195,9 @@ class DocType():
def on_rename(self,newdn,olddn):
sql("update tabItem set item_code = %s where name = %s", (newdn, olddn))
if self.doc.page_name:
from website.utils import clear_cache
clear_cache(self.doc.page_name)
def prepare_template_args(self):
self.doc.web_description_html = self.doc.description or ''

View File

@ -19,7 +19,7 @@ from __future__ import unicode_literals
import webnotes
import website.utils
class DocType():
class DocType:
def __init__(self, d, dl):
self.doc, self.doclist = d, dl

View File

@ -45,6 +45,5 @@ class DocType:
def on_update(self):
"""rebuild pages"""
from webnotes.cms.make import make_web_core
make_web_core()
from website.helpers.make_web_include_files import make
make()

View File

@ -36,7 +36,7 @@ class DocType():
from webnotes.sessions import clear_cache
clear_cache('Guest')
from website.web_cache import clear_cache
from website.utils import clear_cache
clear_cache(self.doc.page_name)
clear_cache('index')

View File

@ -24,11 +24,11 @@ class DocType:
def on_update(self):
# make js and css
from webnotes.cms.make import make_web_core
make_web_core()
from website.helpers.make_web_include_files import make
make()
# clear web cache (for menus!)
from website.web_cache import clear_cache
from website.utils import clear_cache
clear_cache()
from webnotes.sessions import clear_cache

View File

View File

@ -1,3 +1,6 @@
# Copyright (c) 2012 Web Notes Technologies Pvt Ltd.
# License: GNU General Public License (v3). For more information see license.txt
from __future__ import unicode_literals
import webnotes
@ -17,10 +20,10 @@ def get_blog_list(args=None):
select
name, content, owner, creation as creation,
title, (select count(name) from `tabComment` where
comment_doctype='Blog' and comment_docname=name) as comments
comment_doctype='Blog' and comment_docname=`tabBlog`.name) as comments
from `tabBlog`
where ifnull(published,0)=1
order by published desc, name asc"""
order by creation desc, name asc"""
from webnotes.widgets.query_builder import add_limit_to_query
query, args = add_limit_to_query(query, args)
@ -29,14 +32,13 @@ def get_blog_list(args=None):
# strip html tags from content
import webnotes.utils
import website.web_cache
for res in result:
from webnotes.utils import global_date_format, get_fullname
res['full_name'] = get_fullname(res['owner'])
res['published'] = global_date_format(res['creation'])
if not res['content']:
res['content'] = website.web_cache.get_html(res['name'])
res['content'] = website.utils.get_html(res['name'])
res['content'] = split_blog_content(res['content'])
res['content'] = res['content'][:1000]
@ -88,7 +90,6 @@ def add_comment(args=None):
import webnotes
import webnotes.utils, markdown2
import webnotes.widgets.form.comments
import website.web_cache
if not args: args = webnotes.form_dict
args['comment'] = unicode(markdown2.markdown(args.get('comment') or ''))
@ -96,15 +97,13 @@ def add_comment(args=None):
comment = webnotes.widgets.form.comments.add_comment(args)
# since comments are embedded in the page, clear the web cache
website.web_cache.clear_cache(args.get('page_name'),
args.get('comment_doctype'), args.get('comment_docname'))
website.utils.clear_cache(args.get('page_name'))
comment['comment_date'] = webnotes.utils.global_date_format(comment['creation'])
template_args = { 'comment_list': [comment], 'template': 'html/comment.html' }
# get html of comment row
comment_html = website.web_cache.build_html(template_args)
comment_html = website.utils.build_html(template_args)
# notify commentors
commentors = [d[0] for d in webnotes.conn.sql("""select comment_by from tabComment where
@ -144,8 +143,8 @@ def add_subscriber():
lead.save()
def get_blog_content(blog_page_name):
import website.web_cache
content = website.web_cache.get_html(blog_page_name)
import website.utils
content = website.utils.get_html(blog_page_name)
content = split_blog_content(content)
import webnotes.utils
content = webnotes.utils.escape_html(content)

View File

@ -0,0 +1,79 @@
# Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
#
# MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
from __future__ import unicode_literals
"""
Generate RSS feed for blog
"""
rss = u"""<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
<title>%(title)s</title>
<description>%(description)s</description>
<link>%(link)s</link>
<lastBuildDate>%(modified)s</lastBuildDate>
<pubDate>%(modified)s</pubDate>
<ttl>1800</ttl>
%(items)s
</channel>
</rss>"""
rss_item = u"""
<item>
<title>%(title)s</title>
<description>%(content)s</description>
<link>%(link)s</link>
<guid>%(name)s</guid>
<pubDate>%(creation)s</pubDate>
</item>"""
def generate():
"""generate rss feed"""
import webnotes, os
from webnotes.model.doc import Document
from website.helpers.blog import get_blog_content
host = (os.environ.get('HTTPS') and 'https://' or 'http://') + os.environ.get('HTTP_HOST')
items = ''
blog_list = webnotes.conn.sql("""\
select page_name as name, modified, creation, title from tabBlog
where ifnull(published,0)=1
order by creation desc, modified desc, name asc limit 100""", as_dict=1)
for blog in blog_list:
blog.link = host + '/' + blog.name + '.html'
blog.content = get_blog_content(blog.name)
items += rss_item % blog
modified = max((blog['modified'] for blog in blog_list))
ws = Document('Website Settings', 'Website Settings')
return (rss % {
'title': ws.title_prefix,
'description': ws.description or (ws.title_prefix + ' Blog'),
'modified': modified,
'items': items,
'link': host + '/blog.html'
}).encode('utf-8', 'ignore')

View File

@ -0,0 +1,32 @@
# Copyright (c) 2012 Web Notes Technologies Pvt Ltd.
# License: GNU General Public License (v3). For more information see license.txt
def make():
import os
import webnotes
import website.utils
import startup.event_handlers
if not webnotes.conn:
webnotes.connect()
home_page = website.utils.get_home_page()
fname = 'js/wn-web.js'
if os.path.basename(os.path.abspath('.'))!='public':
fname = os.path.join('public', fname)
if hasattr(startup.event_handlers, 'get_web_script'):
with open(fname, 'w') as f:
script = 'window.home_page = "%s";\n' % home_page
script += startup.event_handlers.get_web_script()
f.write(script)
fname = 'css/wn-web.css'
if os.path.basename(os.path.abspath('.'))!='public':
fname = os.path.join('public', fname)
# style - wn.css
if hasattr(startup.event_handlers, 'get_web_style'):
with open(fname, 'w') as f:
f.write(startup.event_handlers.get_web_style())

View File

@ -1,3 +1,6 @@
# Copyright (c) 2012 Web Notes Technologies Pvt Ltd.
# License: GNU General Public License (v3). For more information see license.txt
from __future__ import unicode_literals
import webnotes

View File

@ -0,0 +1,38 @@
# Copyright (c) 2012 Web Notes Technologies Pvt Ltd.
# License: GNU General Public License (v3). For more information see license.txt
from __future__ import unicode_literals
frame_xml = """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">%s
</urlset>"""
link_xml = """\n<url><loc>%s</loc><lastmod>%s</lastmod></url>"""
# generate the sitemap XML
def generate(domain):
global frame_xml, link_xml
import urllib, os
import webnotes
import website.utils
# settings
max_doctypes = 10
max_items = 1000
site_map = ''
page_list = []
if domain:
# list of all pages in web cache
for doctype in website.utils.page_map:
d = website.utils.page_map[doctype];
pages = webnotes.conn.sql("""select page_name, `modified`
from `tab%s` where ifnull(%s,0)=1
order by modified desc""" % (doctype, d.condition_field))
for p in pages:
page_url = os.path.join(domain, urllib.quote(p[0]) + '.html')
modified = p[1].strftime('%Y-%m-%d')
site_map += link_xml % (page_url, modified)
return frame_xml % site_map

View File

@ -18,7 +18,7 @@
wn.pages['{{ name }}'].onload = function(wrapper) {
erpnext.blog_list = new wn.ui.Listing({
parent: $(wrapper).find('#blog-list').get(0),
method: 'website.blog.get_blog_list',
method: 'website.helpers.blog.get_blog_list',
hide_refresh: true,
no_toolbar: true,
render_row: function(parent, data) {

View File

@ -52,7 +52,7 @@ erpnext.blog.render_recent_list = function(wrapper) {
wrapper.recent_list = new wn.ui.Listing({
parent: $(wrapper).find('.recent-posts'),
no_toolbar: true,
method: 'website.blog.get_recent_blog_list',
method: 'website.helpers.blog.get_recent_blog_list',
get_args: function() {
return { name: '{{ name }}' }
},
@ -139,7 +139,7 @@ erpnext.blog.add_comment = function(wrapper) {
args.page_name = '{{ page_name }}';
wn.call({
method: 'website.blog.add_comment',
method: 'website.helpers.blog.add_comment',
args: args,
btn: this,
callback: function(r) {

View File

@ -15,7 +15,7 @@ wn.provide('erpnext.blog');
var args = d.get_values();
if(!args) return;
wn.call({
method: 'website.blog.add_subscriber',
method: 'website.helpers.blog.add_subscriber',
args: args,
callback: function(r) {
if(r.exc) {

View File

@ -6,7 +6,7 @@ erpnext.products.make_product_categories = function(wrapper) {
wrapper.category_list = new wn.ui.Listing({
parent: $(wrapper).find('.more-categories').get(0),
method: 'website.product.get_product_category_list',
method: 'website.helpers.product.get_product_category_list',
hide_refresh: true,
render_row: function(parent, data) {
parent.innerHTML = repl(

View File

@ -53,7 +53,7 @@ erpnext.products.make_similar_products = function(wrapper) {
parent: $(wrapper).find('.similar-products').get(0),
hide_refresh: true,
page_length: 5,
method: 'website.product.get_similar_product_list',
method: 'website.helpers.product.get_similar_product_list',
get_args: function() {
return {
product_group: wrapper.product_group,

View File

@ -45,7 +45,7 @@ erpnext.products.make_product_list = function(wrapper) {
parent: $(wrapper).find('#products-list').get(0),
run_btn: $(wrapper).find('.products-search .btn').get(0),
no_toolbar: true,
method: 'website.product.get_product_list',
method: 'website.helpers.product.get_product_list',
get_args: function() {
return {
search: $('input[name="products-search"]').val() || '',

View File

@ -15,7 +15,26 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
import os
import conf
import webnotes
from webnotes.utils import cstr
page_map = {
'Web Page': webnotes._dict({
"template": 'html/web_page.html',
"condition_field": "published"
}),
'Blog': webnotes._dict({
"template": 'html/blog_page.html',
"condition_field": "published",
}),
'Item': webnotes._dict({
"template": 'html/product_page.html',
"condition_field": "show_in_website",
})
}
def render(page_name):
"""render html page"""
@ -36,8 +55,21 @@ def get_html(page_name):
page_name = scrub_page_name(page_name)
comments = get_comments(page_name)
from website.web_cache import get_page_html
html = get_page_html(page_name, comments)
html = ''
# load from cache, if auto cache clear is falsy
if not (hasattr(conf, 'auto_cache_clear') and conf.auto_cache_clear or 0):
html = webnotes.cache().get_value("page:" + page_name)
if html:
comments += "\nload status: cache"
else:
html = load_into_cache(page_name)
comments += "\nload status: fresh"
# insert comments
html += """\n<!-- %s -->""" % webnotes.utils.cstr(comments)
return html
def get_comments(page_name):
@ -54,16 +86,6 @@ def scrub_page_name(page_name):
return page_name
def make_template(doc, path, convert_fields = ['main_section', 'side_section']):
"""make template"""
import os, jinja2
# write template
with open(path, 'r') as f:
temp = jinja2.Template(f.read())
return temp.render(doc = doc.fields)
def page_name(title):
"""make page name from title"""
import re
@ -83,3 +105,119 @@ def update_page_name(doc, title):
webnotes.msgprint("""A %s with the same title already exists.
Please change the title of %s and save again."""
% (doc.doctype, doc.name), raise_exception=1)
delete_page_cache(doc.page_name)
def load_into_cache(page_name):
args = prepare_args(page_name)
html = build_html(args)
webnotes.cache().set_value("page:" + page_name, html)
return html
def build_html(args):
from jinja2 import Environment, FileSystemLoader
templates_path = os.path.join(os.path.dirname(conf.__file__),
'app', 'website', 'templates')
jenv = Environment(loader = FileSystemLoader(templates_path))
html = jenv.get_template(args['template']).render(args)
return html
def prepare_args(page_name):
if page_name == 'index':
page_name = get_home_page()
if page_name in get_template_pages():
args = {
'template': 'pages/%s.html' % page_name,
'name': page_name,
}
else:
args = get_doc_fields(page_name)
args.update(get_outer_env())
return args
def get_template_pages():
pages_path = os.path.join(os.path.dirname(conf.__file__), 'app',
'website', 'templates', 'pages')
page_list = []
for page in os.listdir(pages_path):
page_list.append(scrub_page_name(page))
return page_list
def get_doc_fields(page_name):
doc_type, doc_name = get_source_doc(page_name)
obj = webnotes.get_obj(doc_type, doc_name)
if hasattr(obj, 'prepare_template_args'):
obj.prepare_template_args()
args = obj.doc.fields
args['template'] = page_map[doc_type].template
return args
def get_source_doc(page_name):
"""get source doc for the given page name"""
for doctype in page_map:
name = webnotes.conn.sql("""select name from `tab%s` where
page_name=%s and ifnull(%s, 0)=1""" % (doctype, "%s",
page_map[doctype].condition_field), page_name)
if name:
return doctype, name[0][0]
return None, None
def get_outer_env():
all_top_items = webnotes.conn.sql("""\
select * from `tabTop Bar Item`
where parent='Website Settings' and parentfield='top_bar_items'
order by idx asc""", as_dict=1)
top_items = [d for d in all_top_items if not d['parent_label']]
# attach child items to top bar
for d in all_top_items:
if d['parent_label']:
for t in top_items:
if t['label']==d['parent_label']:
if not 'child_items' in t:
t['child_items'] = []
t['child_items'].append(d)
break
return {
'top_bar_items': top_items,
'footer_items': webnotes.conn.sql("""\
select * from `tabTop Bar Item`
where parent='Website Settings' and parentfield='footer_items'
order by idx asc""", as_dict=1),
'brand': webnotes.conn.get_value('Website Settings', None, 'brand_html') or 'ERPNext',
'copyright': webnotes.conn.get_value('Website Settings', None, 'copyright'),
'favicon': webnotes.conn.get_value('Website Settings', None, 'favicon')
}
def get_home_page():
doc_name = webnotes.conn.get_value('Website Settings', None, 'home_page')
if doc_name:
page_name = webnotes.conn.get_value('Web Page', doc_name, 'page_name')
else:
page_name = 'login'
return page_name
def clear_cache(page_name=None):
if page_name:
delete_page_cache(page_name)
else:
webnotes.cache().delete_keys("page:")
def delete_page_cache(page_name):
webnotes.cache().delete_value("page:" + page_name)

View File

@ -1,174 +0,0 @@
# ERPNext - web based ERP (http://erpnext.com)
# Copyright (C) 2012 Web Notes Technologies Pvt Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# html generation functions
from __future__ import unicode_literals
import os
import conf
import webnotes
import website.utils
from webnotes.utils import cstr
template_map = {
'Web Page': 'html/web_page.html',
'Blog': 'html/blog_page.html',
'Item': 'html/product_page.html',
}
def get_page_html(page_name, comments=''):
html = ''
# load from cache, if auto cache clear is falsy
if not (hasattr(conf, 'auto_cache_clear') and conf.auto_cache_clear or 0):
html = webnotes.cache().get_value("page:" + page_name)
comments += "\n\npage load status: fresh"
if not html:
html = load_into_cache(page_name)
comments += "\n\npage load status: cache"
# insert comments
html += """\n<!-- %s -->""" % webnotes.utils.cstr(comments)
return html
def load_into_cache(page_name):
templates_path = os.path.join(os.path.dirname(conf.__file__),
'app', 'website', 'templates')
args = prepare_args(page_name)
from jinja2 import Environment, FileSystemLoader
jenv = Environment(loader = FileSystemLoader(templates_path))
html = jenv.get_template(args['template']).render(args)
return html
html = build_html()
webnotes.cache().set_value("page:" + page_name, html)
return html
def prepare_args(page_name):
if page_name == 'index':
page_name = get_home_page()
if page_name in get_predefined_pages():
args = {
'template': 'pages/%s.html' % page_name,
'name': page_name,
}
else:
args = get_doc_fields(page_name)
args.update(get_outer_env())
return args
def load_from_cache(page_name):
result = search_cache(page_name)
if not result:
if page_name in get_predefined_pages():
# if a predefined page doesn't exist, load it into cache
return None
else:
# if page doesn't exist, raise exception
raise Exception, "Page %s not found" % page_name
return result[0][0]
def get_predefined_pages():
pages_path = os.path.join(os.path.dirname(conf.__file__), 'app',
'website', 'templates', 'pages')
page_list = []
for page in os.listdir(pages_path):
page_list.append(website.utils.scrub_page_name(page))
return page_list
def get_home_page():
doc_name = webnotes.conn.get_value('Website Settings', None, 'home_page')
if doc_name:
page_name = webnotes.conn.get_value('Web Page', doc_name, 'page_name')
else:
page_name = 'login'
return page_name
def get_doc_fields(page_name):
doc_type, doc_name = get_source_doc(page_name)
obj = webnotes.get_obj(doc_type, doc_name)
if hasattr(obj, 'prepare_template_args'):
obj.prepare_template_args()
args = obj.doc.fields
args['template'] = template_map[doc_type]
return args
def get_source_doc(page_name):
"""get source doc for the given page name"""
for doctype in [('Web Page', 'published'), ('Blog', 'published'),
('Item', 'show_in_website')]:
name = webnotes.conn.sql("""select name from `tab%s` where
page_name=%s and ifnull(`%s`, 0)=1""" % (doctype[0], "%s", doctype[1]),
page_name)
if name:
return doctype[0], name[0][0]
return None, None
def get_outer_env():
all_top_items = webnotes.conn.sql("""\
select * from `tabTop Bar Item`
where parent='Website Settings' and parentfield='top_bar_items'
order by idx asc""", as_dict=1)
top_items = [d for d in all_top_items if not d['parent_label']]
# attach child items to top bar
for d in all_top_items:
if d['parent_label']:
for t in top_items:
if t['label']==d['parent_label']:
if not 'child_items' in t:
t['child_items'] = []
t['child_items'].append(d)
break
return {
'top_bar_items': top_items,
'footer_items': webnotes.conn.sql("""\
select * from `tabTop Bar Item`
where parent='Website Settings' and parentfield='footer_items'
order by idx asc""", as_dict=1),
'brand': webnotes.conn.get_value('Website Settings', None, 'brand_html') or 'ERPNext',
'copyright': webnotes.conn.get_value('Website Settings', None, 'copyright'),
'favicon': webnotes.conn.get_value('Website Settings', None, 'favicon')
}
def clear_cache(page_name, doc_type=None, doc_name=None):
if page_name:
delete_page_cache(page_name)
else:
webnotes.cache().flush_keys("page:")
def delete_page_cache(page_name):
webnotes.cache().delete_value("page:" + page_name)