Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

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