Merge branch 'master' of github.com:webnotes/wnframework
This commit is contained in:
commit
3e59adcd2e
48 changed files with 739 additions and 617 deletions
|
|
@ -99,6 +99,7 @@
|
|||
"lib/js/legacy/utils/msgprint.js",
|
||||
"lib/js/wn/ui/appframe.js",
|
||||
"lib/js/wn/ui/dialog.js",
|
||||
"lib/js/wn/ui/button.js",
|
||||
"lib/js/legacy/widgets/dialog.js",
|
||||
"lib/js/legacy/webpage/page_header.js",
|
||||
"lib/js/legacy/webpage/spinner.js",
|
||||
|
|
@ -132,6 +133,7 @@
|
|||
"lib/js/wn/ui/button.js",
|
||||
"lib/js/wn/ui/search.js",
|
||||
"lib/js/wn/ui/tree.js",
|
||||
"lib/js/wn/upload.js",
|
||||
"lib/js/wn/misc/about.js",
|
||||
"lib/js/wn/views/doclistview.js",
|
||||
"lib/js/wn/views/formview.js",
|
||||
|
|
@ -146,7 +148,6 @@
|
|||
"lib/js/legacy/webpage/spinner.js",
|
||||
"lib/js/legacy/webpage/error_console.js",
|
||||
"lib/js/legacy/webpage/loaders.js",
|
||||
"lib/js/legacy/webpage/uploader.js",
|
||||
"lib/js/legacy/wn/page_layout.js",
|
||||
"lib/js/legacy/wn/widgets/page_sidebar.js",
|
||||
"lib/js/legacy/wn/widgets/footer.js",
|
||||
|
|
|
|||
|
|
@ -92,6 +92,7 @@ li {
|
|||
}
|
||||
|
||||
hr {
|
||||
clear: both;
|
||||
margin: 18px 0;
|
||||
border: 0;
|
||||
border-top: 1px solid #e5e5e5;
|
||||
|
|
|
|||
|
|
@ -125,7 +125,7 @@ div.stat-item {
|
|||
margin-bottom: 7px;
|
||||
background-color: #fff;
|
||||
height: 18px;
|
||||
border: 2px solid #aaa;
|
||||
border: 1px solid #aaa;
|
||||
border-radius: 9px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
|
|
|||
7
js/core.min.js
vendored
7
js/core.min.js
vendored
|
|
@ -31,7 +31,8 @@ var l=items.length;for(var i=0;i<l;i++){var src=items[i];wn.assets.execute(src);
|
|||
/*
|
||||
* lib/js/wn/dom.js
|
||||
*/
|
||||
wn.provide('wn.dom');wn.dom={id_count:0,by_id:function(id){return document.getElementById(id);},set_unique_id:function(ele){var id='unique-'+wn.dom.id_count;ele.setAttribute('id',id);wn.dom.id_count++;return id;},eval:function(txt){if(!txt)return;var el=document.createElement('script');el.appendChild(document.createTextNode(txt));document.getElementsByTagName('head')[0].appendChild(el);},set_style:function(txt){if(!txt)return;var se=document.createElement('style');se.type="text/css";if(se.styleSheet){se.styleSheet.cssText=txt;}else{se.appendChild(document.createTextNode(txt));}
|
||||
wn.provide('wn.dom');wn.dom={id_count:0,by_id:function(id){return document.getElementById(id);},set_unique_id:function(ele){var id='unique-'+wn.dom.id_count;if(ele)
|
||||
ele.setAttribute('id',id);wn.dom.id_count++;return id;},eval:function(txt){if(!txt)return;var el=document.createElement('script');el.appendChild(document.createTextNode(txt));document.getElementsByTagName('head')[0].appendChild(el);},set_style:function(txt){if(!txt)return;var se=document.createElement('style');se.type="text/css";if(se.styleSheet){se.styleSheet.cssText=txt;}else{se.appendChild(document.createTextNode(txt));}
|
||||
document.getElementsByTagName('head')[0].appendChild(se);},add:function(parent,newtag,className,cs,innerHTML,onclick){if(parent&&parent.substr)parent=wn.dom.by_id(parent);var c=document.createElement(newtag);if(parent)
|
||||
parent.appendChild(c);if(className){if(newtag.toLowerCase()=='img')
|
||||
c.src=className
|
||||
|
|
@ -61,9 +62,9 @@ wn.dom.set_box_shadow=function(ele,spread){$(ele).css('-moz-box-shadow','0px 0px
|
|||
$(ele).css('-webkit-box-shadow','0px 0px '+spread+'px rgba(0,0,0,0.3);')
|
||||
$(ele).css('-box-shadow','0px 0px '+spread+'px rgba(0,0,0,0.3);')};(function($){$.fn.add_options=function(options_list){for(var i=0;i<options_list.length;i++){var v=options_list[i];value=v.value||v;label=v.label||v;$('<option>').html(label).attr('value',value).appendTo(this);}
|
||||
$(this).val(options_list[0].value||options_list[0]);}
|
||||
$.fn.set_working=function(){var ele=this.get(0);if(ele.loading_img){$(ele.loading_img).toggle(true);}else{ele.disabled=1;ele.loading_img=$('<img src="images/lib/ui/button-load.gif" \
|
||||
$.fn.set_working=function(){var ele=this.get(0);$(ele).attr('disabled','disabled');if(ele.loading_img){$(ele.loading_img).toggle(true);}else{ele.loading_img=$('<img src="images/lib/ui/button-load.gif" \
|
||||
style="margin-left: 4px; margin-bottom: -2px; display: inline;" />').insertAfter(ele);}}
|
||||
$.fn.done_working=function(){var ele=this.get(0);ele.disabled=0;if(ele.loading_img){$(ele.loading_img).toggle(false);};}})(jQuery);
|
||||
$.fn.done_working=function(){var ele=this.get(0);$(ele).attr('disabled',null);if(ele.loading_img){$(ele.loading_img).toggle(false);};}})(jQuery);
|
||||
/*
|
||||
* lib/js/wn/model.js
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -256,12 +256,11 @@ LocalDB.no_copy_list = ['amended_from','amendment_date','cancel_reason'];
|
|||
LocalDB.copy=function(dt, dn, from_amend) {
|
||||
var newdoc = LocalDB.create(dt);
|
||||
for(var key in locals[dt][dn]) {
|
||||
if(key!=='name' && key.substr(0,2)!='__') { // dont copy name and blank fields
|
||||
locals[dt][newdoc][key] = locals[dt][dn][key];
|
||||
}
|
||||
// dont copy name and blank fields
|
||||
var df = get_field(dt, key);
|
||||
if(df && ((!from_amend && cint(df.no_copy)==1) || in_list(LocalDB.no_copy_list, df.fieldname))) { // blank out 'No Copy'
|
||||
locals[dt][newdoc][key]='';
|
||||
if(key!=='name' && key.substr(0,2)!='__' &&
|
||||
!(df && ((!from_amend && cint(df.no_copy)==1) || in_list(LocalDB.no_copy_list, df.fieldname)))) {
|
||||
locals[dt][newdoc][key] = locals[dt][dn][key];
|
||||
}
|
||||
}
|
||||
return locals[dt][newdoc];
|
||||
|
|
|
|||
|
|
@ -1,237 +0,0 @@
|
|||
|
||||
/*
|
||||
* lib/js/legacy/widgets/report_builder/report_builder.js
|
||||
*/
|
||||
_r.ReportContainer=function(){if(user=='Guest'){msgprint("Not Allowed");return;}
|
||||
var page=wn.container.add_page("Report Builder");this.wrapper=$a(page,'div','layout-wrapper',{padding:'0px'});this.appframe=new wn.ui.AppFrame(this.wrapper);this.appframe.$titlebar.append('<span class="report-title">');this.rb_area=$a(this.wrapper,'div','',{padding:'15px'});var me=this;this.rb_dict={};var run_fn=function(){if(me.cur_rb){me.cur_rb.dt.start_rec=1;me.cur_rb.dt.run();}}
|
||||
var runbtn=this.appframe.add_button('Run',run_fn,'icon-refresh');this.appframe.add_button('Export',function(){me.cur_rb&&me.cur_rb.dt.do_export();},'icon-download-alt');this.appframe.add_button('Print',function(){me.cur_rb&&me.cur_rb.dt.do_print();},'icon-print');this.appframe.add_button('Calc',function(){me.cur_rb&&me.cur_rb.dt.do_calc();},'icon-plus');if(has_common(['Administrator','System Manager'],user_roles)){var savebtn=this.appframe.add_button('Save',function(){if(me.cur_rb)me.cur_rb.save_criteria();});var fn=function(){if(me.cur_rb){if(!me.cur_rb.current_loaded){msgprint("error:You must save the report before you can set Advanced features");return;}
|
||||
loaddoc('Search Criteria',me.cur_rb.sc_dict[me.cur_rb.current_loaded]);}};var advancedbtn=this.appframe.add_button('Advanced Settings',fn,'icon-cog');}
|
||||
this.set_dt=function(dt,onload){my_onload=function(f){if(!f.forbidden){me.cur_rb=f;me.cur_rb.mytabs.items['Result'].expand();if(onload)onload(f);}}
|
||||
if(me.cur_rb)
|
||||
me.cur_rb.hide();if(me.rb_dict[dt]){me.rb_dict[dt].show(my_onload);}else{me.rb_dict[dt]=new _r.ReportBuilder(me.rb_area,dt,my_onload);}}}
|
||||
_r.ReportBuilder=function(parent,doctype,onload){this.menuitems={};this.has_primary_filters=false;this.doctype=doctype;this.forbidden=0;this.filter_fields=[];this.filter_fields_dict={};var me=this;this.fn_list=['beforetableprint','beforerowprint','afterrowprint','aftertableprint','customize_filters','get_query'];this.wrapper=$a(parent,'div','finder_wrapper');this.make_tabs();this.current_loaded=null;this.setup_doctype(onload);this.hide=function(){$dh(me.wrapper);}
|
||||
this.show=function(my_onload){$ds(me.wrapper);this.set_main_title('Report: '+get_doctype_label(me.doctype));if(my_onload)my_onload(me);}}
|
||||
_r.ReportBuilder.prototype.make_tabs=function(){this.tab_wrapper=$a(this.wrapper,'div','finder_tab_area');this.mytabs=new TabbedPage(this.tab_wrapper);this.mytabs.add_item('Result',null,null,1);this.mytabs.add_item('More Filters',null,null,1);this.mytabs.add_item('Select Columns',null,null,1);this.mytabs.tabs=this.mytabs.items;}
|
||||
_r.ReportBuilder.prototype.make_body=function(){this.set_main_title('Report: '+get_doctype_label(this.doctype));var me=this;this.make_save_criteria();this.column_picker=new _r.ReportColumnPicker(this);this.report_filters=new _r.ReportFilters(this);}
|
||||
_r.ReportBuilder.prototype.make_save_criteria=function(){var me=this;this.sc_list=[];this.sc_dict={};for(var n in locals['Search Criteria']){var d=locals['Search Criteria'][n];if(d.doc_type==this.doctype){this.sc_list[this.sc_list.length]=d.criteria_name;this.sc_dict[d.criteria_name]=n;}}}
|
||||
_r.ReportBuilder.prototype.save_criteria=function(save_as){var overwrite=0;if(this.current_loaded&&(!save_as)){var overwrite=confirm('Do you want to overwrite the saved criteria "'+this.current_loaded+'"');if(overwrite){var doc=locals['Search Criteria'][this.sc_dict[this.current_loaded]];var criteria_name=this.current_loaded;}}
|
||||
if(!overwrite){var criteria_name=prompt('Select a name for the criteria:','');if(!criteria_name)
|
||||
return;var dn=createLocal('Search Criteria');var doc=locals['Search Criteria'][dn];doc.criteria_name=criteria_name;doc.doc_type=this.doctype;}
|
||||
var cl=[];var fl={};var t=this.column_picker.get_selected();for(var i=0;i<t.length;i++)
|
||||
cl.push(t[i].parent+'\1'+t[i].label);for(var i=0;i<this.filter_fields.length;i++){var t=this.filter_fields[i];var v=t.get_value?t.get_value():'';if(v)fl[t.df.parent+'\1'+t.df.label+(t.bound?('\1'+t.bound):'')]=v;}
|
||||
doc.columns=cl.join(',');doc.filters=JSON.stringify(fl);doc.sort_by=sel_val(this.dt.sort_sel);doc.sort_order=this.dt.sort_order;doc.page_len=this.dt.page_len;if(this.parent_dt)
|
||||
doc.parent_doc_type=this.parent_dt
|
||||
var me=this;var fn=function(r){me.sc_dict[criteria_name]=r.main_doc_name;me.set_criteria_sel(criteria_name);}
|
||||
save_doclist(doc.doctype,doc.name,'Save',fn);}
|
||||
_r.ReportBuilder.prototype.hide_all_filters=function(){for(var i=0;i<this.filter_fields.length;i++){this.filter_fields[i].df.filter_hide=1;}}
|
||||
_r.ReportBuilder.prototype.run=function(){this.dt.run();}
|
||||
_r.ReportBuilder.prototype.clear_criteria=function(){this.column_picker.clear();this.column_picker.set_defaults();for(var i=0;i<this.filter_fields.length;i++){this.filter_fields[i].df.filter_hide=0;this.filter_fields[i].df.ignore=0;if(this.filter_fields[i].is_custom){this.filter_fields[i].df.filter_hide=1;this.filter_fields[i].df.ignore=1;}
|
||||
this.filter_fields[i].set_input(null);}
|
||||
this.set_sort_options();this.set_main_title('Report: '+get_doctype_label(this.doctype));this.current_loaded=null;this.customized_filters=null;this.sc=null;this.has_index=1;this.has_headings=1;for(var i in this.fn_list)this[this.fn_list[i]]=null;}
|
||||
_r.ReportBuilder.prototype.set_main_title=function(t,t1){var title=t+(t1?t1:'');_r.rb_con.appframe.$titlebar.find('.report-title').html(title);set_title(title);}
|
||||
_r.ReportBuilder.prototype.select_column=function(dt,label,value){if(value==null)value=1;this.column_picker.set(dt,label,value);}
|
||||
_r.ReportBuilder.prototype.set_filter=function(dt,label,value){if(this.filter_fields_dict[dt+'\1'+label])
|
||||
this.filter_fields_dict[dt+'\1'+label].set_input(value);}
|
||||
_r.ReportBuilder.prototype.load_criteria=function(criteria_name){this.clear_criteria();if(!this.sc_dict[criteria_name]){alert(criteria_name+' could not be loaded. Please Refresh and try again');}
|
||||
this.sc=locals['Search Criteria'][this.sc_dict[criteria_name]];var report=this;if(this.sc&&this.sc.report_script)eval(this.sc.report_script);this.large_report=0;if(report.customize_filters){try{report.customize_filters(this);}catch(err){errprint('Error in "customize_filters":\n'+err);}}
|
||||
this.report_filters.refresh();this.column_picker.clear();var cl=this.sc.columns?this.sc.columns.split(','):[];for(var c=0;c<cl.length;c++){var key=cl[c].split('\1');this.select_column(key[0],key[1],1);}
|
||||
eval('var fl='+this.sc.filters);for(var n in fl){if(fl[n]){var key=n.split('\1');if(key[1]=='docstatus'){}
|
||||
this.set_filter(key[0],key[1],fl[n]);}}
|
||||
this.set_criteria_sel(criteria_name);this.set_filters_from_route();}
|
||||
_r.ReportBuilder.prototype.set_criteria_sel=function(criteria_name){var sc=locals['Search Criteria'][this.sc_dict[criteria_name]];if(sc&&sc.add_col)
|
||||
var acl=sc.add_col.split('\n');else
|
||||
var acl=[];var new_sl=[];for(var i=0;i<acl.length;i++){var tmp=acl[i].split(' AS ');if(tmp[1]){var t=eval(tmp[1]);new_sl[new_sl.length]=[t,"`"+t+"`"];}}
|
||||
this.set_sort_options(new_sl);if(sc&&sc.sort_by){this.dt.sort_sel.value=sc.sort_by;}
|
||||
if(sc&&sc.sort_order){sc.sort_order=='ASC'?this.dt.set_asc():this.dt.set_desc();}
|
||||
if(sc&&sc.page_len){this.dt.page_len_sel.inp.value=sc.page_len;}
|
||||
this.current_loaded=criteria_name;this.set_main_title(criteria_name,sc.description);}
|
||||
_r.ReportBuilder.prototype.setup_filters_and_cols=function(){function can_dt_be_submitted(dt){if(locals.DocType&&locals.DocType[dt]&&locals.DocType[dt].allow_trash)return 1;var plist=getchildren('DocPerm',dt,'permissions','DocType');for(var pidx in plist){if(plist[pidx].submit)return 1;}
|
||||
return 0;}
|
||||
var me=this;var dt=me.parent_dt?me.parent_dt:me.doctype;var fl=[{'fieldtype':'Data','label':'ID','fieldname':'name','in_filter':1,'parent':dt},{'fieldtype':'Data','label':'Owner','fieldname':'owner','in_filter':1,'parent':dt},{'fieldtype':'Date','label':'Created on','fieldname':'creation','in_filter':0,'parent':dt},{'fieldtype':'Date','label':'Last modified on','fieldname':'modified','in_filter':0,'parent':dt},];if(can_dt_be_submitted(dt)){fl[fl.length]={'fieldtype':'Check','label':'Saved','fieldname':'docstatus','search_index':1,'in_filter':1,'def_filter':1,'parent':dt};fl[fl.length]={'fieldtype':'Check','label':'Submitted','fieldname':'docstatus','search_index':1,'in_filter':1,'def_filter':1,'parent':dt};fl[fl.length]={'fieldtype':'Check','label':'Cancelled','fieldname':'docstatus','search_index':1,'in_filter':1,'parent':dt};}
|
||||
me.make_datatable();me.orig_sort_list=[];if(me.parent_dt){me.setup_dt_filters_and_cols(fl,me.parent_dt);var fl=[];}
|
||||
me.setup_dt_filters_and_cols(fl,me.doctype);if(!this.has_primary_filters)
|
||||
$dh(this.report_filters.first_page_filter);this.column_picker.refresh();$ds(me.body);}
|
||||
_r.ReportBuilder.prototype.set_filters_from_route=function(){var route=wn.get_route();if(route.length>3){for(var i=3;i<route.length;i++){var p=route[i].split('=');if(p.length==2){var dt=this.parent_dt?this.parent_dt:this.doctype;this.set_filter(dt,p[0],p[1]);}}}}
|
||||
_r.ReportBuilder.prototype.add_filter=function(f){if(this.filter_fields_dict[f.parent+'\1'+f.label]){this.filter_fields_dict[f.parent+'\1'+f.label].df=f;}else{this.report_filters.add_field(f,f.parent,null,1);}}
|
||||
_r.ReportBuilder.prototype.setup_dt_filters_and_cols=function(fl,dt){var me=this;var lab=$a(me.filter_area,'div','filter_dt_head');lab.innerHTML='Filters for '+get_doctype_label(dt);var lab=$a(me.picker_area,'div','builder_dt_head');lab.innerHTML='Select columns for '+get_doctype_label(dt);var dt_fields=wn.meta.docfield_list[dt];for(var i=0;i<dt_fields.length;i++){fl[fl.length]=dt_fields[i];}
|
||||
var sf_list=locals.DocType[dt].search_fields?locals.DocType[dt].search_fields.split(','):[];for(var i in sf_list)sf_list[i]=strip(sf_list[i]);for(var i=0;i<fl.length;i++){var f=fl[i];if(f&&cint(f.in_filter)){me.report_filters.add_field(f,dt,in_list(sf_list,f.fieldname));}
|
||||
if(f&&!in_list(no_value_fields,f.fieldtype)&&f.fieldname!='docstatus'&&(!f.report_hide)){me.column_picker.add_field(f);}}
|
||||
me.set_sort_options();}
|
||||
_r.ReportBuilder.prototype.set_sort_options=function(l){var sl=this.orig_sort_list;empty_select(this.dt.sort_sel);if(l)sl=add_lists(l,this.orig_sort_list);if(!l)l=[];if(!l.length){l.push(['ID','name'])}
|
||||
for(var i=0;i<sl.length;i++){this.dt.add_sort_option(sl[i][0],sl[i][1]);}}
|
||||
_r.ReportBuilder.prototype.validate_permissions=function(onload){this.perm=get_perm(this.parent_dt?this.parent_dt:this.doctype);if(!this.perm[0][READ]){this.forbidden=1;if(user=='Guest'){msgprint('You must log in to view this page');}else{msgprint('No Read Permission');}
|
||||
window.back();return 0;}
|
||||
return 1;}
|
||||
_r.ReportBuilder.prototype.setup_doctype=function(onload){var me=this;if(!locals['DocType'][this.doctype]){this.load_doctype_from_server(onload);}else{for(var key in locals.DocField){var f=locals.DocField[key];if(f.fieldtype=='Table'&&f.options==this.doctype)
|
||||
this.parent_dt=f.parent;}
|
||||
if(!me.validate_permissions())
|
||||
return;me.validate_permissions();me.make_body();me.setup_filters_and_cols();if(onload)onload(me);}}
|
||||
_r.ReportBuilder.prototype.load_doctype_from_server=function(onload){var me=this;$c('webnotes.widgets.form.load.getdoctype',args={'doctype':this.doctype,'with_parent':1},function(r,rt){if(r.parent_dt)me.parent_dt=r.parent_dt;if(!me.validate_permissions())
|
||||
return;me.make_body();me.setup_filters_and_cols();if(onload)onload(me);});}
|
||||
_r.ReportBuilder.prototype.reset_report=function(){this.clear_criteria();this.mytabs.items['Select Columns'].show();this.mytabs.items['More Filters'].show();this.report_filters.refresh();this.column_picker.refresh();var dt=this.parent_dt?this.parent_dt:this.doctype;this.set_filter(dt,'Saved',1);this.set_filter(dt,'Submitted',1);this.set_filter(dt,'Cancelled',0);this.column_picker.set_defaults();this.dt.clear_all();this.dt.sort_sel.value='ID';this.dt.page_len_sel.inp.value='50';this.dt.set_no_limit(0);this.dt.set_desc();this.set_filters_from_route();}
|
||||
_r.ReportBuilder.prototype.make_datatable=function(){var me=this;this.dt_area=$a(this.mytabs.items['Result'].body,'div');var clear_area=$a(this.mytabs.items['Result'].body,'div');clear_area.style.marginTop='8px';clear_area.style.textAlign='right';this.clear_btn=$a($a(clear_area,'span'),'button');this.clear_btn.innerHTML='Clear Settings';this.clear_btn.onclick=function(){me.reset_report();}
|
||||
var d=$a(clear_area,'span','',{marginLeft:'16px'});d.innerHTML='<span>Show Query: </span>';this.show_query=$a_input(d,'checkbox');this.show_query.checked=false;this.dt=new _r.DataTable(this.dt_area,'');this.dt.finder=this;this.dt.make_query=function(){var report=me;if(me.current_loaded&&me.sc_dict[me.current_loaded]){var sc=get_local('Search Criteria',me.sc_dict[me.current_loaded]);}
|
||||
if(sc)me.dt.search_criteria=sc;else me.dt.search_criteria=null;if(sc&&sc.server_script)me.dt.server_script=sc.server_script;else me.dt.server_script=null;for(var i=0;i<me.fn_list.length;i++){if(me[me.fn_list[i]])me.dt[me.fn_list[i]]=me[me.fn_list[i]];else me.dt[me.fn_list[i]]=null;}
|
||||
var fl=[];var docstatus_cl=[];var cl=[];var table_name=function(t){return'`tab'+t+'`';}
|
||||
var dis_filters_list=[];if(sc&&sc.dis_filters)
|
||||
var dis_filters_list=sc.dis_filters.split('\n');var t=me.column_picker.get_selected();for(var i=0;i<t.length;i++){fl.push(table_name(t[i].parent)+'.`'+t[i].fieldname+'` AS `'+t[i].parent+'.'+t[i].fieldname+'`');}
|
||||
me.selected_fields=fl;if(sc&&sc.add_col){var adv_fl=sc.add_col.split('\n');for(var i=0;i<adv_fl.length;i++){fl[fl.length]=adv_fl[i];}}
|
||||
me.dt.filter_vals={}
|
||||
add_to_filter=function(k,v,is_select){if(v==null)v='';if(!in_list(keys(me.dt.filter_vals),k)){me.dt.filter_vals[k]=v;}else{if(is_select)
|
||||
me.dt.filter_vals[k]+='\n'+v;else
|
||||
me.dt.filter_vals[k+'1']=v;}}
|
||||
for(var i=0;i<me.filter_fields.length;i++){var t=me.filter_fields[i];var v=t.get_value?t.get_value():'';if(t.df.fieldtype=='Select'){if(t.input.multiple){for(var sel_i=0;sel_i<v.length;sel_i++){add_to_filter(t.df.fieldname,v[sel_i],1);}
|
||||
if(!v.length)add_to_filter(t.df.fieldname,"",1);}else{add_to_filter(t.df.fieldname,v);}}else add_to_filter(t.df.fieldname,v);if(!in_list(dis_filters_list,t.df.fieldname)&&!t.df.ignore){if(t.df.fieldname=='docstatus'){if(t.df.label=='Saved'){if(t.get_value())docstatus_cl[docstatus_cl.length]=table_name(t.df.parent)+'.docstatus=0';else cl[cl.length]=table_name(t.df.parent)+'.docstatus!=0';}
|
||||
else if(t.df.label=='Submitted'){if(t.get_value())docstatus_cl[docstatus_cl.length]=table_name(t.df.parent)+'.docstatus=1';else cl[cl.length]=table_name(t.df.parent)+'.docstatus!=1';}
|
||||
else if(t.df.label=='Cancelled'){if(t.get_value())docstatus_cl[docstatus_cl.length]=table_name(t.df.parent)+'.docstatus=2';else cl[cl.length]=table_name(t.df.parent)+'.docstatus!=2';}}else{var fn='`'+t.df.fieldname+'`';var v=t.get_value?t.get_value():'';if(v){if(in_list(['Data','Link','Small Text','Text'],t.df.fieldtype)){cl[cl.length]=table_name(t.df.parent)+'.'+fn+' LIKE "'+v+'%"';}else if(t.df.fieldtype=='Select'){if(t.input.multiple){var tmp_cl=[];for(var sel_i=0;sel_i<v.length;sel_i++){if(v[sel_i]){tmp_cl[tmp_cl.length]=table_name(t.df.parent)+'.'+fn+' = "'+v[sel_i]+'"';}}
|
||||
if(tmp_cl.length)cl[cl.length]='('+tmp_cl.join(' OR ')+')';}else{cl[cl.length]=table_name(t.df.parent)+'.'+fn+' = "'+v+'"';}}else{var condition='=';if(t.sql_condition)condition=t.sql_condition;cl[cl.length]=table_name(t.df.parent)+'.'+fn+condition+'"'+v+'"';}}}}}
|
||||
me.dt.filter_vals.user=user;me.dt.filter_vals.user_email=user_email;me.filter_vals=me.dt.filter_vals;this.is_simple=0;if(sc&&sc.custom_query){this.query=repl(sc.custom_query,me.dt.filter_vals);this.is_simple=1;return}
|
||||
if(me.get_query){this.query=me.get_query();this.is_simple=1;}else{if(docstatus_cl.length)
|
||||
cl[cl.length]='('+docstatus_cl.join(' OR ')+')';if(sc&&sc.add_cond){var adv_cl=sc.add_cond.split('\n');for(var i=0;i<adv_cl.length;i++){cl[cl.length]=adv_cl[i];}}
|
||||
if(!fl.length){alert('You must select atleast one column to view');this.query='';return;}
|
||||
var tn=table_name(me.doctype);if(me.parent_dt){tn=tn+','+table_name(me.parent_dt);cl[cl.length]=table_name(me.doctype)+'.`parent` = '+table_name(me.parent_dt)+'.`name`';}
|
||||
if(sc&&sc.add_tab){var adv_tl=sc.add_tab.split('\n');tn=tn+','+adv_tl.join(',');}
|
||||
if(!cl.length)
|
||||
this.query='SELECT '+fl.join(',\n')+' FROM '+tn
|
||||
else
|
||||
this.query='SELECT '+fl.join(',')+' FROM '+tn+' WHERE '+cl.join('\n AND ');if(sc&&sc.group_by){this.query+=' GROUP BY '+sc.group_by;}
|
||||
this.query=repl(this.query,me.dt.filter_vals)}
|
||||
if(me.show_query.checked){this.show_query=1;}
|
||||
if(me.current_loaded)this.rep_name=me.current_loaded;else this.rep_name=me.doctype;}}
|
||||
_r.ReportBuilder.prototype.get_filter=function(dt,label){return this.filter_fields_dict[dt+FILTER_SEP+label];}
|
||||
_r.ReportBuilder.prototype.set_filter_properties=function(dt,label,properties){var f=this.filter_fields_dict[dt+FILTER_SEP+label];for(key in properties){f.df[key]=properties[key];}}
|
||||
_r.ReportFilters=function(rb){this.rb=rb;this.first_page_filter=$a(rb.mytabs.items['Result'].body,'div','finder_filter_area');this.filter_area=$a(rb.mytabs.items['More Filters'].body,'div','finder_filter_area');this.filter_fields_area=$a(this.filter_area,'div');}
|
||||
_r.ReportFilters.prototype.refresh=function(){var fl=this.rb.filter_fields
|
||||
for(var i=0;i<fl.length;i++){var f=fl[i];if(f.df.filter_hide){$dh(f.wrapper);}else{$ds(f.wrapper);}
|
||||
if(f.df.bold){if(f.label_cell)
|
||||
$y(f.label_cell,{fontWeight:'bold'})}else{if(f.label_cell)$y(f.label_cell,{fontWeight:'normal'})}
|
||||
if(f.df['report_default'])
|
||||
f.set_input(f.df['report_default']);if(f.df.in_first_page&&f.df.filter_cell){f.df.filter_cell.parentNode.removeChild(f.df.filter_cell);this.first_page_filter.appendChild(f.df.filter_cell);this.rb.has_primary_filters=1;$ds(this.first_page_filter);}}}
|
||||
_r.ReportFilters.prototype.add_date_field=function(cell,f,dt,is_custom){var my_div=$a(cell,'div','',{});var f1=copy_dict(f);f1.label='From '+f1.label;var tmp1=this.make_field_obj(f1,dt,my_div,is_custom);tmp1.sql_condition='>=';tmp1.bound='lower';var f2=copy_dict(f);f2.label='To '+f2.label;var tmp2=this.make_field_obj(f2,dt,my_div,is_custom);tmp2.sql_condition='<=';tmp2.bound='upper';}
|
||||
_r.ReportFilters.prototype.add_numeric_field=function(cell,f,dt,is_custom){var my_div=$a(cell,'div','',{});var f1=copy_dict(f);f1.label=f1.label+' >=';var tmp1=this.make_field_obj(f1,dt,my_div,is_custom);tmp1.sql_condition='>=';tmp1.bound='lower';var f2=copy_dict(f);f2.label=f2.label+' <=';var tmp2=this.make_field_obj(f2,dt,my_div,is_custom);tmp2.sql_condition='<=';tmp2.bound='upper';}
|
||||
_r.ReportFilters.prototype.make_field_obj=function(f,dt,parent,is_custom){var tmp=make_field(f,dt,parent,this.rb,false);tmp.not_in_form=1;tmp.in_filter=1;tmp.refresh();this.rb.filter_fields[this.rb.filter_fields.length]=tmp;this.rb.filter_fields_dict[f.parent+'\1'+f.label]=tmp;if(is_custom)tmp.is_custom=1;return tmp;}
|
||||
_r.ReportFilters.prototype.add_field=function(f,dt,in_primary,is_custom){var me=this;if(f.in_first_page)in_primary=true;var fparent=this.filter_fields_area;if(in_primary){fparent=this.first_page_filter;this.rb.has_primary_filters=1;}
|
||||
if(f.on_top){var cell=document.createElement('div');fparent.insertBefore(cell,fparent.firstChild);$y(cell,{width:'70%'});}else if(f.insert_before){var cell=document.createElement('div');fparent.insertBefore(cell,fparent[f.df.insert_before].filter_cell);$y(cell,{width:'70%'});}
|
||||
else
|
||||
var cell=$a(fparent,'div','',{width:'70%'});f.filter_cell=cell;if(f.fieldtype=='Date'){this.add_date_field(cell,f,dt);}else if(in_list(['Currency','Int','Float'],f.fieldtype)){this.add_numeric_field(cell,f,dt);}else if(!in_list(['Section Break','Column Break','Read Only','HTML','Table','Image','Button'],f.fieldtype)){var tmp=this.make_field_obj(f,dt,cell,is_custom);}
|
||||
if(f.fieldname!='docstatus')
|
||||
me.rb.orig_sort_list.push([f.label,'`tab'+f.parent+'`.`'+f.fieldname+'`']);if(f.def_filter)
|
||||
tmp.input.checked=true;}
|
||||
_r.ReportColumnPicker=function(rb){this.rb=rb;this.picker_area=$a(this.rb.mytabs.items['Select Columns'].body,'div','finder_picker_area');this.all_fields=[];this.sel_idx=0;this.make_body();}
|
||||
_r.ReportColumnPicker.prototype.make_body=function(){var t=make_table(this.picker_area,1,3,'100%',['35%','30%','35%'],{verticalAlign:'middle',textAlign:'center'});$a($td(t,0,0),'h3','',{marginBottom:'8px'}).innerHTML='Columns';this.unsel_fields=$a($td(t,0,0),'select','',{height:'200px',width:'100%',border:'1px solid #AAA'});this.unsel_fields.multiple=true;this.unsel_fields.onchange=function(){for(var i=0;i<this.options.length;i++)this.options[i].field.is_selected=this.options[i].selected;}
|
||||
var me=this;this.up_btn=$a($a($td(t,0,1),'div'),'button','',{width:'70px'});this.up_btn.innerHTML='Up ↑';this.up_btn.onclick=function(){me.move_up();}
|
||||
this.add_all=$a($a($td(t,0,1),'div'),'button','',{width:'40px'});this.add_all.innerHTML='>>';this.add_all.onclick=function(){me.move(me.unsel_fields,'add',1);}
|
||||
this.add_btn=$a($a($td(t,0,1),'div'),'button','',{width:'110px'});this.add_btn.innerHTML='<b>Add ></b>';this.add_btn.onclick=function(){me.move(me.unsel_fields,'add');}
|
||||
this.remove_btn=$a($a($td(t,0,1),'div'),'button','',{width:'110px'});this.remove_btn.innerHTML='<b>< Remove</b>';this.remove_btn.onclick=function(){me.move(me.sel_fields,'remove');}
|
||||
this.remove_all=$a($a($td(t,0,1),'div'),'button','',{width:'40px'});this.remove_all.innerHTML='<<';this.remove_all.onclick=function(){me.move(me.sel_fields,'remove',1);}
|
||||
this.dn_btn=$a($a($td(t,0,1),'div'),'button','',{width:'70px'});this.dn_btn.innerHTML='Down ↓';this.dn_btn.onclick=function(){me.move_down();}
|
||||
$a($td(t,0,2),'h3','',{marginBottom:'8px'}).innerHTML='Selected Columns';this.sel_fields=$a($td(t,0,2),'select','',{height:'200px',width:'100%',border:'1px solid #AAA'});this.sel_fields.multiple=true;this.sel_fields.onchange=function(){for(var i=0;i<this.options.length;i++)this.options[i].field.is_selected=this.options[i].selected;}}
|
||||
_r.ReportColumnPicker.prototype.get_by_sel_idx=function(s,idx){for(var j=0;j<s.options.length;j++){if(s.options[j].field.sel_idx==idx)
|
||||
return s.options[j].field;}
|
||||
return{}}
|
||||
_r.ReportColumnPicker.prototype.move_up=function(){var s=this.sel_fields;for(var i=1;i<s.options.length;i++){if(s.options[i].selected){s.options[i].field.sel_idx--;this.get_by_sel_idx(s,i-1).sel_idx++;}}
|
||||
this.refresh();}
|
||||
_r.ReportColumnPicker.prototype.move_down=function(){var s=this.sel_fields;if(s.options.length<=1)return;for(var i=s.options.length-2;i>=0;i--){if(s.options[i].selected){this.get_by_sel_idx(s,i+1).sel_idx--;s.options[i].field.sel_idx++;}}
|
||||
this.refresh();}
|
||||
_r.ReportColumnPicker.prototype.move=function(s,type,all){for(var i=0;i<s.options.length;i++){if(s.options[i].selected||all){if(type=='add'){s.options[i].field.selected=1;s.options[i].field.sel_idx=this.sel_idx;this.sel_idx++;}else{s.options[i].field.selected=0;s.options[i].field.sel_idx=0;this.sel_idx--;}}}
|
||||
this.refresh();}
|
||||
_r.ReportColumnPicker.prototype.refresh=function(){var ul=[];var sl=[];for(var i=0;i<this.all_fields.length;i++){var o=this.all_fields[i];if(o.selected){sl.push(o);if(this.rb.dt)this.rb.dt.set_sort_option_disabled(o.df.label,0);}else{ul.push(o);if(this.rb.dt)this.rb.dt.set_sort_option_disabled(o.df.label,1);}}
|
||||
ul.sort(function(a,b){return(cint(a.df.idx)-cint(b.df.idx))});sl.sort(function(a,b){return(cint(a.sel_idx)-cint(b.sel_idx))})
|
||||
for(var i=0;i<sl.length;i++){sl[i].sel_idx=i;}
|
||||
this.set_options(this.unsel_fields,ul);this.set_options(this.sel_fields,sl);}
|
||||
_r.ReportColumnPicker.prototype.set_options=function(s,l){empty_select(s);for(var i=0;i<l.length;i++){var v=l[i].df.parent+'.'+l[i].df.label;var v_label=get_doctype_label(l[i].df.parent)+'.'+l[i].df.label;var o=new Option(v_label,v,false,false);o.field=l[i];if(o.field.is_selected)o.selected=1;s.options[s.options.length]=o;}}
|
||||
_r.ReportColumnPicker.prototype.clear=function(){this.sel_idx=0;for(var i=0;i<this.all_fields.length;i++){this.all_fields[i].selected=0;}
|
||||
this.refresh();}
|
||||
_r.ReportColumnPicker.prototype.get_selected=function(){var sl=[];for(var i=0;i<this.all_fields.length;i++){var o=this.all_fields[i];if(o.selected){sl[sl.length]=o.df;o.df.sel_idx=o.sel_idx;}}
|
||||
return sl.sort(function(a,b){return(cint(a.sel_idx)-cint(b.sel_idx))});}
|
||||
_r.ReportColumnPicker.prototype.set_defaults=function(){for(var i=0;i<this.all_fields.length;i++){if(this.all_fields[i].selected_by_default)
|
||||
this.all_fields[i].selected=1;}}
|
||||
_r.ReportColumnPicker.prototype.add_field=function(f){if(!f.label)return;var by_default=(f.in_filter)?1:0;this.all_fields.push({selected:by_default,df:f,sel_idx:(by_default?this.sel_idx:0),selected_by_default:by_default});this.sel_idx+=by_default;}
|
||||
_r.ReportColumnPicker.prototype.set=function(dt,label,selected){for(var i=0;i<this.all_fields.length;i++){if(this.all_fields[i].df.parent==dt&&this.all_fields[i].df.label==label){this.all_fields[i].selected=selected;this.all_fields[i].sel_idx=this.sel_idx;this.sel_idx+=cint(selected);this.refresh();return;}}}
|
||||
/*
|
||||
* lib/js/legacy/widgets/report_builder/datatable.js
|
||||
*/
|
||||
_r.scroll_head=function(ele){var h=ele.childNodes[0];h.style.top=cint(ele.scrollTop)+'px';}
|
||||
_r.DataTable=function(html_fieldname,dt,repname,hide_toolbar){var me=this;if(html_fieldname.substr){var html_field=cur_frm.fields_dict[html_fieldname];html_field.onrefresh=function(){if(me.docname!=cur_frm.docname){me.clear_all();me.docname=cur_frm.docname;}}
|
||||
var parent=html_field.wrapper;datatables[html_fieldname]=this;}else{var parent=html_fieldname;}
|
||||
this.start_rec=1;this.page_len=50;this.repname=repname;this.dt=dt;this.no_limit=false;this.query='';this.has_index=1;this.has_headings=1;this.disabled_options={};this.levels=[];if(this.dt){var tw=$a(parent,'div');var t=$a(tw,'div','link_type');t.style.cssFloat='right';$h(tw,'14px');t.style.margin='2px 0px';t.style.fontSize='11px';t.onclick=function(){new_doc(me.dt);}
|
||||
t.innerHTML='New '+this.dt;}
|
||||
if(!hide_toolbar)this.make_toolbar(parent);this.wrapper=$a(parent,'div','report_tab');$h(this.wrapper,cint(screen.height*0.35)+'px');this.wrapper.onscroll=function(){_r.scroll_head(this);}
|
||||
this.hwrapper=$a(this.wrapper,'div','report_head_wrapper');this.twrapper=$a(this.wrapper,'div','report_tab_wrapper');this.no_data_tag=$a(this.wrapper,'div','report_no_data');this.no_data_tag.innerHTML='No Records Found';this.fetching_tag=$a(this.wrapper,'div','',{height:'100%',background:'url("images/lib/ui/square_loading.gif") center no-repeat',display:'none'});}
|
||||
_r.DataTable.prototype.add_icon=function(parent,imgsrc){var i=$a(parent,'img');i.style.padding='2px';i.style.cursor='pointer';i.setAttribute('src','images/lib/icons/'+imgsrc+'.gif');return i;}
|
||||
_r.DataTable.prototype.set_no_limit=function(v){if(v){this.no_limit=1;$dh(this.page_len_sel.wrapper);}else{this.no_limit=0;$ds(this.page_len_sel.wrapper);}}
|
||||
_r.DataTable.prototype.make_toolbar=function(parent){var me=this;this.hbar=$a(parent,'div','',{margin:'8px 0px 16px 0px'});var ht=make_table(this.hbar,1,3,'100%',['40%','40%','20%'],{verticalAlign:'middle'});var div=$a($td(ht,0,0),'div');var t=make_table($td(ht,0,1),1,6,null,[null,null,null,'20px',null,null],{verticalAlign:'middle'});$td(t,0,0).innerHTML='Sort By:';$y($td(t,0,1),{textAlign:'right',paddingRight:'4px'});this.sort_sel=$a($td(t,0,2),'select','',{width:'100px'});this.sort_sel.onchange=function(){me.start_rec=1;me.run();}
|
||||
this.sort_icon=this.add_icon($td(t,0,3),'arrow_down');this.sort_order='DESC';this.sort_icon.onclick=function(){if(me.sort_order=='ASC')me.set_desc();else me.set_asc();me.start_rec=1;me.run();}
|
||||
$td(t,0,4).innerHTML='Per Page:';$y($td(t,0,4),{textAlign:'right',paddingRight:'4px'});var s=new SelectWidget($td(t,0,5),['50','100','500','1000'],'70px');s.inp.value='50';s.inp.onchange=function(){me.page_len=flt(this.value);}
|
||||
this.page_len_sel=s;var c1=$td(ht,0,2);c1.style.textAlign='right';var ic=this.add_icon(c1,'resultset_first');ic.onclick=function(){me.start_rec=1;me.run();}
|
||||
var ic=this.add_icon(c1,'resultset_previous');ic.onclick=function(){if(me.start_rec-me.page_len<=0)return;me.start_rec=me.start_rec-me.page_len;me.run();}
|
||||
this.has_next=false;var ic=this.add_icon(c1,'resultset_next');ic.onclick=function(){if(!me.has_next)return;me.start_rec=me.start_rec+me.page_len;me.run();}}
|
||||
_r.DataTable.prototype.set_desc=function(){this.sort_icon.src='images/lib/icons/arrow_down.gif';this.sort_order='DESC';}
|
||||
_r.DataTable.prototype.set_asc=function(icon){this.sort_icon.src='images/lib/icons/arrow_up.gif';this.sort_order='ASC';}
|
||||
_r.DataTable.prototype.set_sort_option_disabled=function(label,disabled){var s=this.sort_sel;if(disabled){for(var i=0;i<s.options.length;i++){if(s.options[i]&&s.options[i].text==label){this.disabled_options[label]=s.options[i];s.remove(i);}}}else{if(this.disabled_options[label]){try{s.add(this.disabled_options[label],s.options[s.options.length-1]);}catch(e){try{s.add(this.disabled_options[label],s.options.length-1);}catch(e){}}
|
||||
this.disabled_options[label]=null;}}}
|
||||
_r.DataTable.prototype.add_sort_option=function(label,val){var s=this.sort_sel;s.options[s.options.length]=new Option(label,val,false,s.options.length==0?true:false);}
|
||||
_r.DataTable.prototype.update_query=function(no_limit){if((_r.rb_con.cur_rb&&_r.rb_con.cur_rb.get_query)||(this.search_criteria&&this.search_criteria.custom_query)){}else{if(!sel_val(this.sort_sel)){this.sort_sel.selectedIndex=0;}
|
||||
this.query+=NEWLINE
|
||||
+' ORDER BY '+sel_val(this.sort_sel)
|
||||
+' '+this.sort_order;}
|
||||
if(no_limit||this.no_limit){if(this.show_query)alert(this.query);return;}
|
||||
this.query+=' LIMIT '+(this.start_rec-1)+','+this.page_len;if(this.show_query)
|
||||
alert(this.query);}
|
||||
_r.DataTable.prototype._get_query=function(no_limit){$dh(this.no_data_tag);this.show_query=0;if(this.make_query)
|
||||
this.make_query();this.update_query(no_limit);}
|
||||
_r.DataTable.prototype.run=function(){if(this.validate&&!this.validate())
|
||||
return;if(_r.rb_con.cur_rb){if(_r.rb_con.cur_rb.large_report==1){msgprint("This is a very large report and cannot be shown in the browser as it is likely to make your browser very slow.<br><br>Please click on 'Export' to open in a spreadsheet");return;}
|
||||
_r.rb_con.cur_rb.mytabs.items['Result'].expand();}
|
||||
var me=this;this._get_query();if(this.set_data){this.show_result(this.set_data);this.set_data=null;return;}
|
||||
$ds(this.fetching_tag);if($.browser.mozilla)this.clear_all();var args={'query':me.query,'report_name':'_r.DataTable','show_deleted':1,'sc_id':me.search_criteria?me.search_criteria.name:'','filter_values':me.filter_vals?docstring(me.filter_vals):'','roles':'["'+user_roles.join('","')+'"]'}
|
||||
if(this.is_simple)args.is_simple=1;$c('webnotes.widgets.query_builder.runquery',args,function(r,rt){$dh(me.fetching_tag);me.show_result(r,rt);});}
|
||||
_r.DataTable.prototype.clear_all=function(){if(this.htab&&this.htab.parentNode){this.htab.parentNode.removeChild(this.htab);delete this.htab;}
|
||||
if(this.tab&&this.tab.parentNode){this.tab.parentNode.removeChild(this.tab);delete this.tab;}
|
||||
$dh(this.no_data_tag);}
|
||||
_r.DataTable.prototype.has_data=function(){if(this.htab&&this.htab.rows.length)return 1;else return 0;}
|
||||
_r.DataTable.prototype.show_result=function(r,rt){var me=this;this.clear_all();this.rset=eval(r.values);if(this.rset&&this.rset.length){if(this.has_headings){this.htab=$a(this.hwrapper,'table');$y(this.twrapper,{top:'25px',borderTop:'0px'});}
|
||||
this.tab=$a(this.twrapper,'table');this.colwidths=eval(r.colwidths);this.coltypes=eval(r.coltypes);this.coloptions=eval(r.coloptions);this.colnames=eval(r.colnames);$y(this.tab,{tableLayout:'fixed'});if(this.beforetableprint)this.beforetableprint(this);if(this.has_headings)this.make_head_tab(this.colnames);var start=this.start_rec;var rset_len=this.rset.length;if(rset_len>1000){msgprint("Showing only 1000 records out of "+rset_len+". Use 'Export' to see all records");rset_len=1000;}
|
||||
for(var vi=0;vi<rset_len;vi++){var row=this.tab.insertRow(vi);if(this.has_index){var c0=row.insertCell(0);$w(c0,'30px');$a(c0,'div','',{width:'23px'}).innerHTML=start;}
|
||||
start++;for(var ci=0;ci<this.rset[vi].length;ci++){this.make_data_cell(vi,ci,this.rset[vi][ci]);}
|
||||
if(this.afterrowprint){row.data_cells={};row.data={};for(var ci=0;ci<this.colnames.length;ci++){row.data[this.colnames[ci]]=this.rset[vi][ci];row.data_cells[this.colnames[ci]]=row.cells[ci+1];}f
|
||||
this.afterrowprint(row);}}
|
||||
if(this.rset.length&&this.rset.length>=this.page_len)this.has_next=true;if(r.style){for(var i=0;i<r.style.length;i++){$yt(this.tab,r.style[i][0],r.style[i][1],r.style[i][2]);}}
|
||||
if(this.aftertableprint)this.aftertableprint(this.tab);}else{$ds(this.no_data_tag);}}
|
||||
_r.DataTable.prototype.get_col_width=function(i){if(this.colwidths&&this.colwidths.length&&this.colwidths[i])
|
||||
return cint(this.colwidths[i])+'px';else return'100px';}
|
||||
_r.DataTable.prototype.make_head_tab=function(colnames){var r0=this.htab.insertRow(0);if(this.has_index){var c0=r0.insertCell(0);c0.className='report_head_cell';$w(c0,'30px');$a(c0,'div').innerHTML='Sr';this.total_width=30;}
|
||||
for(var i=0;i<colnames.length;i++){var w=this.get_col_width(i);this.total_width+=cint(w);var c=r0.insertCell(r0.cells.length);c.className='report_head_cell';if(w)$w(c,w);$a(c,'div').innerHTML=colnames[i];c.val=colnames[i];}
|
||||
$w(this.htab,this.total_width+'px');$w(this.tab,this.total_width+'px');}
|
||||
_r.DataTable.prototype.make_data_cell=function(ri,ci,val){var row=this.tab.rows[ri];var c=row.insertCell(row.cells.length);if(row.style.color)
|
||||
c.style.color=row.style.color;if(row.style.backgroundColor)
|
||||
c.style.backgroundColor=row.style.backgroundColor;if(row.style.fontWeight)
|
||||
c.style.fontWeight=row.style.fontWeight;if(row.style.fontSize)
|
||||
c.style.fontSize=row.style.fontSize;var w=this.get_col_width(ci);if(w)$w(c,w);c.val=val;var me=this;c.div=$a(c,'div','',{width:(cint(w)-7)+'px'});$s(c.div,val,this.coltypes[ci],this.coloptions[ci])}
|
||||
_r.DataTable.prototype.do_print=function(){this._get_query(true);args={query:this.query,title:this.rep_name?this.rep_name:this.dt,colnames:null,colwidhts:null,coltypes:null,has_index:this.has_index,has_headings:this.has_headings,check_limit:1,is_simple:(this.is_simple?'Yes':''),sc_id:(this.search_criteria?this.search_criteria.name:''),filter_values:docstring(this.filter_vals),finder:this.finder?this.finder:null};wn.require('js/print_query.js');_p.print_query=new _p.PrintQuery();_p.print_query.show_dialog(args);}
|
||||
_r.DataTable.prototype.do_export=function(){this._get_query(true);var me=this;export_query(this.query,function(q){export_csv(q,(me.rep_name?me.rep_name:me.dt),(me.search_criteria?me.search_criteria.name:''),me.is_simple,docstring(me.filter_vals));});}
|
||||
_r.DataTable.prototype.do_calc=function(){_r.show_calc(this.tab,this.colnames,this.coltypes,1);}
|
||||
_r.DataTable.prototype.get_col_data=function(colname){var ci=0;if(!this.htab)return[];for(var i=1;i<this.htab.rows[0].cells.length;i++){var hc=this.htab.rows[0].cells[i];if(hc.val==colname){ci=i;break;}}
|
||||
var ret=[];for(var ri=0;ri<this.tab.rows.length;ri++){ret[ret.length]=this.tab.rows[ri].cells[ci].val;}
|
||||
return ret;}
|
||||
_r.DataTable.prototype.get_html=function(){var w=document.createElement('div');w=$a(w,'div');w.style.marginTop='16px';var tab=$a(w,'table');var add_head_style=function(c,w){c.style.fontWeight='bold';c.style.border='1px solid #000';c.style.padding='2px';if(w)$w(c,w);return c;}
|
||||
var add_cell_style=function(c){c.style.padding='2px';c.style.border='1px solid #000';return c;}
|
||||
tab.style.borderCollapse='collapse';var hr=tab.insertRow(0);var c0=add_head_style(hr.insertCell(0),'30px');c0.innerHTML='Sr';for(var i=1;i<this.htab.rows[0].cells.length;i++){var hc=this.htab.rows[0].cells[i];var c=add_head_style(hr.insertCell(i),hc.style.width);c.innerHTML=hc.innerHTML;}
|
||||
for(var ri=0;ri<this.tab.rows.length;ri++){var row=this.tab.rows[ri];var dt_row=tab.insertRow(tab.rows.length);for(var ci=0;ci<row.cells.length;ci++){var c=add_cell_style(dt_row.insertCell(ci));c.innerHTML=row.cells[ci].innerHTML;}}
|
||||
return w.innerHTML;}
|
||||
/*
|
||||
* lib/js/legacy/widgets/report_builder/calculator.js
|
||||
*/
|
||||
_r.calc_dialog=null;_r.show_calc=function(tab,colnames,coltypes,add_idx){if(!add_idx)add_idx=0;if(!tab||!tab.rows.length){msgprint("No Data");return;}
|
||||
if(!_r.calc_dialog){var d=new Dialog(400,400,"Calculator")
|
||||
d.make_body([['Select','Column'],['Data','Sum'],['Data','Average'],['Data','Min'],['Data','Max']])
|
||||
d.widgets['Sum'].readonly='readonly';d.widgets['Average'].readonly='readonly';d.widgets['Min'].readonly='readonly';d.widgets['Max'].readonly='readonly';d.widgets['Column'].onchange=function(){d.set_calc();}
|
||||
d.set_calc=function(){var cn=sel_val(this.widgets['Column']);var cidx=0;var sum=0;var avg=0;var minv=null;var maxv=null;for(var i=0;i<this.colnames.length;i++){if(this.colnames[i]==cn){cidx=i+add_idx;break;}}
|
||||
for(var i=0;i<this.datatab.rows.length;i++){var c=this.datatab.rows[i].cells[cidx];var v=c.div?flt(c.div.innerHTML):flt(c.innerHTML);sum+=v;if(minv==null)minv=v;if(maxv==null)maxv=v;if(v>maxv)maxv=v;if(v<minv)minv=v;}
|
||||
d.widgets['Sum'].value=fmt_money(sum);d.widgets['Average'].value=fmt_money(sum/this.datatab.rows.length);d.widgets['Min'].value=fmt_money(minv);d.widgets['Max'].value=fmt_money(maxv);_r.calc_dialog=d;}
|
||||
d.onshow=function(){var cl=[];for(var i in _r.calc_dialog.colnames){if(in_list(['Currency','Int','Float'],_r.calc_dialog.coltypes[i]))
|
||||
cl.push(_r.calc_dialog.colnames[i]);}
|
||||
if(!cl.length){this.hide();alert("No Numeric Column");return;}
|
||||
var s=this.widgets['Column'];empty_select(s);add_sel_options(s,cl);if(s.inp)s.inp.value=cl[0];else s.value=cl[0];this.set_calc();}
|
||||
_r.calc_dialog=d;}
|
||||
_r.calc_dialog.datatab=tab;_r.calc_dialog.colnames=colnames;_r.calc_dialog.coltypes=coltypes;_r.calc_dialog.show();}
|
||||
|
|
@ -76,7 +76,9 @@ wn.datetime = {
|
|||
},
|
||||
|
||||
add_days: function(d, days) {
|
||||
d.setTime(d.getTime()+(days*24*60*60*1000)); return d
|
||||
dt = dateutil.str_to_obj(d)
|
||||
dt.setTime(dt.getTime()+(days*24*60*60*1000));
|
||||
return dateutil.obj_to_str(dt);
|
||||
},
|
||||
|
||||
add_months: function(d, months) {
|
||||
|
|
@ -222,16 +224,18 @@ wn.datetime.only_date = function(val) {
|
|||
wn.datetime.time_to_ampm = function(v) {
|
||||
if(!v) {
|
||||
var d = new Date();
|
||||
var t = [d.getHours(), cint(d.getMinutes()/5)*5]
|
||||
var t = [d.getHours(), cint(d.getMinutes()/5)*5 + '']
|
||||
} else {
|
||||
var t = v.split(':');
|
||||
}
|
||||
|
||||
|
||||
|
||||
if(t.length!=2){
|
||||
show_alert('[set_time] Incorect time format');
|
||||
return;
|
||||
}
|
||||
|
||||
if(t[1].length==1) t[1]='0' + t[1];
|
||||
|
||||
if(cint(t[0]) == 0) var ret = ['12', t[1], 'AM'];
|
||||
else if(cint(t[0]) < 12) var ret = [cint(t[0]) + '', t[1], 'AM'];
|
||||
else if(cint(t[0]) == 12) var ret = ['12', t[1], 'PM'];
|
||||
|
|
@ -246,6 +250,9 @@ wn.datetime.time_to_hhmm = function(hh,mm,am) {
|
|||
} else if(am == 'PM' && hh!='12') {
|
||||
hh = cint(hh) + 12;
|
||||
}
|
||||
if(!mm) mm='00';
|
||||
if(!hh) hh='00';
|
||||
|
||||
return hh + ':' + mm;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -338,59 +338,6 @@ function $td(t,r,c) {
|
|||
if(c<0)c=t.rows[0].cells.length+c;
|
||||
return t.rows[r].cells[c];
|
||||
}
|
||||
// sum of values in a table column
|
||||
function $sum(t, cidx) {
|
||||
var s = 0;
|
||||
if(cidx<1)cidx = t.rows[0].cells.length + cidx;
|
||||
for(var ri=0; ri<t.rows.length; ri++) {
|
||||
var c = t.rows[ri].cells[cidx];
|
||||
if(c.div) s += flt(c.div.innerHTML);
|
||||
else if(c.value) s+= flt(c.value);
|
||||
else s += flt(c.innerHTML);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function objpos(obj){
|
||||
if(obj.substr)obj = $i(obj);
|
||||
var p = $(obj).offset();
|
||||
return {x : cint(p.left), y : cint(p.top) }
|
||||
}
|
||||
|
||||
|
||||
function get_screen_dims() {
|
||||
var d={};
|
||||
d.w = 0; d.h = 0;
|
||||
if( typeof( window.innerWidth ) == 'number' ) {
|
||||
//Non-IE
|
||||
d.w = window.innerWidth;
|
||||
d.h = window.innerHeight;
|
||||
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
|
||||
//IE 6+ in 'standards compliant mode'
|
||||
d.w = document.documentElement.clientWidth;
|
||||
d.h = document.documentElement.clientHeight;
|
||||
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
|
||||
//IE 4 compatible
|
||||
d.w = document.body.clientWidth;
|
||||
d.h = document.body.clientHeight;
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// get full page size
|
||||
function get_page_size(){
|
||||
return [$(document).height(), $(document).width()];
|
||||
}
|
||||
|
||||
// get scroll top
|
||||
function get_scroll_top() {
|
||||
var st = 0;
|
||||
if(document.documentElement && document.documentElement.scrollTop)
|
||||
st = document.documentElement.scrollTop;
|
||||
else if(document.body && document.body.scrollTop)
|
||||
st = document.body.scrollTop;
|
||||
return st;
|
||||
}
|
||||
|
||||
// URL utilities
|
||||
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ function $c(command, args, callback, error, no_spinner, freeze_msg, btn) {
|
|||
// For calling an object
|
||||
function $c_obj(doclist, method, arg, callback, no_spinner, freeze_msg, btn) {
|
||||
if(arg && typeof arg!='string') arg = JSON.stringify(arg);
|
||||
|
||||
|
||||
args = {
|
||||
cmd:'runserverobj',
|
||||
arg: arg,
|
||||
|
|
|
|||
|
|
@ -1,65 +0,0 @@
|
|||
// 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.
|
||||
//
|
||||
|
||||
var uploaders = {};
|
||||
var upload_frame_count = 0;
|
||||
|
||||
//
|
||||
// parent is the element in which you want to add the upload box
|
||||
// args - additional hidden arguments
|
||||
// callback - callback function to be called after upload with file id
|
||||
//
|
||||
Uploader = function(parent, args, callback) {
|
||||
var id = 'frame'+upload_frame_count; upload_frame_count++;
|
||||
this.callback = callback;
|
||||
|
||||
var div = $a(parent, 'div');
|
||||
div.innerHTML = '<iframe id="'+id+'" name="'+id+'" src="blank.html" \
|
||||
style="width:0px; height:0px; border:0px"></iframe>';
|
||||
|
||||
// upload form
|
||||
var div = $a(parent,'div');
|
||||
div.innerHTML = '<form method="POST" enctype="multipart/form-data" action="'+wn.request.url+'" target="'+id+'"></form>';
|
||||
var ul_form = div.childNodes[0];
|
||||
|
||||
var f_list = [];
|
||||
|
||||
// file data
|
||||
var inp_fdata = $a_input($a(ul_form,'span'),'file',{name:'filedata'},{marginLeft:'7px'});
|
||||
|
||||
if(!('cmd' in args)) { var inp = $a_input($a(ul_form,'span'),'hidden',{name:'cmd'}); inp.value = 'uploadfile'; }
|
||||
var inp = $a_input($a(ul_form,'span'),'hidden',{name:'uploader_id'}); inp.value = id;
|
||||
var inp = $a_input($a(ul_form,'span'),'submit',null,{marginLeft:'7px'}); inp.value = 'Upload';
|
||||
|
||||
$y(inp,{width:'80px'});
|
||||
|
||||
// dt, dn to show
|
||||
for(var key in args) {
|
||||
var inp = $a_input($a(ul_form,'span'),'hidden',{name:key}); inp.value = args[key];
|
||||
}
|
||||
|
||||
uploaders[id] = this;
|
||||
}
|
||||
|
||||
function upload_callback(id, fid) {
|
||||
uploaders[id].callback(fid);
|
||||
}
|
||||
|
|
@ -454,6 +454,9 @@ DataField.prototype.make_input = function() {
|
|||
response(r.results);
|
||||
}
|
||||
});
|
||||
},
|
||||
select: function(event, ui) {
|
||||
me.set(ui.item.value);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -1273,18 +1276,15 @@ _f.ButtonField.prototype.make_input = function() { var me = this;
|
|||
me.df.label, null,
|
||||
{fontWeight:'bold'}, null, 1)
|
||||
|
||||
this.input.onclick = function() {
|
||||
$(this.input).click(function() {
|
||||
if(me.not_in_form) return;
|
||||
this.disabled = 'disabled';
|
||||
|
||||
if(cur_frm.cscript[me.df.fieldname] && (!me.in_filter)) {
|
||||
cur_frm.runclientscript(me.df.fieldname, me.doctype, me.docname);
|
||||
this.disabled = false;
|
||||
} else {
|
||||
cur_frm.runscript(me.df.options, me);
|
||||
this.disabled = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
_f.ButtonField.prototype.hide = function() {
|
||||
|
|
|
|||
|
|
@ -865,7 +865,8 @@ _f.Frm.prototype.runscript = function(scriptname, callingfield, onrefresh) {
|
|||
// make doc list
|
||||
var doclist = compress_doclist(make_doclist(this.doctype, this.docname));
|
||||
// send to run
|
||||
if(callingfield)callingfield.input.disabled = true;
|
||||
if(callingfield)
|
||||
$(callingfield.input).set_working();
|
||||
|
||||
$c('runserverobj', {'docs':doclist, 'method':scriptname },
|
||||
function(r, rtxt) {
|
||||
|
|
@ -880,7 +881,8 @@ _f.Frm.prototype.runscript = function(scriptname, callingfield, onrefresh) {
|
|||
me.refresh_dependency();
|
||||
|
||||
// enable button
|
||||
if(callingfield)callingfield.input.done_working();
|
||||
if(callingfield)
|
||||
$(callingfield.input).done_working();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
|
@ -1113,10 +1115,12 @@ _f.set_value = function(dt, dn, fn, v) {
|
|||
d.__unsaved = 1;
|
||||
|
||||
if(d.parent && d.parenttype) {
|
||||
locals[d.parenttype][d.parent].__unsaved = 1;
|
||||
var doc = locals[d.parenttype][d.parent];
|
||||
doc.__unsaved = 1;
|
||||
var frm = wn.views.formview[d.parenttype].frm;
|
||||
} else {
|
||||
locals[d.doctype][d.name].__unsaved = 1;
|
||||
var doc = locals[d.doctype][d.name]
|
||||
doc.__unsaved = 1;
|
||||
var frm = wn.views.formview[d.doctype] && wn.views.formview[d.doctype].frm;
|
||||
}
|
||||
|
||||
|
|
@ -1124,7 +1128,7 @@ _f.set_value = function(dt, dn, fn, v) {
|
|||
// Just check if __unsaved was not set previously
|
||||
if(frm && frm==cur_frm && frm.frm_head && !prev_unsaved) {
|
||||
frm.frm_head.refresh_labels();
|
||||
frm.frm_head.refresh_toolbar();
|
||||
//frm.frm_head.refresh_toolbar();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -62,13 +62,18 @@ _f.FrmHeader = Class.extend({
|
|||
|
||||
this.set_label(labinfo);
|
||||
|
||||
// show update button if unsaved
|
||||
if(cur_frm.doc.__unsaved && cint(cur_frm.doc.docstatus)==1 && this.appframe.buttons['Update']) {
|
||||
this.appframe.buttons['Update'].toggle(true);
|
||||
}
|
||||
|
||||
},
|
||||
set_label: function(labinfo) {
|
||||
this.$w.find('.label-area').html(repl('<span class="label %(lab_class)s">\
|
||||
%(lab_status)s</span>', {
|
||||
lab_status: labinfo[0],
|
||||
lab_class: labinfo[1]
|
||||
}));
|
||||
}));
|
||||
},
|
||||
refresh_toolbar: function() {
|
||||
// clear
|
||||
|
|
|
|||
|
|
@ -80,13 +80,17 @@ wn.widgets.form.sidebar.Attachments = function(parent, sidebar, doctype, docname
|
|||
}
|
||||
this.dialog.body.innerHTML = '';
|
||||
this.dialog.show();
|
||||
|
||||
this.uploader = new Uploader(this.dialog.body, {
|
||||
from_form: 1,
|
||||
doctype: doctype,
|
||||
docname: docname,
|
||||
at_id: this.at_id
|
||||
}, wn.widgets.form.file_upload_done);
|
||||
|
||||
wn.upload.make({
|
||||
parent: this.dialog.body,
|
||||
args: {
|
||||
from_form: 1,
|
||||
doctype: doctype,
|
||||
docname: docname
|
||||
},
|
||||
callback: wn.widgets.form.file_upload_done
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
this.make();
|
||||
|
|
@ -140,9 +144,7 @@ wn.widgets.form.sidebar.Attachment = function(parent, filedet, frm) {
|
|||
// this function will be called after the upload is done
|
||||
// from webnotes.utils.file_manager
|
||||
wn.widgets.form.file_upload_done = function(doctype, docname, fileid, filename, at_id, new_timestamp) {
|
||||
|
||||
var at_id = cint(at_id);
|
||||
|
||||
|
||||
// add to file_list
|
||||
var doc = locals[doctype][docname];
|
||||
if(doc.file_list) {
|
||||
|
|
|
|||
|
|
@ -38,7 +38,7 @@ wn.Application = Class.extend({
|
|||
})
|
||||
} else {
|
||||
// clear sid cookie
|
||||
document.cookie = "sid=Guest;expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"
|
||||
//document.cookie = "sid=Guest;expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"
|
||||
this.startup();
|
||||
//wn.views.pageview.show(window.home_page);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,7 +30,8 @@ wn.dom = {
|
|||
},
|
||||
set_unique_id: function(ele) {
|
||||
var id = 'unique-' + wn.dom.id_count;
|
||||
ele.setAttribute('id', id);
|
||||
if(ele)
|
||||
ele.setAttribute('id', id);
|
||||
wn.dom.id_count++;
|
||||
return id;
|
||||
},
|
||||
|
|
@ -142,10 +143,10 @@ wn.dom.set_box_shadow = function(ele, spread) {
|
|||
}
|
||||
$.fn.set_working = function() {
|
||||
var ele = this.get(0);
|
||||
$(ele).attr('disabled', 'disabled');
|
||||
if(ele.loading_img) {
|
||||
$(ele.loading_img).toggle(true);
|
||||
} else {
|
||||
ele.disabled = 1;
|
||||
ele.loading_img = $('<img src="images/lib/ui/button-load.gif" \
|
||||
style="margin-left: 4px; margin-bottom: -2px; display: inline;" />')
|
||||
.insertAfter(ele);
|
||||
|
|
@ -153,7 +154,7 @@ wn.dom.set_box_shadow = function(ele, spread) {
|
|||
}
|
||||
$.fn.done_working = function() {
|
||||
var ele = this.get(0);
|
||||
ele.disabled = 0;
|
||||
$(ele).attr('disabled', null);
|
||||
if(ele.loading_img) {
|
||||
$(ele.loading_img).toggle(false);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ wn.request.url = 'index.cgi';
|
|||
wn.request.prepare = function(opts) {
|
||||
// btn indicator
|
||||
if(opts.btn) $(opts.btn).set_working();
|
||||
|
||||
|
||||
// navbar indicator
|
||||
if(opts.show_spinner) set_loading();
|
||||
|
||||
|
|
|
|||
|
|
@ -30,7 +30,6 @@ wn.ui.Button = function(args) {
|
|||
// ajax loading
|
||||
me.loading_img = wn.dom.add(me.btn.args.parent,'img','',{margin:'0px 4px -2px 4px', display:'none'});
|
||||
me.loading_img.src= 'images/lib/ui/button-load.gif';
|
||||
if(args.is_ajax) wn.dom.css(me.btn,{marginRight:'24px'});
|
||||
|
||||
// label
|
||||
me.btn.innerHTML = args.label;
|
||||
|
|
@ -53,17 +52,11 @@ wn.ui.Button = function(args) {
|
|||
|
||||
set_working: function() {
|
||||
me.btn.disabled = 'disabled';
|
||||
if(me.btn.args.is_ajax) {
|
||||
$(me.btn).css('margin-right', '0px');
|
||||
}
|
||||
$(me.loading_img).css('display','inline');
|
||||
},
|
||||
|
||||
done_working: function() {
|
||||
me.btn.disabled = false;
|
||||
if(me.btn.args.is_ajax) {
|
||||
$(me.btn).css('margin-right', '24px');
|
||||
}
|
||||
$(me.loading_img).toggle(false);
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -137,10 +137,8 @@ wn.widgets.Dialog = function(opts) {
|
|||
|
||||
this.set_postion = function() {
|
||||
// place it at the center
|
||||
var d = get_screen_dims();
|
||||
|
||||
this.wrapper.style.left = ((d.w - cint(this.wrapper.style.width))/2) + 'px';
|
||||
this.wrapper.style.top = (get_scroll_top() + 60) + 'px';
|
||||
this.wrapper.style.left = (($(window).width() - cint(this.wrapper.style.width))/2) + 'px';
|
||||
this.wrapper.style.top = ($(window).scrollTop() + 60) + 'px';
|
||||
|
||||
// place it on top
|
||||
top_index++;
|
||||
|
|
|
|||
2
js/wn/ui/toolbar.min.js
vendored
2
js/wn/ui/toolbar.min.js
vendored
|
|
@ -16,7 +16,7 @@ wn.ui.toolbar.Search=wn.ui.toolbar.SelectorDialog.extend({init:function(){this._
|
|||
/*
|
||||
* lib/js/wn/ui/toolbar/report.js
|
||||
*/
|
||||
wn.ui.toolbar.Report=wn.ui.toolbar.SelectorDialog.extend({init:function(){this._super({title:"Start Report For",execute:function(val){loadreport(val,null,null,null,1);},});this.set_values(profile.can_get_report.join(',').split(','));}});
|
||||
wn.ui.toolbar.Report=wn.ui.toolbar.SelectorDialog.extend({init:function(){this._super({title:"Start Report For",execute:function(val){wn.set_route('Report2',val);},});this.set_values(profile.can_get_report.join(',').split(','));}});
|
||||
/*
|
||||
* lib/js/wn/ui/toolbar/recent.js
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ wn.ui.toolbar.Report = wn.ui.toolbar.SelectorDialog.extend({
|
|||
this._super({
|
||||
title: "Start Report For",
|
||||
execute: function(val) {
|
||||
loadreport(val, null, null, null, 1);
|
||||
wn.set_route('Report2', val);
|
||||
},
|
||||
});
|
||||
|
||||
|
|
|
|||
34
js/wn/upload.js
Normal file
34
js/wn/upload.js
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
// parent, args, callback
|
||||
wn.upload = {
|
||||
make: function(opts) {
|
||||
var id = wn.dom.set_unique_id();
|
||||
$(opts.parent).append(repl('<iframe id="%(id)s" name="%(id)s" src="blank.html" \
|
||||
style="width:0px; height:0px; border:0px"></iframe>\
|
||||
<form method="POST" enctype="multipart/form-data" \
|
||||
action="%(action)s" target="%(id)s">\
|
||||
<input type="file" name="filedata" /><br><br>\
|
||||
<input type="submit" class="btn btn-small" value="Upload" />\
|
||||
</form>', {
|
||||
id: id,
|
||||
action: wn.request.url
|
||||
}));
|
||||
|
||||
opts.args.cmd = 'uploadfile';
|
||||
opts.args._id = id;
|
||||
|
||||
// add request parameters
|
||||
for(key in opts.args) {
|
||||
if(opts.args[key]) {
|
||||
$('<input type="hidden">')
|
||||
.attr('name', key)
|
||||
.attr('value', opts.args[key])
|
||||
.appendTo($(opts.parent).find('form'));
|
||||
}
|
||||
}
|
||||
|
||||
$('#' + id).get(0).callback = opts.callback
|
||||
},
|
||||
callback: function(id, file_id, args) {
|
||||
$('#' + id).get(0).callback(file_id, args);
|
||||
}
|
||||
}
|
||||
|
|
@ -64,36 +64,59 @@ wn.views.reportview2 = {
|
|||
} else {
|
||||
var route = wn.get_route();
|
||||
if(route[1]) {
|
||||
new wn.views.ReportView(route[1], route[2]);
|
||||
new wn.views.ReportViewPage(route[1], route[2]);
|
||||
} else {
|
||||
new wn.views.ReportHome();
|
||||
wn.set_route('404');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
wn.views.ReportView = wn.ui.Listing.extend({
|
||||
wn.views.ReportViewPage = Class.extend({
|
||||
init: function(doctype, docname) {
|
||||
var me = this;
|
||||
this.doctype = doctype;
|
||||
this.docname = docname;
|
||||
this.page_name = wn.get_route_str();
|
||||
this.make_page();
|
||||
|
||||
var me = this;
|
||||
wn.model.with_doctype(doctype, function() {
|
||||
me.make_report_view();
|
||||
if(docname) {
|
||||
wn.model.with_doc('Report', docname, function(r) {
|
||||
me.reportview.set_columns_and_filters(JSON.parse(locals['Report'][docname].json));
|
||||
me.reportview.run();
|
||||
});
|
||||
} else {
|
||||
me.reportview.run();
|
||||
}
|
||||
});
|
||||
|
||||
},
|
||||
make_page: function() {
|
||||
this.page = wn.container.add_page(this.page_name);
|
||||
wn.ui.make_app_page({parent:this.page,
|
||||
single_column:true});
|
||||
wn.container.change_to(this.page_name);
|
||||
},
|
||||
make_report_view: function() {
|
||||
// add breadcrumbs
|
||||
wn.views.breadcrumbs($('<span>').appendTo(this.page.appframe.$titlebar),
|
||||
locals.DocType[this.doctype].module);
|
||||
|
||||
this.reportview = new wn.views.ReportView(this.doctype, this.docname, this.page)
|
||||
}
|
||||
})
|
||||
|
||||
wn.views.ReportView = wn.ui.Listing.extend({
|
||||
init: function(doctype, docname, page) {
|
||||
var me = this;
|
||||
this.import_slickgrid();
|
||||
this.doctype = doctype;
|
||||
this.docname = docname;
|
||||
this.page = page;
|
||||
this.tab_name = '`tab'+doctype+'`';
|
||||
|
||||
// list of [column_name, table_name]
|
||||
this.make_page();
|
||||
wn.model.with_doctype(doctype, function() {
|
||||
me.setup();
|
||||
if(docname) {
|
||||
wn.model.with_doc('Report', docname, function(r) {
|
||||
me.set_columns_and_filters(JSON.parse(locals['Report'][docname].json));
|
||||
me.run();
|
||||
});
|
||||
} else {
|
||||
me.run();
|
||||
}
|
||||
});
|
||||
this.setup();
|
||||
},
|
||||
import_slickgrid: function() {
|
||||
wn.require('js/lib/slickgrid/slick.grid.css');
|
||||
|
|
@ -103,12 +126,7 @@ wn.views.ReportView = wn.ui.Listing.extend({
|
|||
wn.require('js/lib/slickgrid/slick.grid.js');
|
||||
wn.dom.set_style('.slick-cell { font-size: 12px; }');
|
||||
},
|
||||
make_page: function() {
|
||||
this.page = wn.container.add_page(this.page_name);
|
||||
wn.ui.make_app_page({parent:this.page,
|
||||
single_column:true});
|
||||
wn.container.change_to(this.page_name);
|
||||
},
|
||||
|
||||
set_init_columns: function() {
|
||||
// pre-select mandatory columns
|
||||
var columns = [['name'], ['owner']];
|
||||
|
|
@ -121,8 +139,6 @@ wn.views.ReportView = wn.ui.Listing.extend({
|
|||
},
|
||||
setup: function() {
|
||||
var me = this;
|
||||
wn.views.breadcrumbs($('<span>').appendTo(this.page.appframe.$titlebar),
|
||||
locals.DocType[this.doctype].module);
|
||||
this.make({
|
||||
title: 'Report: ' + (this.docname ? (this.doctype + ' - ' + this.docname) : this.doctype),
|
||||
appframe: this.page.appframe,
|
||||
|
|
@ -203,9 +219,7 @@ wn.views.ReportView = wn.ui.Listing.extend({
|
|||
name: (docfield ? docfield.label : toTitle(c[0])),
|
||||
width: (docfield ? cint(docfield.width) : 120) || 120
|
||||
}
|
||||
|
||||
console.log(docfield && docfield.width);
|
||||
|
||||
|
||||
if(c[0]=='name') {
|
||||
coldef.formatter = function(row, cell, value, columnDef, dataContext) {
|
||||
return repl("<a href='#!Form/%(doctype)s/%(name)s'>%(name)s</a>", {
|
||||
|
|
|
|||
|
|
@ -3,9 +3,9 @@
|
|||
|
||||
# These values are common in all dictionaries
|
||||
{
|
||||
'creation': '2012-03-27 14:35:35',
|
||||
'creation': '2012-03-27 14:35:36',
|
||||
'docstatus': 0,
|
||||
'modified': '2012-03-27 14:35:35',
|
||||
'modified': '2012-03-27 14:35:36',
|
||||
'modified_by': u'Administrator',
|
||||
'owner': u'Administrator'
|
||||
},
|
||||
|
|
@ -173,7 +173,7 @@
|
|||
'no_copy': 0,
|
||||
'oldfieldname': u'fieldtype',
|
||||
'oldfieldtype': u'Select',
|
||||
'options': u'\nButton\nCheck\nColumn Break\nCurrency\nData\nDate\nFloat\nHTML\nInt\nLink\nRead Only\nSection Break\nSelect\nSmall Text\nText\nText Editor\nTime',
|
||||
'options': u'\nButton\nCheck\nColumn Break\nCurrency\nData\nDate\nFloat\nHTML\nInt\nLink\nRead Only\nSection Break\nSelect\nSmall Text\nText\nText Editor\nTime\nTable',
|
||||
'permlevel': 0,
|
||||
'reqd': 1,
|
||||
'search_index': 0,
|
||||
|
|
|
|||
|
|
@ -75,6 +75,7 @@ class DocType:
|
|||
fieldnames = {}
|
||||
illegal = ['.', ',', ' ', '-', '&', '%', '=', '"', "'", '*', '$']
|
||||
for d in self.doclist:
|
||||
if not d.permlevel: d.permlevel = 0
|
||||
if d.parent and d.fieldtype and d.parent == self.doc.name:
|
||||
# check if not double
|
||||
if d.fieldname:
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ import webnotes
|
|||
|
||||
from webnotes.utils import cint, cstr, default_fields, flt, formatdate, get_defaults, getdate, now, nowdate, replace_newlines, set_default
|
||||
from webnotes.model import db_exists, default_fields
|
||||
from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
|
||||
from webnotes.model.doc import Document, addchild, getchildren, make_autoname
|
||||
from webnotes.model.doclist import getlist
|
||||
from webnotes.model.code import get_obj
|
||||
from webnotes import session, form, msgprint, errprint
|
||||
|
|
|
|||
|
|
@ -40,6 +40,8 @@ class DocType():
|
|||
if not '.' in self.doc.file_name:
|
||||
raise Exception, 'file name must have extension (.)'
|
||||
|
||||
self.doc.file_name = self.doc.file_name.replace('-', '')
|
||||
|
||||
parts = self.doc.file_name.split('.')
|
||||
|
||||
same = webnotes.conn.sql("""select name from `tabFile Data`
|
||||
|
|
|
|||
5
py/core/doctype/print_format/print_format.js
Normal file
5
py/core/doctype/print_format/print_format.js
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
cur_frm.cscript.refresh = function(doc, dt, dn) {
|
||||
if (doc.standard == 'Yes') {
|
||||
set_field_permlevel('html', 1);
|
||||
}
|
||||
}
|
||||
|
|
@ -3,9 +3,9 @@
|
|||
|
||||
# These values are common in all dictionaries
|
||||
{
|
||||
'creation': '2012-04-02 16:01:07',
|
||||
'creation': '2012-05-15 12:14:24',
|
||||
'docstatus': 0,
|
||||
'modified': '2012-05-03 09:55:18',
|
||||
'modified': '2012-05-16 13:29:26',
|
||||
'modified_by': u'Administrator',
|
||||
'owner': u'Administrator'
|
||||
},
|
||||
|
|
@ -49,25 +49,17 @@
|
|||
'name': '__common__',
|
||||
'parent': u'Print Format',
|
||||
'parentfield': u'fields',
|
||||
'parenttype': u'DocType',
|
||||
'permlevel': 0
|
||||
'parenttype': u'DocType'
|
||||
},
|
||||
|
||||
# These values are common for all DocPerm
|
||||
{
|
||||
'cancel': 0,
|
||||
'create': 1,
|
||||
'doctype': u'DocPerm',
|
||||
'execute': 0,
|
||||
'name': '__common__',
|
||||
'parent': u'Print Format',
|
||||
'parentfield': u'permissions',
|
||||
'parenttype': u'DocType',
|
||||
'permlevel': 0,
|
||||
'read': 1,
|
||||
'role': u'Administrator',
|
||||
'submit': 0,
|
||||
'write': 1
|
||||
'read': 1
|
||||
},
|
||||
|
||||
# DocType, Print Format
|
||||
|
|
@ -78,7 +70,41 @@
|
|||
|
||||
# DocPerm
|
||||
{
|
||||
'doctype': u'DocPerm'
|
||||
'amend': 0,
|
||||
'cancel': 0,
|
||||
'create': 1,
|
||||
'doctype': u'DocPerm',
|
||||
'permlevel': 0,
|
||||
'role': u'System Manager',
|
||||
'submit': 0,
|
||||
'write': 1
|
||||
},
|
||||
|
||||
# DocPerm
|
||||
{
|
||||
'cancel': 0,
|
||||
'create': 1,
|
||||
'doctype': u'DocPerm',
|
||||
'execute': 0,
|
||||
'permlevel': 0,
|
||||
'role': u'Administrator',
|
||||
'submit': 0,
|
||||
'write': 1
|
||||
},
|
||||
|
||||
# DocPerm
|
||||
{
|
||||
'doctype': u'DocPerm',
|
||||
'permlevel': 1,
|
||||
'role': u'System Manager'
|
||||
},
|
||||
|
||||
# DocPerm
|
||||
{
|
||||
'doctype': u'DocPerm',
|
||||
'permlevel': 1,
|
||||
'role': u'Administrator',
|
||||
'write': 1
|
||||
},
|
||||
|
||||
# DocField
|
||||
|
|
@ -94,6 +120,7 @@
|
|||
'oldfieldname': u'module',
|
||||
'oldfieldtype': u'Select',
|
||||
'options': u'link:Module Def',
|
||||
'permlevel': 0,
|
||||
'print_hide': 0,
|
||||
'report_hide': 0,
|
||||
'reqd': 1,
|
||||
|
|
@ -109,6 +136,7 @@
|
|||
'in_filter': 1,
|
||||
'label': u'DocType',
|
||||
'options': u'link:DocType',
|
||||
'permlevel': 0,
|
||||
'reqd': 0,
|
||||
'search_index': 0
|
||||
},
|
||||
|
|
@ -116,16 +144,19 @@
|
|||
# DocField
|
||||
{
|
||||
'allow_on_submit': 0,
|
||||
'colour': u'White:FFF',
|
||||
'default': u'No',
|
||||
'doctype': u'DocField',
|
||||
'fieldname': u'standard',
|
||||
'fieldtype': u'Select',
|
||||
'hidden': 0,
|
||||
'in_filter': 1,
|
||||
'label': u'Standard',
|
||||
'no_copy': 0,
|
||||
'no_copy': 1,
|
||||
'oldfieldname': u'standard',
|
||||
'oldfieldtype': u'Select',
|
||||
'options': u'\nYes\nNo',
|
||||
'options': u'No\nYes',
|
||||
'permlevel': 1,
|
||||
'print_hide': 0,
|
||||
'report_hide': 0,
|
||||
'reqd': 1,
|
||||
|
|
@ -145,6 +176,7 @@
|
|||
'oldfieldname': u'html',
|
||||
'oldfieldtype': u'Text Editor',
|
||||
'options': u'HTML',
|
||||
'permlevel': 0,
|
||||
'print_hide': 0,
|
||||
'report_hide': 0,
|
||||
'reqd': 0,
|
||||
|
|
|
|||
0
py/core/page/data_import_tool/__init__.py
Normal file
0
py/core/page/data_import_tool/__init__.py
Normal file
5
py/core/page/data_import_tool/data_import_tool.css
Normal file
5
py/core/page/data_import_tool/data_import_tool.css
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
.float-column {
|
||||
width: 40%;
|
||||
float: left;
|
||||
margin-right: 9%;
|
||||
}
|
||||
0
py/core/page/data_import_tool/data_import_tool.html
Normal file
0
py/core/page/data_import_tool/data_import_tool.html
Normal file
130
py/core/page/data_import_tool/data_import_tool.js
Normal file
130
py/core/page/data_import_tool/data_import_tool.js
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
wn.pages['data-import-tool'].onload = function(wrapper) {
|
||||
wrapper.app_page = wn.ui.make_app_page({
|
||||
parent: wrapper,
|
||||
title: "Data Import Tool"
|
||||
});
|
||||
|
||||
$(wrapper).find('.layout-main-section').append('<h3>1. Download Template</h3>\
|
||||
<div style="min-height: 150px">\
|
||||
<p class="help">Download a template for importing a table.</p>\
|
||||
<p class="float-column">\
|
||||
<select style="width: 200px" name="dit-doctype">\
|
||||
</select><br><br>\
|
||||
<input type="checkbox" name="dit-with-data">\
|
||||
<span> Download with data</span>\
|
||||
</p>\
|
||||
<p class="float-column" id="dit-download"></p>\
|
||||
</div>\
|
||||
<hr>\
|
||||
<h3>2. Import Data</h3>\
|
||||
<p class="help">Attach .csv file to import data</p>\
|
||||
<div id="dit-upload-area"></div><br>\
|
||||
<p id="dit-output"></p>\
|
||||
');
|
||||
|
||||
$(wrapper).find('.layout-side-section').append('<h4>Help</h4><br>\
|
||||
<p><b>Date Format:</b></p>\
|
||||
<p>Dates must be in format "YYYY-MM-DD", for example, \
|
||||
31st Jan 2012 must be "2012-01-31"</p>\
|
||||
<p><b>Importing non-English data:</b></p>\
|
||||
<p>While uploading non English files ensure that the encoding is UTF-8.</p>\
|
||||
<p>Microsoft Excel Users:\
|
||||
<ol>\
|
||||
<li>In Excel, save the file in CSV (Comma Delimited) format</li>\
|
||||
<li>Open this saved file in Notepad</li>\
|
||||
<li>Click on File -> Save As</li>\
|
||||
<li>File Name: <your filename>.csv<br />\
|
||||
Save as type: Text Documents (*.txt)<br />\
|
||||
Encoding: UTF-8\
|
||||
</li>\
|
||||
<li>Click on Save</li>\
|
||||
</ol>\
|
||||
</p>')
|
||||
|
||||
$select = $(wrapper).find('[name="dit-doctype"]');
|
||||
|
||||
// load doctypes
|
||||
wn.call({
|
||||
method:'core.page.data_import_tool.data_import_tool.get_doctypes',
|
||||
callback: function(r) {
|
||||
$select.add_options(['Select...'].concat(r.message));
|
||||
}
|
||||
});
|
||||
|
||||
// load options
|
||||
$select.change(function() {
|
||||
var val = $(this).val()
|
||||
if(val!='Select...') {
|
||||
$('#dit-download').empty();
|
||||
|
||||
// get options
|
||||
wn.call({
|
||||
method:'core.page.data_import_tool.data_import_tool.get_doctype_options',
|
||||
args: {doctype: val},
|
||||
callback: function(r) {
|
||||
$('<h4>Select Template:</h4>').appendTo('#dit-download');
|
||||
var with_data = $('[name="dit-with-data"]:checked').length ? 'Yes' : 'No';
|
||||
// download link
|
||||
$.each(r.message, function(i, v) {
|
||||
if(i==0)
|
||||
$('<span>Main Table:</span><br>').appendTo('#dit-download');
|
||||
if(i==1)
|
||||
$('<br><span>Child Tables:</span><br>').appendTo('#dit-download');
|
||||
$('<a style="cursor: pointer">')
|
||||
.html(v)
|
||||
.data('doctype', v)
|
||||
.click(function() {
|
||||
window.location.href = repl(wn.request.url
|
||||
+ '?cmd=%(cmd)s&doctype=%(doctype)s'
|
||||
+ '&parent_doctype=%(parent_doctype)s&with_data=%(with_data)s',
|
||||
{
|
||||
cmd: 'core.page.data_import_tool.data_import_tool.get_template',
|
||||
doctype: $(this).data('doctype'),
|
||||
parent_doctype: $('[name="dit-doctype"]').val(),
|
||||
with_data: $('[name="dit-with-data"]:checked').length ? 'Yes' : 'No'
|
||||
});
|
||||
})
|
||||
.appendTo('#dit-download');
|
||||
$('#dit-download').append('<br>');
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
|
||||
// upload
|
||||
wn.upload.make({
|
||||
parent: $('#dit-upload-area'),
|
||||
args: {
|
||||
method: 'core.page.data_import_tool.data_import_tool.upload'
|
||||
},
|
||||
callback: function(r) {
|
||||
$('#dit-output').empty();
|
||||
|
||||
$.each(r, function(i, v) {
|
||||
var $p = $('<p>').html(v).appendTo('#dit-output');
|
||||
if(v.substr(0,5)=='Error') {
|
||||
$p.css('color', 'red');
|
||||
}
|
||||
if(v.substr(0,8)=='Inserted') {
|
||||
$p.css('color', 'green');
|
||||
}
|
||||
if(v.substr(0,7)=='Updated') {
|
||||
$p.css('color', 'green');
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
// add overwrite option
|
||||
$('<input type="checkbox" name="overwrite"><span> Overwrite</span><br><br>')
|
||||
.insertBefore('#dit-upload-area form input[type="submit"]')
|
||||
|
||||
// rename button
|
||||
$('#dit-upload-area form input[type="submit"]')
|
||||
.attr('value', 'Upload and Import')
|
||||
.click(function() {
|
||||
$('#dit-output').html('Performing hardcore import process....')
|
||||
});
|
||||
}
|
||||
223
py/core/page/data_import_tool/data_import_tool.py
Normal file
223
py/core/page/data_import_tool/data_import_tool.py
Normal file
|
|
@ -0,0 +1,223 @@
|
|||
import webnotes
|
||||
|
||||
@webnotes.whitelist()
|
||||
def get_doctypes():
|
||||
return [r[0] for r in webnotes.conn.sql("""select name from `tabDocType`
|
||||
where document_type = 'Master'""")]
|
||||
|
||||
@webnotes.whitelist()
|
||||
def get_doctype_options():
|
||||
import webnotes
|
||||
doctype = webnotes.form_dict['doctype']
|
||||
import webnotes.model.doctype
|
||||
return [doctype] + filter(None, map(lambda d: \
|
||||
d.doctype=='DocField' and d.fieldtype=='Table' and d.options or None,
|
||||
webnotes.model.doctype.get(doctype, form=0)))
|
||||
|
||||
data_separator = '----Start entering data below this line----'
|
||||
|
||||
doctype_dl = None
|
||||
|
||||
@webnotes.whitelist(allow_roles=['System Manager', 'Administrator'])
|
||||
def get_template():
|
||||
import webnotes, csv
|
||||
from cStringIO import StringIO
|
||||
import webnotes.model.doctype
|
||||
global doctype_dl
|
||||
|
||||
doctype = webnotes.form_dict['doctype']
|
||||
parentdoctype = webnotes.form_dict.get('parent_doctype')
|
||||
|
||||
doctype_dl = webnotes.model.doctype.get(doctype)
|
||||
tablecolumns = [f[0] for f in webnotes.conn.sql('desc `tab%s`' % doctype)]
|
||||
|
||||
def getinforow(docfield):
|
||||
"""make info comment"""
|
||||
if docfield.fieldtype == 'Select':
|
||||
if docfield.options.startswith('link:'):
|
||||
return 'Valid %s' % docfield.options[5:]
|
||||
else:
|
||||
return 'One of: %s' % ', '.join(filter(None, docfield.options.split('\n')))
|
||||
if docfield.fieldtype == 'Link':
|
||||
return 'Valid %s' % docfield.options
|
||||
if docfield.fieldtype in ('Int'):
|
||||
return 'Integer'
|
||||
else:
|
||||
return ''
|
||||
|
||||
tobj = StringIO()
|
||||
w = csv.writer(tobj)
|
||||
key = 'name'
|
||||
|
||||
w.writerow(['Upload Template for: %s' % doctype])
|
||||
|
||||
if parentdoctype != doctype:
|
||||
w.writerow(['This is a child table for: %s' % parentdoctype])
|
||||
key = 'parent'
|
||||
else:
|
||||
w.writerow([''])
|
||||
|
||||
w.writerow(['----'])
|
||||
|
||||
fieldrow = ['Column Name:', key]
|
||||
mandatoryrow = ['Mandatory:', 'Yes']
|
||||
typerow = ['Type:', 'Data (text)']
|
||||
inforow = ['Info:', 'ID']
|
||||
columns = [key]
|
||||
|
||||
def append_row(t, mandatory):
|
||||
docfield = getdocfield(t)
|
||||
if docfield and ((mandatory and docfield.reqd) or (not mandatory and not docfield.reqd)) \
|
||||
and (t not in ('parenttype', 'trash_reason')):
|
||||
fieldrow.append(t)
|
||||
mandatoryrow.append(docfield.reqd and 'Yes' or 'No')
|
||||
typerow.append(docfield.fieldtype)
|
||||
inforow.append(getinforow(docfield))
|
||||
columns.append(t)
|
||||
|
||||
# get all mandatory fields
|
||||
for t in tablecolumns:
|
||||
append_row(t, True)
|
||||
|
||||
# all non mandatory fields
|
||||
for t in tablecolumns:
|
||||
append_row(t, False)
|
||||
|
||||
w.writerow(fieldrow)
|
||||
w.writerow(mandatoryrow)
|
||||
w.writerow(typerow)
|
||||
w.writerow(inforow)
|
||||
|
||||
w.writerow([data_separator])
|
||||
|
||||
if webnotes.form_dict.get('with_data')=='Yes':
|
||||
data = webnotes.conn.sql("""select * from `tab%s` where docstatus<2""" % doctype, as_dict=1)
|
||||
for d in data:
|
||||
row = ['']
|
||||
for c in columns:
|
||||
val = d.get(c, '')
|
||||
if type(val) is unicode:
|
||||
val = val.encode('utf-8')
|
||||
row.append(val)
|
||||
w.writerow(row)
|
||||
|
||||
# write out response as a type csv
|
||||
webnotes.response['result'] = tobj.getvalue()
|
||||
webnotes.response['type'] = 'csv'
|
||||
webnotes.response['doctype'] = doctype
|
||||
|
||||
def getdocfield(fieldname):
|
||||
"""get docfield from doclist of doctype"""
|
||||
l = [d for d in doctype_dl if d.doctype=='DocField' and d.fieldname==fieldname]
|
||||
return l and l[0] or None
|
||||
|
||||
@webnotes.whitelist(allow_roles=['System Manager', 'Administrator'])
|
||||
def upload():
|
||||
"""upload data"""
|
||||
import csv
|
||||
global doctype_dl
|
||||
from webnotes.utils.file_manager import get_uploaded_content
|
||||
import webnotes.model.doctype
|
||||
from webnotes.model.doc import Document
|
||||
|
||||
fname, fcontent = get_uploaded_content()
|
||||
overwrite = webnotes.form_dict.get('overwrite')
|
||||
|
||||
ret, rows = [], []
|
||||
try:
|
||||
reader = csv.reader(fcontent.splitlines())
|
||||
# decode everything
|
||||
for row in reader:
|
||||
rows.append([unicode(c.strip(), 'utf-8') for c in row])
|
||||
except Exception, e:
|
||||
webnotes.msgprint("Not a valid Comma Separated Value (CSV File)")
|
||||
raise e
|
||||
|
||||
|
||||
# doctype
|
||||
doctype = rows[0][0].split(':')[1].strip()
|
||||
doctype_dl = webnotes.model.doctype.get(doctype, form=0)
|
||||
|
||||
parentdoctype = None
|
||||
if len(rows[1]) > 0 and ':' in rows[1][0]:
|
||||
parentdoctype = rows[1][0].split(':')[1].strip()
|
||||
|
||||
# columns
|
||||
columns = rows[3][1:]
|
||||
|
||||
if parentdoctype and overwrite:
|
||||
delete_child_rows(rows, doctype)
|
||||
|
||||
for row in rows[8:]:
|
||||
d = dict(zip(columns, row[1:]))
|
||||
d['doctype'] = doctype
|
||||
|
||||
try:
|
||||
check_record(d, parentdoctype)
|
||||
if parentdoctype:
|
||||
# child doc
|
||||
doc = Document(doctype)
|
||||
doc.fields.update(d)
|
||||
doc.save()
|
||||
ret.append('Inserted row for %s at #%s' % (getlink(parentdoctype, doc.parent),
|
||||
str(doc.idx)))
|
||||
else:
|
||||
ret.append(import_doc(d, doctype, overwrite))
|
||||
except Exception, e:
|
||||
ret.append('Error for ' + row[1] + ': ' + str(e))
|
||||
webnotes.errprint(webnotes.getTraceback())
|
||||
return ret
|
||||
|
||||
def check_record(d, parentdoctype):
|
||||
"""check for mandatory, select options, dates. these should ideally be in doclist"""
|
||||
if parentdoctype and not d.get('parent'):
|
||||
raise Exception, "parent is required."
|
||||
|
||||
for key in d:
|
||||
docfield = getdocfield(key)
|
||||
val = d[key]
|
||||
if docfield:
|
||||
if docfield.reqd and (val=='' or val==None):
|
||||
raise Exception, "%s is mandatory." % key
|
||||
|
||||
if docfield.fieldtype=='Select':
|
||||
if docfield.options.startswith('link:'):
|
||||
if val:
|
||||
link_doctype = docfield.options.split(':')[1]
|
||||
if not webnotes.conn.exists(link_doctype, val):
|
||||
raise Exception, "%s must be a valid %s" % (key, link_doctype)
|
||||
else:
|
||||
if val not in docfield.options.split('\n'):
|
||||
raise Exception, "%s must be one of:" % key
|
||||
|
||||
if docfield.fieldtype=='Date' and val:
|
||||
import datetime
|
||||
datetime.datetime.strptime(val, '%Y-%m-%d')
|
||||
|
||||
def getlink(doctype, name):
|
||||
return '<a href="#Form/%(doctype)s/%(name)s">%(name)s</a>' % locals()
|
||||
|
||||
def delete_child_rows(rows, doctype):
|
||||
"""delete child rows for all parents"""
|
||||
import webnotes
|
||||
for p in list(set([r[1] for r in rows[8:]])):
|
||||
webnotes.conn.sql("""delete from `tab%s` where parent=%s""" % (doctype, '%s'), p)
|
||||
|
||||
def import_doc(d, doctype, overwrite):
|
||||
"""import main (non child) document"""
|
||||
import webnotes
|
||||
from webnotes.model.doc import Document
|
||||
from webnotes.model.doclist import DocList
|
||||
|
||||
if webnotes.conn.exists(doctype, d['name']):
|
||||
if overwrite:
|
||||
doc = Document(doctype, d['name'])
|
||||
doc.fields.update(d)
|
||||
DocList([doc]).save()
|
||||
return 'Updated ' + getlink(doctype, d['name'])
|
||||
else:
|
||||
return 'Ignored ' + getlink(doctype, d['name']) + ' (exists)'
|
||||
else:
|
||||
d['__islocal'] = 1
|
||||
DocList([Document(fielddata = d)]).save()
|
||||
return 'Inserted ' + getlink(doctype, d['name'])
|
||||
29
py/core/page/data_import_tool/data_import_tool.txt
Normal file
29
py/core/page/data_import_tool/data_import_tool.txt
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
# Page, data-import-tool
|
||||
[
|
||||
|
||||
# These values are common in all dictionaries
|
||||
{
|
||||
'creation': '2012-05-10 10:06:00',
|
||||
'docstatus': 0,
|
||||
'modified': '2012-05-10 10:06:00',
|
||||
'modified_by': u'Administrator',
|
||||
'owner': u'Administrator'
|
||||
},
|
||||
|
||||
# These values are common for all Page
|
||||
{
|
||||
'doctype': 'Page',
|
||||
'module': u'Core',
|
||||
'name': '__common__',
|
||||
'page_name': u'Data Import Tool',
|
||||
'standard': u'Yes',
|
||||
'title': u'Data Import Tool',
|
||||
'web_page': u'No'
|
||||
},
|
||||
|
||||
# Page, data-import-tool
|
||||
{
|
||||
'doctype': 'Page',
|
||||
'name': u'data-import-tool'
|
||||
}
|
||||
]
|
||||
|
|
@ -95,7 +95,7 @@ def msgprint(msg, small=0, raise_exception=0, as_table=False):
|
|||
|
||||
message_log.append((small and '__small:' or '')+cstr(msg or ''))
|
||||
if raise_exception:
|
||||
raise ValidationError
|
||||
raise ValidationError, msg
|
||||
|
||||
def is_apache_user():
|
||||
import os
|
||||
|
|
@ -190,12 +190,14 @@ def get_db_password(db_name):
|
|||
|
||||
whitelisted = []
|
||||
guest_methods = []
|
||||
def whitelist(allow_guest=False):
|
||||
def whitelist(allow_guest=False, allow_roles=[]):
|
||||
"""
|
||||
decorator for whitelisting a function
|
||||
|
||||
Note: if the function is allowed to be accessed by a guest user,
|
||||
it must explicitly be marked as allow_guest=True
|
||||
|
||||
for specific roles, set allow_roles = ['Administrator'] etc.
|
||||
"""
|
||||
def innerfn(fn):
|
||||
global whitelisted, guest_methods
|
||||
|
|
@ -204,6 +206,17 @@ def whitelist(allow_guest=False):
|
|||
if allow_guest:
|
||||
guest_methods.append(fn)
|
||||
|
||||
if allow_roles:
|
||||
roles = get_roles()
|
||||
allowed = False
|
||||
for role in allow_roles:
|
||||
if role in roles:
|
||||
allowed = True
|
||||
break
|
||||
|
||||
if not allowed:
|
||||
raise PermissionError, "Method not allowed"
|
||||
|
||||
return fn
|
||||
|
||||
return innerfn
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ make index, wn.js, wn.css pages
|
|||
def make():
|
||||
import os
|
||||
import webnotes
|
||||
# TODO: why is jinja2 imported?
|
||||
from jinja2 import Template
|
||||
import webnotes.cms
|
||||
|
||||
|
|
|
|||
|
|
@ -259,10 +259,10 @@ class Database:
|
|||
r = self.sql("select value from tabSingles where field in ('%s') and doctype='%s'" % (fieldname, doctype))
|
||||
return r and (len(r) > 1 and (i[0] for i in r) or r[0][0]) or None
|
||||
|
||||
def set_value(self, dt, dn, field, val):
|
||||
def set_value(self, dt, dn, field, val, modified = None):
|
||||
from webnotes.utils import now
|
||||
if dn and dt!=dn:
|
||||
self.sql("update `tab"+dt+"` set `"+field+"`=%s, modified=%s where name=%s", (val, now(), dn))
|
||||
self.sql("update `tab"+dt+"` set `"+field+"`=%s, modified=%s where name=%s", (val, modified or now(), dn))
|
||||
else:
|
||||
if self.sql("select value from tabSingles where field=%s and doctype=%s", (field, dt)):
|
||||
self.sql("update tabSingles set value=%s where field=%s and doctype=%s", (val, field, dt))
|
||||
|
|
@ -270,7 +270,7 @@ class Database:
|
|||
self.sql("insert into tabSingles(doctype, field, value) values (%s, %s, %s)", (dt, field, val))
|
||||
|
||||
def set(self, doc, field, val):
|
||||
self.set_value(doc.doctype, doc.name, field, val)
|
||||
self.set_value(doc.doctype, doc.name, field, val, doc.modified)
|
||||
doc.fields[field] = val
|
||||
|
||||
# ======================================================================================
|
||||
|
|
|
|||
|
|
@ -127,66 +127,35 @@ def get_template():
|
|||
|
||||
@webnotes.whitelist()
|
||||
def uploadfile():
|
||||
import webnotes.utils
|
||||
import webnotes.utils.file_manager
|
||||
if webnotes.form_dict.get('from_form'):
|
||||
webnotes.utils.file_manager.upload()
|
||||
else:
|
||||
# save the file
|
||||
fid, fname = webnotes.utils.file_manager.save_uploaded()
|
||||
|
||||
# do something with the uploaded file
|
||||
if fid:
|
||||
if webnotes.form_dict.get('server_obj'):
|
||||
from webnotes.model.code import get_obj
|
||||
getattr(get_obj(webnotes.form_dict.get('server_obj')), webnotes.form_dict.get('method'))(fid, fname)
|
||||
|
||||
elif webnotes.form_dict.get('modulename'):
|
||||
# calls a python module to handle the script
|
||||
__import__(webnotes.form_dict['modulename'])
|
||||
import json
|
||||
|
||||
ret = []
|
||||
|
||||
try:
|
||||
if webnotes.form_dict.get('from_form'):
|
||||
webnotes.utils.file_manager.upload()
|
||||
else:
|
||||
if webnotes.form_dict.get('method'):
|
||||
m = webnotes.form_dict['method']
|
||||
modulename = '.'.join(m.split('.')[:-1])
|
||||
methodname = m.split('.')[-1]
|
||||
|
||||
__import__(modulename)
|
||||
import sys
|
||||
moduleobj = sys.modules[webnotes.form_dict['modulename']]
|
||||
getattr(moduleobj, webnotes.form_dict['method'])(fid, fname)
|
||||
moduleobj = sys.modules[modulename]
|
||||
ret = getattr(moduleobj, methodname)()
|
||||
except Exception, e:
|
||||
webnotes.msgprint(e)
|
||||
webnotes.errprint(webnotes.utils.getTraceback())
|
||||
|
||||
|
||||
webnotes.response['result'] = '<script>window.parent.upload_callback("'+webnotes.form_dict.get('uploader_id')+'", "'+fid+'")</script>'
|
||||
|
||||
# File upload (from scripts)
|
||||
# ------------------------------------------------------------------------------------
|
||||
|
||||
@webnotes.whitelist()
|
||||
def upload_many():
|
||||
from webnotes.model.code import get_obj
|
||||
|
||||
# pass it on to upload_many method in Control Panel
|
||||
cp = get_obj('Control Panel')
|
||||
cp.upload_many(webnotes.form)
|
||||
|
||||
webnotes.response['result'] = """
|
||||
<script type='text/javascript'>
|
||||
%s
|
||||
</script>
|
||||
%s
|
||||
%s""" % (cp.upload_callback(webnotes.form), '\n----\n'.join(webnotes.message_log).replace("'", "\'"), '\n----\n'.join(webnotes.debug_log).replace("'", "\'").replace("\n","<br>"))
|
||||
webnotes.response['type'] = 'iframe'
|
||||
|
||||
|
||||
@webnotes.whitelist()
|
||||
def get_file():
|
||||
import webnotes
|
||||
import webnotes.utils.file_manager
|
||||
form = webnotes.form
|
||||
|
||||
res = webnotes.utils.file_manager.get_file(form.getvalue('fname'))
|
||||
if res:
|
||||
webnotes.response['type'] = 'download'
|
||||
webnotes.response['filename'] = res[0]
|
||||
|
||||
if hasattr(res[1], 'tostring'):
|
||||
webnotes.response['filecontent'] = res[1].tostring()
|
||||
else:
|
||||
webnotes.response['filecontent'] = res[1]
|
||||
else:
|
||||
webnotes.msgprint('[get_file] Unknown file name')
|
||||
if not webnotes.response.get('result'):
|
||||
webnotes.response['result'] = """<script>
|
||||
window.parent.wn.upload.callback("%s", %s);
|
||||
</script>""" % (webnotes.form_dict.get('_id'),
|
||||
json.dumps(ret))
|
||||
|
||||
@webnotes.whitelist(allow_guest=True)
|
||||
def reset_password():
|
||||
|
|
@ -299,12 +268,25 @@ def print_csv():
|
|||
print webnotes.response['result']
|
||||
|
||||
def print_iframe():
|
||||
import json
|
||||
print "Content-Type: text/html"
|
||||
print
|
||||
if webnotes.response.get('result'):
|
||||
print webnotes.response['result']
|
||||
if webnotes.debug_log:
|
||||
print '''<script type='text/javascript'>alert("%s");</script>''' % ('-------'.join(webnotes.debug_log).replace('"', '').replace('\n',''))
|
||||
print """
|
||||
<script>
|
||||
var messages = %s;
|
||||
if(messages.length) {
|
||||
for(var i in messages)
|
||||
window.parent.msgprint(messages[i]);
|
||||
};
|
||||
var errors = %s;
|
||||
if(errors.length) {
|
||||
for(var i in errors)
|
||||
window.parent.console.log(errors[i]);
|
||||
}
|
||||
</script>""" % (json.dumps(webnotes.message_log), json.dumps(webnotes.debug_log))
|
||||
|
||||
def print_raw():
|
||||
import mimetypes
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ import webnotes
|
|||
|
||||
from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
|
||||
from webnotes.model import db_exists
|
||||
from webnotes.model.doc import Document, addchild, removechild, getchildren, make_autoname, SuperDocType
|
||||
from webnotes.model.doc import Document, addchild, getchildren, make_autoname
|
||||
from webnotes.model.utils import getlist
|
||||
from webnotes.model.code import get_obj, get_server_obj, run_server_obj, updatedb, check_syntax
|
||||
from webnotes import session, form, is_testing, msgprint, errprint
|
||||
|
|
@ -70,7 +70,7 @@ def execute(code, doc=None, doclist=[]):
|
|||
# --------------------------------------------------
|
||||
from webnotes.utils import add_days, add_months, add_years, cint, cstr, date_diff, default_fields, flt, fmt_money, formatdate, generate_hash, getTraceback, get_defaults, get_first_day, get_last_day, getdate, has_common, month_name, now, nowdate, replace_newlines, sendmail, set_default, str_esc_quote, user_format, validate_email_add
|
||||
from webnotes.model import db_exists
|
||||
from webnotes.model.doc import Document, addchild, removechild, getchildren
|
||||
from webnotes.model.doc import Document, addchild, getchildren
|
||||
from webnotes.model.utils import getlist
|
||||
from webnotes import session, form, msgprint, errprint
|
||||
|
||||
|
|
|
|||
|
|
@ -29,19 +29,6 @@ import webnotes.model.meta
|
|||
|
||||
from webnotes.utils import *
|
||||
|
||||
# actually should be "BaseDocType" - deprecated. Only for v160
|
||||
class SuperDocType:
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def __getattr__(self, name):
|
||||
if self.__dict__.has_key(name):
|
||||
return self.__dict__[name]
|
||||
elif self.super and hasattr(self.super, name):
|
||||
return getattr(self.super, name)
|
||||
else:
|
||||
raise AttributeError, 'BaseDocType Attribute Error'
|
||||
|
||||
class Document:
|
||||
"""
|
||||
The wn(meta-data)framework equivalent of a Database Record.
|
||||
|
|
@ -208,7 +195,6 @@ class Document:
|
|||
# amendments
|
||||
if self.amended_from:
|
||||
self._get_amended_name()
|
||||
|
||||
# by method
|
||||
elif so and hasattr(so, 'autoname'):
|
||||
r = webnotes.model.code.run_server_obj(so, 'autoname')
|
||||
|
|
@ -401,6 +387,9 @@ class Document:
|
|||
# add missing parentinfo (if reqd)
|
||||
if self.parent and not (self.parenttype and self.parentfield):
|
||||
self.update_parentinfo()
|
||||
|
||||
if self.parent and not self.idx:
|
||||
self.set_idx()
|
||||
|
||||
# if required, make new
|
||||
if new or (not new and self.fields.get('__islocal')) and (not res.get('issingle')):
|
||||
|
|
@ -431,6 +420,12 @@ class Document:
|
|||
self.parenttype = tmp[0][0]
|
||||
self.parentfield = tmp[0][1]
|
||||
|
||||
def set_idx(self):
|
||||
"""set idx"""
|
||||
self.idx = (webnotes.conn.sql("""select max(idx) from `tab%s`
|
||||
where parent=%s and parentfield=%s""" % (self.doctype, '%s', '%s'),
|
||||
(self.parent, self.parentfield))[0][0] or 0) + 1
|
||||
|
||||
# check permissions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
|
@ -560,20 +555,6 @@ def addchild(parent, fieldname, childtype = '', local=0, doclist=None):
|
|||
d.save(1)
|
||||
"""
|
||||
return parent.addchild(fieldname, childtype, local, doclist)
|
||||
|
||||
# Remove Child
|
||||
# ------------
|
||||
|
||||
def removechild(d, is_local = 0):
|
||||
"""
|
||||
Sets the docstatus of the object d to 2 (deleted) and appends an 'old_parent:' to the parent name
|
||||
"""
|
||||
if not is_local:
|
||||
set(d, 'docstatus', 2)
|
||||
set(d, 'parent', 'old_parent:' + d.parent)
|
||||
else:
|
||||
d.parent = 'old_parent:' + d.parent
|
||||
d.docstatus = 2
|
||||
|
||||
# Naming
|
||||
# ------
|
||||
|
|
@ -645,11 +626,12 @@ def getchildren(name, childtype, field='', parenttype='', from_doctype=0, prefix
|
|||
|
||||
if field:
|
||||
tmp = ' and parentfield="%s" ' % field
|
||||
if parenttype:
|
||||
if parenttype:
|
||||
tmp = ' and parenttype="%s" ' % parenttype
|
||||
|
||||
try:
|
||||
dataset = webnotes.conn.sql("select * from `%s%s` where parent='%s' %s order by idx" % (prefix, childtype, name, tmp))
|
||||
dataset = webnotes.conn.sql("select * from `%s%s` where parent='%s' %s order by idx" \
|
||||
% (prefix, childtype, name, tmp))
|
||||
desc = webnotes.conn.get_description()
|
||||
except Exception, e:
|
||||
if prefix=='arc' and e.args[0]==1146:
|
||||
|
|
|
|||
|
|
@ -40,6 +40,10 @@ class DocList:
|
|||
self.to_docstatus = 0
|
||||
if dt and dn:
|
||||
self.load_from_db(dt, dn)
|
||||
if type(dt) is list:
|
||||
self.docs = dt
|
||||
self.doc = dt[0]
|
||||
self.children = dt[1:]
|
||||
|
||||
def load_from_db(self, dt, dn, prefix='tab'):
|
||||
"""
|
||||
|
|
|
|||
|
|
@ -368,7 +368,7 @@ class _DocType:
|
|||
def insert_into_cache(self, doclist):
|
||||
import json
|
||||
json_doclist = json.dumps([d.fields for d in doclist])
|
||||
CacheItem(self.name).set(json_doclist, 3600)
|
||||
CacheItem(self.name).set(json_doclist)
|
||||
|
||||
def get(dt, form=1):
|
||||
"""
|
||||
|
|
|
|||
|
|
@ -49,8 +49,8 @@ def walk_and_sync(start_path, force=0):
|
|||
|
||||
if doctype == 'doctype':
|
||||
sync(module_name, name, force)
|
||||
elif doctype == 'page':
|
||||
reload_doc(module_name, 'page', name)
|
||||
elif doctype in ['page']:#, 'search_criteria', 'Print Format', 'DocType Mapper']:
|
||||
reload_doc(module_name, doctype, name)
|
||||
print module_name + ' | ' + doctype + ' | ' + name
|
||||
|
||||
return modules
|
||||
|
|
|
|||
|
|
@ -48,19 +48,25 @@ class CacheItem:
|
|||
def get(self):
|
||||
"""get value"""
|
||||
try:
|
||||
return webnotes.conn.sql("select `value` from __CacheItem where `key`=%s and expires_on > NOW()", self.key)[0][0]
|
||||
return webnotes.conn.sql("""select `value` from __CacheItem where
|
||||
`key`=%s and ifnull(expires_on, '2100-01-01') > NOW()""", self.key)[0][0]
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def set(self, value, interval=6000):
|
||||
def set(self, value, interval=None):
|
||||
"""set a new value, with interval"""
|
||||
self.clear()
|
||||
webnotes.conn.sql("""INSERT INTO
|
||||
__CacheItem (`key`, `value`, expires_on)
|
||||
VALUES
|
||||
(%s, %s, addtime(now(), sec_to_time(%s)))
|
||||
""", (self.key, str(value), interval))
|
||||
|
||||
if interval:
|
||||
webnotes.conn.sql("""insert into
|
||||
__CacheItem (`key`, `value`, expires_on)
|
||||
values (%s, %s, addtime(now(), sec_to_time(%s)))
|
||||
""", (self.key, str(value), interval))
|
||||
else:
|
||||
webnotes.conn.sql("""insert into
|
||||
__CacheItem (`key`, `value`)
|
||||
values (%s, %s)
|
||||
""", (self.key, str(value)))
|
||||
|
||||
|
||||
def clear(self):
|
||||
"""clear the item"""
|
||||
|
|
|
|||
|
|
@ -70,26 +70,17 @@ def add_file_list(dt, dn, fname, fid):
|
|||
"""
|
||||
udpate file_list attribute of the record
|
||||
"""
|
||||
try:
|
||||
# get the old file_list
|
||||
fl = webnotes.conn.get_value(dt, dn, 'file_list') or ''
|
||||
if fl:
|
||||
fl += '\n'
|
||||
|
||||
# add new file id
|
||||
fl += fname + ',' + fid
|
||||
|
||||
# save
|
||||
webnotes.conn.set_value(dt, dn, 'file_list', fl)
|
||||
|
||||
return True
|
||||
fl = webnotes.conn.get_value(dt, dn, 'file_list') or ''
|
||||
if fl:
|
||||
fl += '\n'
|
||||
|
||||
# add new file id
|
||||
fl += fname + ',' + fid
|
||||
|
||||
except Exception, e:
|
||||
webnotes.response['result'] = """
|
||||
<script type='text/javascript'>
|
||||
window.parent.msgprint("Error while uploading: %s");
|
||||
</script>""" % str(e)
|
||||
# save
|
||||
webnotes.conn.set_value(dt, dn, 'file_list', fl)
|
||||
|
||||
return True
|
||||
|
||||
def remove_all(dt, dn):
|
||||
"""remove all files in a transaction"""
|
||||
|
|
@ -107,7 +98,7 @@ def remove_file(dt, dn, fid):
|
|||
new_fl = []
|
||||
fl = fl.split('\n')
|
||||
for f in fl:
|
||||
if f.split(',')[1]!=fid:
|
||||
if f and f.split(',')[1]!=fid:
|
||||
new_fl.append(f)
|
||||
|
||||
# delete
|
||||
|
|
@ -133,37 +124,31 @@ def make_thumbnail(blob, size):
|
|||
|
||||
return fcontent
|
||||
|
||||
def get_uploaded_content():
|
||||
import webnotes
|
||||
|
||||
if 'filedata' in webnotes.form:
|
||||
i = webnotes.form['filedata']
|
||||
webnotes.uploaded_filename, webnotes.uploaded_content = i.filename, i.file.read()
|
||||
return webnotes.uploaded_filename, webnotes.uploaded_content
|
||||
else:
|
||||
webnotes.msgprint('No File');
|
||||
return None, None
|
||||
|
||||
def save_uploaded(js_okay='window.parent.msgprint("File Upload Successful")', js_fail=''):
|
||||
def save_uploaded():
|
||||
import webnotes.utils
|
||||
|
||||
webnotes.response['type'] = 'iframe'
|
||||
|
||||
form, fid, fname = webnotes.form, None, None
|
||||
form = webnotes.form
|
||||
|
||||
try:
|
||||
# has attachment?
|
||||
if 'filedata' in form:
|
||||
i = form['filedata']
|
||||
|
||||
fname, content = i.filename, i.file.read()
|
||||
fname, content = get_uploaded_content()
|
||||
if content:
|
||||
fid = save_file(fname, content)
|
||||
return fid, fname
|
||||
|
||||
# get the file id
|
||||
fid = save_file(fname, content)
|
||||
|
||||
# okay
|
||||
webnotes.response['result'] = """<script type='text/javascript'>%s</script>""" % js_okay
|
||||
else:
|
||||
webnotes.response['result'] = """<script type='text/javascript'>window.parent.msgprint("No file"); %s</script>""" % js_fail
|
||||
|
||||
except Exception, e:
|
||||
webnotes.response['result'] = """<script type='text/javascript'>
|
||||
window.parent.msgprint("%s");
|
||||
window.parent.errprint("%s");
|
||||
%s</script>""" % (str(e), \
|
||||
webnotes.utils.getTraceback().replace('\n','<br>').replace('"', '\\"'), js_fail)
|
||||
|
||||
return fid, fname
|
||||
else:
|
||||
return None, fname
|
||||
|
||||
# -------------------------------------------------------
|
||||
|
||||
|
|
@ -227,12 +212,8 @@ def delete_file(fid, verbose=0):
|
|||
path = os.path.join(webnotes.get_files_path(), fid.replace('/','-'))
|
||||
if os.path.exists(path):
|
||||
os.remove(path)
|
||||
|
||||
# Get File
|
||||
# -------------------------------------------------------
|
||||
|
||||
|
||||
def get_file(fname):
|
||||
"""deprecated"""
|
||||
f = get_file_system_name(fname)
|
||||
if f:
|
||||
file_id = f[0][0].replace('/','-')
|
||||
|
|
@ -246,7 +227,4 @@ def get_file(fname):
|
|||
with open(os.path.join(webnotes.get_files_path(), file_id), 'r') as f:
|
||||
content = f.read()
|
||||
|
||||
return [file_name, content]
|
||||
|
||||
|
||||
# -------------------------------------------------------
|
||||
return [file_name, content]
|
||||
|
|
@ -49,7 +49,7 @@ def getsearchfields():
|
|||
webnotes.response['searchfields'] = [['name', 'ID', 'Data', '']] + res
|
||||
|
||||
def make_query(fields, dt, key, txt, start, length):
|
||||
return """SELECT %(fields)s
|
||||
query = """SELECT %(fields)s
|
||||
FROM `tab%(dt)s`
|
||||
WHERE `tab%(dt)s`.`%(key)s` LIKE '%(txt)s' AND `tab%(dt)s`.docstatus != 2
|
||||
ORDER BY `tab%(dt)s`.`%(key)s`
|
||||
|
|
@ -61,6 +61,7 @@ def make_query(fields, dt, key, txt, start, length):
|
|||
'start': start,
|
||||
'len': length
|
||||
}
|
||||
return query
|
||||
|
||||
def get_std_fields_list(dt, key):
|
||||
# get additional search fields
|
||||
|
|
@ -102,6 +103,12 @@ def search_link():
|
|||
txt = webnotes.form.getvalue('txt')
|
||||
dt = webnotes.form.getvalue('dt')
|
||||
query = webnotes.form.getvalue('query')
|
||||
|
||||
# txt - decode it to utf-8. why to do this?
|
||||
# "%(something_unicode)s %(something ascii encoded with utf-8)s"
|
||||
# tries to decode ascii string using ascii codec and not utf-8
|
||||
# since web pages are encoded in utf-8, we can force decode to utf-8
|
||||
txt = txt.decode('utf-8')
|
||||
|
||||
if query:
|
||||
res = webnotes.conn.sql(scrub_custom_query(query, 'name', txt))
|
||||
|
|
@ -122,6 +129,12 @@ def search_widget():
|
|||
key = webnotes.form.getvalue('searchfield') or 'name' # key field
|
||||
user_query = webnotes.form.getvalue('query') or ''
|
||||
|
||||
# txt - decode it to utf-8. why to do this?
|
||||
# "%(something_unicode)s %(something ascii encoded with utf-8)s"
|
||||
# tries to decode ascii string using ascii codec and not utf-8
|
||||
# since web pages are encoded in utf-8, we can force decode to utf-8
|
||||
txt = txt.decode('utf-8')
|
||||
|
||||
if user_query:
|
||||
query = scrub_custom_query(user_query, key, txt)
|
||||
else:
|
||||
|
|
|
|||
15
wnf.py
15
wnf.py
|
|
@ -84,6 +84,8 @@ def setup_options():
|
|||
# build
|
||||
parser.add_option("-b", "--build", default=False, action="store_true",
|
||||
help="minify + concat js files")
|
||||
parser.add_option("--cms", default=False, action="store_true",
|
||||
help="take a dump of website pages, js and css")
|
||||
|
||||
# git
|
||||
parser.add_option("--status", default=False, action="store_true",
|
||||
|
|
@ -162,13 +164,22 @@ def run():
|
|||
webnotes.connect(options.db_name, options.password)
|
||||
else:
|
||||
webnotes.connect(options.db_name)
|
||||
elif not options.install:
|
||||
elif not any([options.install, options.pull]):
|
||||
webnotes.connect(conf.db_name)
|
||||
|
||||
# build
|
||||
if options.build:
|
||||
import build.project
|
||||
build.project.build()
|
||||
build.project.build()
|
||||
|
||||
elif options.cms:
|
||||
from webnotes.model.code import get_obj
|
||||
# rewrite pages
|
||||
ws = get_obj('Website Settings')
|
||||
ws.rewrite_pages()
|
||||
ss = get_obj('Style Settings')
|
||||
ss.validate()
|
||||
ss.on_update()
|
||||
|
||||
# code replace
|
||||
elif options.replace:
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue