Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

778 lignes
23 KiB

  1. # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
  2. #
  3. # MIT License (MIT)
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a
  6. # copy of this software and associated documentation files (the "Software"),
  7. # to deal in the Software without restriction, including without limitation
  8. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. # and/or sell copies of the Software, and to permit persons to whom the
  10. # Software is furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  16. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  17. # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  19. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  20. # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #
  22. from __future__ import unicode_literals
  23. """
  24. Contains the Document class representing an object / record
  25. """
  26. import webnotes
  27. import webnotes.model.meta
  28. from webnotes.utils import *
  29. valid_fields_map = {}
  30. class Document:
  31. """
  32. The wn(meta-data)framework equivalent of a Database Record.
  33. Stores,Retrieves,Updates the record in the corresponding table.
  34. Runs the triggers required.
  35. The `Document` class represents the basic Object-Relational Mapper (ORM). The object type is defined by
  36. `DocType` and the object ID is represented by `name`::
  37. Please note the anamoly in the Web Notes Framework that `ID` is always called as `name`
  38. If both `doctype` and `name` are specified in the constructor, then the object is loaded from the database.
  39. If only `doctype` is given, then the object is not loaded
  40. If `fielddata` is specfied, then the object is created from the given dictionary.
  41. **Note 1:**
  42. The getter and setter of the object are overloaded to map to the fields of the object that
  43. are loaded when it is instantiated.
  44. For example: doc.name will be the `name` field and doc.owner will be the `owner` field
  45. **Note 2 - Standard Fields:**
  46. * `name`: ID / primary key
  47. * `owner`: creator of the record
  48. * `creation`: datetime of creation
  49. * `modified`: datetime of last modification
  50. * `modified_by` : last updating user
  51. * `docstatus` : Status 0 - Saved, 1 - Submitted, 2- Cancelled
  52. * `parent` : if child (table) record, this represents the parent record
  53. * `parenttype` : type of parent record (if any)
  54. * `parentfield` : table fieldname of parent record (if any)
  55. * `idx` : Index (sequence) of the child record
  56. """
  57. def __init__(self, doctype = None, name = None, fielddata = None, prefix='tab'):
  58. self._roles = []
  59. self._perms = []
  60. self._user_defaults = {}
  61. self._prefix = prefix
  62. if isinstance(doctype, dict):
  63. fielddata = doctype
  64. doctype = None
  65. if fielddata:
  66. self.fields = webnotes.DictObj(fielddata)
  67. else:
  68. self.fields = webnotes.DictObj()
  69. if not self.fields.has_key('name'):
  70. self.fields['name']='' # required on save
  71. if not self.fields.has_key('doctype'):
  72. self.fields['doctype']='' # required on save
  73. if not self.fields.has_key('owner'):
  74. self.fields['owner']='' # required on save
  75. if doctype:
  76. self.fields['doctype'] = doctype
  77. if name:
  78. self.fields['name'] = name
  79. self.__initialized = 1
  80. if (doctype and name):
  81. self._loadfromdb(doctype, name)
  82. else:
  83. if not fielddata:
  84. self.fields['__islocal'] = 1
  85. if not self.fields.docstatus:
  86. self.fields.docstatus = 0
  87. def __nonzero__(self):
  88. return True
  89. def __str__(self):
  90. return str(self.fields)
  91. def __eq__(self, other):
  92. return self.fields == other.fields
  93. # Load Document
  94. # ---------------------------------------------------------------------------
  95. def encode(self, encoding='utf-8'):
  96. """convert all unicode values to utf-8"""
  97. for key in self.fields:
  98. if isinstance(self.fields[key], unicode):
  99. self.fields[key] = self.fields[key].encode(encoding)
  100. def _loadfromdb(self, doctype = None, name = None):
  101. if name: self.name = name
  102. if doctype: self.doctype = doctype
  103. is_single = False
  104. try:
  105. is_single = webnotes.model.meta.is_single(self.doctype)
  106. except Exception, e:
  107. pass
  108. if is_single:
  109. self._loadsingle()
  110. else:
  111. dataset = webnotes.conn.sql('select * from `%s%s` where name="%s"' % (self._prefix, self.doctype, self.name.replace('"', '\"')))
  112. if not dataset:
  113. raise Exception, '[WNF] %s %s does not exist' % (self.doctype, self.name)
  114. self._load_values(dataset[0], webnotes.conn.get_description())
  115. # Load Fields from dataset
  116. # ---------------------------------------------------------------------------
  117. def _load_values(self, data, description):
  118. if '__islocal' in self.fields:
  119. del self.fields['__islocal']
  120. for i in range(len(description)):
  121. v = data[i]
  122. self.fields[description[i][0]] = webnotes.conn.convert_to_simple_type(v)
  123. def _merge_values(self, data, description):
  124. for i in range(len(description)):
  125. v = data[i]
  126. if v: # only if value, over-write
  127. self.fields[description[i][0]] = webnotes.conn.convert_to_simple_type(v)
  128. # Load Single Type
  129. # ---------------------------------------------------------------------------
  130. def _loadsingle(self):
  131. self.name = self.doctype
  132. self.fields.update(getsingle(self.doctype))
  133. # Setter
  134. # ---------------------------------------------------------------------------
  135. def __setattr__(self, name, value):
  136. # normal attribute
  137. if not self.__dict__.has_key('_Document__initialized'):
  138. self.__dict__[name] = value
  139. elif self.__dict__.has_key(name):
  140. self.__dict__[name] = value
  141. else:
  142. # field attribute
  143. f = self.__dict__['fields']
  144. f[name] = value
  145. # Getter
  146. # ---------------------------------------------------------------------------
  147. def __getattr__(self, name):
  148. if self.__dict__.has_key(name):
  149. return self.__dict__[name]
  150. elif self.fields.has_key(name):
  151. return self.fields[name]
  152. else:
  153. return ''
  154. # Get Amendement number
  155. # ---------------------------------------------------------------------------
  156. def _get_amended_name(self):
  157. am_id = 1
  158. am_prefix = self.amended_from
  159. if webnotes.conn.sql('select amended_from from `tab%s` where name = "%s"' % (self.doctype, self.amended_from))[0][0] or '':
  160. am_id = cint(self.amended_from.split('-')[-1]) + 1
  161. am_prefix = '-'.join(self.amended_from.split('-')[:-1]) # except the last hyphen
  162. self.name = am_prefix + '-' + str(am_id)
  163. # Set Name
  164. # ---------------------------------------------------------------------------
  165. def _set_name(self, autoname, istable):
  166. self.localname = self.name
  167. # get my object
  168. import webnotes.model.code
  169. so = webnotes.model.code.get_server_obj(self, [])
  170. # amendments
  171. if self.amended_from:
  172. self._get_amended_name()
  173. # by method
  174. elif so and hasattr(so, 'autoname'):
  175. r = webnotes.model.code.run_server_obj(so, 'autoname')
  176. if r: return r
  177. # based on a field
  178. elif autoname and autoname.startswith('field:'):
  179. n = self.fields[autoname[6:]]
  180. if not n:
  181. raise Exception, 'Name is required'
  182. self.name = n.strip()
  183. elif autoname and autoname.startswith("naming_series:"):
  184. if not self.naming_series:
  185. # pick default naming series
  186. from webnotes.model.doctype import get_property
  187. self.naming_series = get_property(self.doctype, "options", "naming_series").split("\n")
  188. self.naming_series = self.naming_series[0] or self.naming_series[1]
  189. self.name = make_autoname(self.naming_series+'.#####')
  190. # based on expression
  191. elif autoname and autoname.startswith('eval:'):
  192. doc = self # for setting
  193. self.name = eval(autoname[5:])
  194. # call the method!
  195. elif autoname and autoname!='Prompt':
  196. self.name = make_autoname(autoname, self.doctype)
  197. # given
  198. elif self.fields.get('__newname',''):
  199. self.name = self.fields['__newname']
  200. # default name for table
  201. elif istable:
  202. self.name = make_autoname('#########', self.doctype)
  203. # unable to determine a name, use a serial number!
  204. if not self.name:
  205. self.name = make_autoname('#########', self.doctype)
  206. # Validate Name
  207. # ---------------------------------------------------------------------------
  208. def _validate_name(self, case):
  209. if webnotes.conn.sql('select name from `tab%s` where name=%s' % (self.doctype,'%s'), self.name):
  210. raise NameError, 'Name %s already exists' % self.name
  211. # no name
  212. if not self.name: return 'No Name Specified for %s' % self.doctype
  213. # new..
  214. if self.name.startswith('New '+self.doctype):
  215. raise NameError, 'There were some errors setting the name, please contact the administrator'
  216. if case=='Title Case': self.name = self.name.title()
  217. if case=='UPPER CASE': self.name = self.name.upper()
  218. self.name = self.name.strip() # no leading and trailing blanks
  219. forbidden = ['%', "'", '"', '#', '*', '?', '`']
  220. for f in forbidden:
  221. if f in self.name:
  222. webnotes.msgprint('%s not allowed in ID (name)' % f, raise_exception =1)
  223. # Insert
  224. # ---------------------------------------------------------------------------
  225. def insert(self, autoname, istable, case='', make_autoname=1, keep_timestamps=False):
  226. # set name
  227. if make_autoname:
  228. self._set_name(autoname, istable)
  229. # validate name
  230. self._validate_name(case)
  231. # insert!
  232. if not keep_timestamps:
  233. if not self.owner:
  234. self.owner = webnotes.session['user']
  235. self.modified_by = webnotes.session['user']
  236. self.creation = self.modified = now()
  237. webnotes.conn.sql("insert into `tab%(doctype)s`" % self.fields \
  238. + """ (name, owner, creation, modified, modified_by)
  239. values (%(name)s, %(owner)s, %(creation)s, %(modified)s,
  240. %(modified_by)s)""", self.fields)
  241. # Update Values
  242. # ---------------------------------------------------------------------------
  243. def _update_single(self, link_list):
  244. update_str = ["(%s, 'modified', %s)",]
  245. values = [self.doctype, now()]
  246. webnotes.conn.sql("delete from tabSingles where doctype='%s'" % self.doctype)
  247. for f in self.fields.keys():
  248. if not (f in ('modified', 'doctype', 'name', 'perm', 'localname', 'creation'))\
  249. and (not f.startswith('__')): # fields not saved
  250. # validate links
  251. if link_list and link_list.get(f):
  252. self.fields[f] = self._validate_link(link_list[f][0], self.fields[f])
  253. if self.fields[f]==None:
  254. update_str.append("(%s,%s,NULL)")
  255. values.append(self.doctype)
  256. values.append(f)
  257. else:
  258. update_str.append("(%s,%s,%s)")
  259. values.append(self.doctype)
  260. values.append(f)
  261. values.append(self.fields[f])
  262. webnotes.conn.sql("insert into tabSingles(doctype, field, value) values %s" % (', '.join(update_str)), values)
  263. # Validate Links
  264. # ---------------------------------------------------------------------------
  265. def validate_links(self, link_list):
  266. err_list = []
  267. for f in self.fields.keys():
  268. # validate links
  269. old_val = self.fields[f]
  270. if link_list and link_list.get(f):
  271. self.fields[f] = self._validate_link(link_list[f][0], self.fields[f])
  272. if old_val and not self.fields[f]:
  273. s = link_list[f][1] + ': ' + old_val
  274. err_list.append(s)
  275. return err_list
  276. def make_link_list(self):
  277. res = webnotes.model.meta.get_link_fields(self.doctype)
  278. link_list = {}
  279. for i in res: link_list[i[0]] = (i[1], i[2]) # options, label
  280. return link_list
  281. def _validate_link(self, dt, dn):
  282. if not dt: return dn
  283. if not dn: return None
  284. if dt=="[Select]": return dn
  285. if dt.lower().startswith('link:'):
  286. dt = dt[5:]
  287. if '\n' in dt:
  288. dt = dt.split('\n')[0]
  289. tmp = webnotes.conn.sql("""SELECT name FROM `tab%s`
  290. WHERE name = %s""" % (dt, '%s'), dn)
  291. return tmp and tmp[0][0] or ''# match case
  292. def _update_values(self, issingle, link_list, ignore_fields=0, keep_timestamps=False):
  293. if issingle:
  294. self._update_single(link_list)
  295. else:
  296. update_str, values = [], []
  297. # set modified timestamp
  298. if self.modified and not keep_timestamps:
  299. self.modified = now()
  300. self.modified_by = webnotes.session['user']
  301. fields_list = ignore_fields and self.get_valid_fields() or self.fields.keys()
  302. for f in fields_list:
  303. if (not (f in ('doctype', 'name', 'perm', 'localname',
  304. 'creation','_user_tags'))) and (not f.startswith('__')):
  305. # fields not saved
  306. # validate links
  307. if link_list and link_list.get(f):
  308. self.fields[f] = self._validate_link(link_list[f][0],
  309. self.fields.get(f))
  310. if self.fields.get(f) is None or self.fields.get(f)=='':
  311. update_str.append("`%s`=NULL" % f)
  312. else:
  313. values.append(self.fields.get(f))
  314. update_str.append("`%s`=%s" % (f, '%s'))
  315. if values:
  316. values.append(self.name)
  317. r = webnotes.conn.sql("update `tab%s` set %s where name=%s" % \
  318. (self.doctype, ', '.join(update_str), "%s"), values)
  319. def get_valid_fields(self):
  320. global valid_fields_map
  321. if not valid_fields_map.get(self.doctype):
  322. import webnotes.model.doctype
  323. if cint(webnotes.conn.get_value("DocType", self.doctype, "issingle")):
  324. doctypelist = webnotes.model.doctype.get(self.doctype)
  325. valid_fields_map[self.doctype] = doctypelist.get_fieldnames({
  326. "fieldtype": ["not in", webnotes.model.no_value_fields]})
  327. else:
  328. valid_fields_map[self.doctype] = \
  329. webnotes.conn.get_table_columns(self.doctype)
  330. return valid_fields_map.get(self.doctype)
  331. # Save values
  332. # ---------------------------------------------------------------------------
  333. def save(self, new=0, check_links=1, ignore_fields=0, make_autoname=1,
  334. keep_timestamps=False):
  335. """
  336. Saves the current record in the database.
  337. If new = 1, creates a new instance of the record.
  338. Also clears temperory fields starting with `__`
  339. * if check_links is set, it validates all `Link` fields
  340. * if ignore_fields is sets, it does not throw an exception
  341. for any field that does not exist in the database table
  342. """
  343. res = webnotes.model.meta.get_dt_values(self.doctype,
  344. 'autoname, issingle, istable, name_case', as_dict=1)
  345. res = res and res[0] or {}
  346. # add missing parentinfo (if reqd)
  347. if self.parent and not (self.parenttype and self.parentfield):
  348. self.update_parentinfo()
  349. if self.parent and not self.idx:
  350. self.set_idx()
  351. # if required, make new
  352. if new or (not new and self.fields.get('__islocal')) and (not res.get('issingle')):
  353. r = self.insert(res.get('autoname'), res.get('istable'), res.get('name_case'),
  354. make_autoname, keep_timestamps = keep_timestamps)
  355. if r:
  356. return r
  357. # save the values
  358. self._update_values(res.get('issingle'),
  359. check_links and self.make_link_list() or {}, ignore_fields=ignore_fields,
  360. keep_timestamps=keep_timestamps)
  361. self._clear_temp_fields()
  362. def update_parentinfo(self):
  363. """update parent type and parent field, if not explicitly specified"""
  364. tmp = webnotes.conn.sql("""select parent, fieldname from tabDocField
  365. where fieldtype='Table' and options=%s""", self.doctype)
  366. if len(tmp)==0:
  367. raise Exception, 'Incomplete parent info in child table (%s, %s)' \
  368. % (self.doctype, self.fields.get('name', '[new]'))
  369. elif len(tmp)>1:
  370. raise Exception, 'Ambiguous parent info (%s, %s)' \
  371. % (self.doctype, self.fields.get('name', '[new]'))
  372. else:
  373. self.parenttype = tmp[0][0]
  374. self.parentfield = tmp[0][1]
  375. def set_idx(self):
  376. """set idx"""
  377. self.idx = (webnotes.conn.sql("""select max(idx) from `tab%s`
  378. where parent=%s and parentfield=%s""" % (self.doctype, '%s', '%s'),
  379. (self.parent, self.parentfield))[0][0] or 0) + 1
  380. # check permissions
  381. # ---------------------------------------------------------------------------
  382. def _get_perms(self):
  383. if not self._perms:
  384. self._perms = webnotes.conn.sql("""select role, `match` from tabDocPerm
  385. where parent=%s and ifnull(`read`,0) = 1
  386. and ifnull(permlevel,0)=0""", self.doctype)
  387. def _get_roles(self):
  388. # check if roles match/
  389. if not self._roles:
  390. if webnotes.user:
  391. self._roles = webnotes.user.get_roles()
  392. else:
  393. self._roles = ['Guest']
  394. def _get_user_defaults(self):
  395. if not self._user_defaults:
  396. if webnotes.user:
  397. self._user_defaults = webnotes.user.get_defaults()
  398. else:
  399. self.defaults = {}
  400. def check_perm(self, verbose=0):
  401. import webnotes
  402. # Admin has all permissions
  403. if webnotes.session['user']=='Administrator':
  404. return 1
  405. # find roles with read access for this record at 0
  406. self._get_perms()
  407. self._get_roles()
  408. self._get_user_defaults()
  409. has_perm, match = 0, []
  410. # loop through everything to find if there is a match
  411. for r in self._perms:
  412. if r[0] in self._roles:
  413. has_perm = 1
  414. if r[1] and match != -1:
  415. match.append(r[1]) # add to match check
  416. else:
  417. match = -1 # has permission and no match, so match not required!
  418. if has_perm and match and match != -1:
  419. for m in match:
  420. if ":" in m:
  421. document_key, default_key = m.split(":")
  422. else:
  423. document_key = default_key = m
  424. if self.fields.get(document_key, 'no value') in \
  425. self._user_defaults.get(default_key, 'no default'):
  426. has_perm = 1
  427. break # permission found! break
  428. else:
  429. has_perm = 0
  430. return has_perm
  431. def _clear_temp_fields(self):
  432. # clear temp stuff
  433. keys = self.fields.keys()
  434. for f in keys:
  435. if f.startswith('__'):
  436. del self.fields[f]
  437. def clear_table(self, doclist, tablefield, save=0):
  438. """
  439. Clears the child records from the given `doclist` for a particular `tablefield`
  440. """
  441. from webnotes.model.utils import getlist
  442. table_list = getlist(doclist, tablefield)
  443. delete_list = [d.name for d in table_list]
  444. if delete_list:
  445. #filter doclist
  446. doclist = filter(lambda d: d.name not in delete_list, doclist)
  447. # delete from db
  448. webnotes.conn.sql("""\
  449. delete from `tab%s`
  450. where parent=%s and parenttype=%s"""
  451. % (table_list[0].doctype, '%s', '%s'),
  452. (self.name, self.doctype))
  453. self.fields['__unsaved'] = 1
  454. return doclist
  455. def addchild(self, fieldname, childtype = '', local=0, doclist=None):
  456. """
  457. Returns a child record of the give `childtype`.
  458. * if local is set, it does not save the record
  459. * if doclist is passed, it append the record to the doclist
  460. """
  461. d = Document()
  462. d.parent = self.name
  463. d.parenttype = self.doctype
  464. d.parentfield = fieldname
  465. d.doctype = childtype
  466. d.docstatus = 0;
  467. d.name = ''
  468. d.owner = webnotes.session['user']
  469. if local:
  470. d.fields['__islocal'] = 1 # for Client to identify unsaved doc
  471. else:
  472. d.save(new=1)
  473. if doclist != None:
  474. doclist.append(d)
  475. return d
  476. def get_values(self):
  477. """get non-null fields dict withouth standard fields"""
  478. from webnotes.model import default_fields
  479. ret = {}
  480. for key in self.fields:
  481. if key not in default_fields and self.fields[key]:
  482. ret[key] = self.fields[key]
  483. return ret
  484. def addchild(parent, fieldname, childtype = '', local=0, doclist=None):
  485. """
  486. Create a child record to the parent doc.
  487. Example::
  488. c = Document('Contact','ABC')
  489. d = addchild(c, 'contact_updates', 'Contact Update', local = 1)
  490. d.last_updated = 'Phone call'
  491. d.save(1)
  492. """
  493. return parent.addchild(fieldname, childtype, local, doclist)
  494. # Naming
  495. # ------
  496. def make_autoname(key, doctype=''):
  497. """
  498. Creates an autoname from the given key:
  499. **Autoname rules:**
  500. * The key is separated by '.'
  501. * '####' represents a series. The string before this part becomes the prefix:
  502. Example: ABC.#### creates a series ABC0001, ABC0002 etc
  503. * 'MM' represents the current month
  504. * 'YY' and 'YYYY' represent the current year
  505. *Example:*
  506. * DE/./.YY./.MM./.##### will create a series like
  507. DE/09/01/0001 where 09 is the year, 01 is the month and 0001 is the series
  508. """
  509. n = ''
  510. l = key.split('.')
  511. for e in l:
  512. en = ''
  513. if e.startswith('#'):
  514. digits = len(e)
  515. en = getseries(n, digits, doctype)
  516. elif e=='YY':
  517. import time
  518. en = time.strftime('%y')
  519. elif e=='MM':
  520. import time
  521. en = time.strftime('%m')
  522. elif e=='YYYY':
  523. import time
  524. en = time.strftime('%Y')
  525. else: en = e
  526. n+=en
  527. return n
  528. # Get Series for Autoname
  529. # -----------------------
  530. def getseries(key, digits, doctype=''):
  531. # series created ?
  532. if webnotes.conn.sql("select name from tabSeries where name='%s'" % key):
  533. # yes, update it
  534. webnotes.conn.sql("update tabSeries set current = current+1 where name='%s'" % key)
  535. # find the series counter
  536. r = webnotes.conn.sql("select current from tabSeries where name='%s'" % key)
  537. n = r[0][0]
  538. else:
  539. # no, create it
  540. webnotes.conn.sql("insert into tabSeries (name, current) values ('%s', 1)" % key)
  541. n = 1
  542. return ('%0'+str(digits)+'d') % n
  543. # Get Children
  544. # ------------
  545. def getchildren(name, childtype, field='', parenttype='', from_doctype=0, prefix='tab'):
  546. import webnotes
  547. from webnotes.model.doclist import DocList
  548. tmp = ''
  549. if field:
  550. tmp = ' and parentfield="%s" ' % field
  551. if parenttype:
  552. tmp = ' and parenttype="%s" ' % parenttype
  553. dataset = webnotes.conn.sql("select * from `%s%s` where parent='%s' %s order by idx" \
  554. % (prefix, childtype, name, tmp))
  555. desc = webnotes.conn.get_description()
  556. l = DocList()
  557. for i in dataset:
  558. d = Document()
  559. d.doctype = childtype
  560. d._load_values(i, desc)
  561. l.append(d)
  562. return l
  563. # Check if "Guest" is allowed to view this page
  564. # ---------------------------------------------
  565. def check_page_perm(doc):
  566. if doc.name=='Login Page':
  567. return
  568. if doc.publish:
  569. return
  570. if not webnotes.conn.sql("select name from `tabPage Role` where parent=%s and role='Guest'", doc.name):
  571. webnotes.response['403'] = 1
  572. raise webnotes.PermissionError, '[WNF] No read permission for %s %s' % ('Page', doc.name)
  573. def get_report_builder_code(doc):
  574. if doc.doctype=='Search Criteria':
  575. from webnotes.model.code import get_code
  576. if doc.standard != 'No':
  577. doc.report_script = get_code(doc.module, 'Search Criteria', doc.name, 'js')
  578. doc.custom_query = get_code(doc.module, 'Search Criteria', doc.name, 'sql')
  579. # called from everywhere
  580. # load a record and its child records and bundle it in a list - doclist
  581. # ---------------------------------------------------------------------
  582. def get(dt, dn='', with_children = 1, from_get_obj = 0, prefix = 'tab'):
  583. """
  584. Returns a doclist containing the main record and all child records
  585. """
  586. import webnotes
  587. import webnotes.model
  588. from webnotes.model.doclist import DocList
  589. dn = dn or dt
  590. # load the main doc
  591. doc = Document(dt, dn, prefix=prefix)
  592. # check permission - for doctypes, pages
  593. if (dt in ('DocType', 'Page', 'Control Panel', 'Search Criteria')) or (from_get_obj and webnotes.session.get('user') != 'Guest'):
  594. if dt=='Page' and webnotes.session['user'] == 'Guest':
  595. check_page_perm(doc)
  596. else:
  597. if not doc.check_perm():
  598. webnotes.response['403'] = 1
  599. raise webnotes.ValidationError, '[WNF] No read permission for %s %s' % (dt, dn)
  600. if not with_children:
  601. # done
  602. return DocList([doc,])
  603. # get all children types
  604. tablefields = webnotes.model.meta.get_table_fields(dt)
  605. # load chilren
  606. doclist = DocList([doc,])
  607. for t in tablefields:
  608. doclist += getchildren(doc.name, t[0], t[1], dt, prefix=prefix)
  609. # import report_builder code
  610. if not from_get_obj:
  611. get_report_builder_code(doc)
  612. return doclist
  613. def getsingle(doctype):
  614. """get single doc as dict"""
  615. dataset = webnotes.conn.sql("select field, value from tabSingles where doctype=%s", doctype)
  616. return dict(dataset)