You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

пре 13 година
пре 12 година
пре 12 година
пре 12 година
пре 12 година
пре 13 година
пре 12 година
пре 12 година
пре 13 година
пре 12 година
пре 12 година
пре 12 година
пре 12 година
пре 12 година
пре 12 година
пре 12 година
пре 12 година
пре 12 година
пре 12 година
пре 12 година
пре 12 година
пре 12 година
пре 12 година
пре 12 година
пре 12 година
пре 12 година
пре 14 година
пре 13 година
пре 13 година
пре 13 година
пре 12 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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._dict(fielddata)
  67. else:
  68. self.fields = webnotes._dict()
  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 __repr__(self):
  92. return repr(self.fields)
  93. def __unicode__(self):
  94. return unicode(self.fields)
  95. def __eq__(self, other):
  96. if isinstance(other, Document):
  97. return self.fields == other.fields
  98. else:
  99. return False
  100. def __getstate__(self):
  101. return self.fields
  102. def __setstate__(self, d):
  103. self.fields = d
  104. def encode(self, encoding='utf-8'):
  105. """convert all unicode values to utf-8"""
  106. for key in self.fields:
  107. if isinstance(self.fields[key], unicode):
  108. self.fields[key] = self.fields[key].encode(encoding)
  109. def _loadfromdb(self, doctype = None, name = None):
  110. if name: self.name = name
  111. if doctype: self.doctype = doctype
  112. is_single = False
  113. try:
  114. is_single = webnotes.model.meta.is_single(self.doctype)
  115. except Exception, e:
  116. pass
  117. if is_single:
  118. self._loadsingle()
  119. else:
  120. dataset = webnotes.conn.sql('select * from `%s%s` where name="%s"' % (self._prefix, self.doctype, self.name.replace('"', '\"')))
  121. if not dataset:
  122. raise Exception, '[WNF] %s %s does not exist' % (self.doctype, self.name)
  123. self._load_values(dataset[0], webnotes.conn.get_description())
  124. def _load_values(self, data, description):
  125. if '__islocal' in self.fields:
  126. del self.fields['__islocal']
  127. for i in range(len(description)):
  128. v = data[i]
  129. self.fields[description[i][0]] = webnotes.conn.convert_to_simple_type(v)
  130. def _merge_values(self, data, description):
  131. for i in range(len(description)):
  132. v = data[i]
  133. if v: # only if value, over-write
  134. self.fields[description[i][0]] = webnotes.conn.convert_to_simple_type(v)
  135. def _loadsingle(self):
  136. self.name = self.doctype
  137. self.fields.update(getsingle(self.doctype))
  138. def __setattr__(self, name, value):
  139. # normal attribute
  140. if not self.__dict__.has_key('_Document__initialized'):
  141. self.__dict__[name] = value
  142. elif self.__dict__.has_key(name):
  143. self.__dict__[name] = value
  144. else:
  145. # field attribute
  146. f = self.__dict__['fields']
  147. f[name] = value
  148. def __getattr__(self, name):
  149. if self.__dict__.has_key(name):
  150. return self.__dict__[name]
  151. elif self.fields.has_key(name):
  152. return self.fields[name]
  153. else:
  154. return ''
  155. def _get_amended_name(self):
  156. am_id = 1
  157. am_prefix = self.amended_from
  158. if webnotes.conn.sql('select amended_from from `tab%s` where name = "%s"' % (self.doctype, self.amended_from))[0][0] or '':
  159. am_id = cint(self.amended_from.split('-')[-1]) + 1
  160. am_prefix = '-'.join(self.amended_from.split('-')[:-1]) # except the last hyphen
  161. self.name = am_prefix + '-' + str(am_id)
  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. elif autoname and autoname.startswith("naming_series:"):
  181. if not self.naming_series:
  182. # pick default naming series
  183. from webnotes.model.doctype import get_property
  184. self.naming_series = get_property(self.doctype, "options", "naming_series").split("\n")
  185. self.naming_series = self.naming_series[0] or self.naming_series[1]
  186. self.name = make_autoname(self.naming_series+'.#####')
  187. # based on expression
  188. elif autoname and autoname.startswith('eval:'):
  189. doc = self # for setting
  190. self.name = eval(autoname[5:])
  191. # call the method!
  192. elif autoname and autoname!='Prompt':
  193. self.name = make_autoname(autoname, self.doctype)
  194. # given
  195. elif self.fields.get('__newname',''):
  196. self.name = self.fields['__newname']
  197. # default name for table
  198. elif istable:
  199. self.name = make_autoname('#########', self.doctype)
  200. # unable to determine a name, use a serial number!
  201. if not self.name:
  202. self.name = make_autoname('#########', self.doctype)
  203. def _validate_name(self, case):
  204. if webnotes.conn.sql('select name from `tab%s` where name=%s' % (self.doctype,'%s'), self.name):
  205. raise NameError, 'Name %s already exists' % self.name
  206. # no name
  207. if not self.name: return 'No Name Specified for %s' % self.doctype
  208. # new..
  209. if self.name.startswith('New '+self.doctype):
  210. raise NameError, 'There were some errors setting the name, please contact the administrator'
  211. if case=='Title Case': self.name = self.name.title()
  212. if case=='UPPER CASE': self.name = self.name.upper()
  213. self.name = self.name.strip() # no leading and trailing blanks
  214. forbidden = ['%', "'", '"', '#', '*', '?', '`']
  215. for f in forbidden:
  216. if f in self.name:
  217. webnotes.msgprint('%s not allowed in ID (name)' % f, raise_exception =1)
  218. def _insert(self, autoname, istable, case='', make_autoname=1, keep_timestamps=False):
  219. # set name
  220. if make_autoname:
  221. self._set_name(autoname, istable)
  222. # validate name
  223. self._validate_name(case)
  224. # insert!
  225. if not keep_timestamps:
  226. if not self.owner:
  227. self.owner = webnotes.session['user']
  228. self.modified_by = webnotes.session['user']
  229. self.creation = self.modified = now()
  230. webnotes.conn.sql("insert into `tab%(doctype)s`" % self.fields \
  231. + """ (name, owner, creation, modified, modified_by)
  232. values (%(name)s, %(owner)s, %(creation)s, %(modified)s,
  233. %(modified_by)s)""", self.fields)
  234. def _update_single(self, link_list):
  235. update_str = ["(%s, 'modified', %s)",]
  236. values = [self.doctype, now()]
  237. webnotes.conn.sql("delete from tabSingles where doctype='%s'" % self.doctype)
  238. for f in self.fields.keys():
  239. if not (f in ('modified', 'doctype', 'name', 'perm', 'localname', 'creation'))\
  240. and (not f.startswith('__')): # fields not saved
  241. # validate links
  242. if link_list and link_list.get(f):
  243. self.fields[f] = self._validate_link(link_list[f][0], self.fields[f])
  244. if self.fields[f]==None:
  245. update_str.append("(%s,%s,NULL)")
  246. values.append(self.doctype)
  247. values.append(f)
  248. else:
  249. update_str.append("(%s,%s,%s)")
  250. values.append(self.doctype)
  251. values.append(f)
  252. values.append(self.fields[f])
  253. webnotes.conn.sql("insert into tabSingles(doctype, field, value) values %s" % (', '.join(update_str)), values)
  254. def validate_links(self, link_list):
  255. err_list = []
  256. for f in self.fields.keys():
  257. # validate links
  258. old_val = self.fields[f]
  259. if link_list and link_list.get(f):
  260. self.fields[f] = self._validate_link(link_list[f][0], self.fields[f])
  261. if old_val and not self.fields[f]:
  262. s = link_list[f][1] + ': ' + old_val
  263. err_list.append(s)
  264. return err_list
  265. def make_link_list(self):
  266. res = webnotes.model.meta.get_link_fields(self.doctype)
  267. link_list = {}
  268. for i in res: link_list[i[0]] = (i[1], i[2]) # options, label
  269. return link_list
  270. def _validate_link(self, dt, dn):
  271. if not dt: return dn
  272. if not dn: return None
  273. if dt=="[Select]": return dn
  274. if dt.lower().startswith('link:'):
  275. dt = dt[5:]
  276. if '\n' in dt:
  277. dt = dt.split('\n')[0]
  278. tmp = webnotes.conn.sql("""SELECT name FROM `tab%s`
  279. WHERE name = %s""" % (dt, '%s'), dn)
  280. return tmp and tmp[0][0] or ''# match case
  281. def _update_values(self, issingle, link_list, ignore_fields=0, keep_timestamps=False):
  282. if issingle:
  283. self._update_single(link_list)
  284. else:
  285. update_str, values = [], []
  286. # set modified timestamp
  287. if self.modified and not keep_timestamps:
  288. self.modified = now()
  289. self.modified_by = webnotes.session['user']
  290. fields_list = ignore_fields and self.get_valid_fields() or self.fields.keys()
  291. for f in fields_list:
  292. if (not (f in ('doctype', 'name', 'perm', 'localname',
  293. 'creation','_user_tags'))) and (not f.startswith('__')):
  294. # fields not saved
  295. # validate links
  296. if link_list and link_list.get(f):
  297. self.fields[f] = self._validate_link(link_list[f][0],
  298. self.fields.get(f))
  299. if self.fields.get(f) is None or self.fields.get(f)=='':
  300. update_str.append("`%s`=NULL" % f)
  301. else:
  302. values.append(self.fields.get(f))
  303. update_str.append("`%s`=%s" % (f, '%s'))
  304. if values:
  305. values.append(self.name)
  306. r = webnotes.conn.sql("update `tab%s` set %s where name=%s" % \
  307. (self.doctype, ', '.join(update_str), "%s"), values)
  308. def get_valid_fields(self):
  309. global valid_fields_map
  310. if not valid_fields_map.get(self.doctype):
  311. import webnotes.model.doctype
  312. if cint(webnotes.conn.get_value("DocType", self.doctype, "issingle")):
  313. doctypelist = webnotes.model.doctype.get(self.doctype)
  314. valid_fields_map[self.doctype] = doctypelist.get_fieldnames({
  315. "fieldtype": ["not in", webnotes.model.no_value_fields]})
  316. else:
  317. valid_fields_map[self.doctype] = \
  318. webnotes.conn.get_table_columns(self.doctype)
  319. return valid_fields_map.get(self.doctype)
  320. def save(self, new=0, check_links=1, ignore_fields=0, make_autoname=1,
  321. keep_timestamps=False):
  322. res = webnotes.model.meta.get_dt_values(self.doctype,
  323. 'autoname, issingle, istable, name_case', as_dict=1)
  324. res = res and res[0] or {}
  325. if new:
  326. self.fields["__islocal"] = 1
  327. # add missing parentinfo (if reqd)
  328. if self.parent and not (self.parenttype and self.parentfield):
  329. self.update_parentinfo()
  330. if self.parent and not self.idx:
  331. self.set_idx()
  332. # if required, make new
  333. if self.fields.get('__islocal') and (not res.get('issingle')):
  334. r = self._insert(res.get('autoname'), res.get('istable'), res.get('name_case'),
  335. make_autoname, keep_timestamps = keep_timestamps)
  336. if r:
  337. return r
  338. else:
  339. if not res.get('issingle') and not webnotes.conn.exists(self.doctype, self.name):
  340. webnotes.msgprint("""This document was updated before your change. Please refresh before saving.""", raise_exception=1)
  341. # save the values
  342. self._update_values(res.get('issingle'),
  343. check_links and self.make_link_list() or {}, ignore_fields=ignore_fields,
  344. keep_timestamps=keep_timestamps)
  345. self._clear_temp_fields()
  346. def insert(self):
  347. self.fields['__islocal'] = 1
  348. self.save()
  349. return self
  350. def update_parentinfo(self):
  351. """update parent type and parent field, if not explicitly specified"""
  352. tmp = webnotes.conn.sql("""select parent, fieldname from tabDocField
  353. where fieldtype='Table' and options=%s""", self.doctype)
  354. if len(tmp)==0:
  355. raise Exception, 'Incomplete parent info in child table (%s, %s)' \
  356. % (self.doctype, self.fields.get('name', '[new]'))
  357. elif len(tmp)>1:
  358. raise Exception, 'Ambiguous parent info (%s, %s)' \
  359. % (self.doctype, self.fields.get('name', '[new]'))
  360. else:
  361. self.parenttype = tmp[0][0]
  362. self.parentfield = tmp[0][1]
  363. def set_idx(self):
  364. """set idx"""
  365. self.idx = (webnotes.conn.sql("""select max(idx) from `tab%s`
  366. where parent=%s and parentfield=%s""" % (self.doctype, '%s', '%s'),
  367. (self.parent, self.parentfield))[0][0] or 0) + 1
  368. def _clear_temp_fields(self):
  369. # clear temp stuff
  370. keys = self.fields.keys()
  371. for f in keys:
  372. if f.startswith('__'):
  373. del self.fields[f]
  374. def clear_table(self, doclist, tablefield, save=0):
  375. """
  376. Clears the child records from the given `doclist` for a particular `tablefield`
  377. """
  378. from webnotes.model.utils import getlist
  379. table_list = getlist(doclist, tablefield)
  380. delete_list = [d.name for d in table_list]
  381. if delete_list:
  382. #filter doclist
  383. doclist = filter(lambda d: d.name not in delete_list, doclist)
  384. # delete from db
  385. webnotes.conn.sql("""\
  386. delete from `tab%s`
  387. where parent=%s and parenttype=%s"""
  388. % (table_list[0].doctype, '%s', '%s'),
  389. (self.name, self.doctype))
  390. self.fields['__unsaved'] = 1
  391. return webnotes.doclist(doclist)
  392. def addchild(self, fieldname, childtype = '', doclist=None):
  393. """
  394. Returns a child record of the give `childtype`.
  395. * if local is set, it does not save the record
  396. * if doclist is passed, it append the record to the doclist
  397. """
  398. from webnotes.model.doc import Document
  399. d = Document()
  400. d.parent = self.name
  401. d.parenttype = self.doctype
  402. d.parentfield = fieldname
  403. d.doctype = childtype
  404. d.docstatus = 0;
  405. d.name = ''
  406. d.owner = webnotes.session['user']
  407. d.fields['__islocal'] = 1 # for Client to identify unsaved doc
  408. if doclist != None:
  409. doclist.append(d)
  410. return d
  411. def get_values(self):
  412. """get non-null fields dict withouth standard fields"""
  413. from webnotes.model import default_fields
  414. ret = {}
  415. for key in self.fields:
  416. if key not in default_fields and self.fields[key]:
  417. ret[key] = self.fields[key]
  418. return ret
  419. def addchild(parent, fieldname, childtype = '', doclist=None):
  420. """
  421. Create a child record to the parent doc.
  422. Example::
  423. c = Document('Contact','ABC')
  424. d = addchild(c, 'contact_updates', 'Contact Update')
  425. d.last_updated = 'Phone call'
  426. d.save(1)
  427. """
  428. return parent.addchild(fieldname, childtype, doclist)
  429. def make_autoname(key, doctype=''):
  430. """
  431. Creates an autoname from the given key:
  432. **Autoname rules:**
  433. * The key is separated by '.'
  434. * '####' represents a series. The string before this part becomes the prefix:
  435. Example: ABC.#### creates a series ABC0001, ABC0002 etc
  436. * 'MM' represents the current month
  437. * 'YY' and 'YYYY' represent the current year
  438. *Example:*
  439. * DE/./.YY./.MM./.##### will create a series like
  440. DE/09/01/0001 where 09 is the year, 01 is the month and 0001 is the series
  441. """
  442. n = ''
  443. l = key.split('.')
  444. for e in l:
  445. en = ''
  446. if e.startswith('#'):
  447. digits = len(e)
  448. en = getseries(n, digits, doctype)
  449. elif e=='YY':
  450. import time
  451. en = time.strftime('%y')
  452. elif e=='MM':
  453. import time
  454. en = time.strftime('%m')
  455. elif e=='YYYY':
  456. import time
  457. en = time.strftime('%Y')
  458. else: en = e
  459. n+=en
  460. return n
  461. def getseries(key, digits, doctype=''):
  462. # series created ?
  463. if webnotes.conn.sql("select name from tabSeries where name='%s'" % key):
  464. # yes, update it
  465. webnotes.conn.sql("update tabSeries set current = current+1 where name='%s'" % key)
  466. # find the series counter
  467. r = webnotes.conn.sql("select current from tabSeries where name='%s'" % key)
  468. n = r[0][0]
  469. else:
  470. # no, create it
  471. webnotes.conn.sql("insert into tabSeries (name, current) values ('%s', 1)" % key)
  472. n = 1
  473. return ('%0'+str(digits)+'d') % n
  474. def getchildren(name, childtype, field='', parenttype='', from_doctype=0, prefix='tab'):
  475. import webnotes
  476. from webnotes.model.doclist import DocList
  477. condition = ""
  478. values = []
  479. if field:
  480. condition += ' and parentfield=%s '
  481. values.append(field)
  482. if parenttype:
  483. condition += ' and parenttype=%s '
  484. values.append(parenttype)
  485. dataset = webnotes.conn.sql("""select * from `%s%s` where parent=%s %s order by idx""" \
  486. % (prefix, childtype, "%s", condition), tuple([name]+values))
  487. desc = webnotes.conn.get_description()
  488. l = DocList()
  489. for i in dataset:
  490. d = Document()
  491. d.doctype = childtype
  492. d._load_values(i, desc)
  493. l.append(d)
  494. return l
  495. def check_page_perm(doc):
  496. if doc.name=='Login Page':
  497. return
  498. if doc.publish:
  499. return
  500. if not webnotes.conn.sql("select name from `tabPage Role` where parent=%s and role='Guest'", doc.name):
  501. webnotes.response['403'] = 1
  502. raise webnotes.PermissionError, '[WNF] No read permission for %s %s' % ('Page', doc.name)
  503. def get_report_builder_code(doc):
  504. if doc.doctype=='Search Criteria':
  505. from webnotes.model.code import get_code
  506. if doc.standard != 'No':
  507. doc.report_script = get_code(doc.module, 'Search Criteria', doc.name, 'js')
  508. doc.custom_query = get_code(doc.module, 'Search Criteria', doc.name, 'sql')
  509. def get(dt, dn='', with_children = 1, from_controller = 0, prefix = 'tab'):
  510. """
  511. Returns a doclist containing the main record and all child records
  512. """
  513. import webnotes
  514. import webnotes.model
  515. from webnotes.model.doclist import DocList
  516. dn = dn or dt
  517. # load the main doc
  518. doc = Document(dt, dn, prefix=prefix)
  519. if dt=='Page' and webnotes.session['user'] == 'Guest':
  520. check_page_perm(doc)
  521. if not with_children:
  522. # done
  523. return DocList([doc,])
  524. # get all children types
  525. tablefields = webnotes.model.meta.get_table_fields(dt)
  526. # load chilren
  527. doclist = DocList([doc,])
  528. for t in tablefields:
  529. doclist += getchildren(doc.name, t[0], t[1], dt, prefix=prefix)
  530. # import report_builder code
  531. if not from_controller:
  532. get_report_builder_code(doc)
  533. return doclist
  534. def getsingle(doctype):
  535. """get single doc as dict"""
  536. dataset = webnotes.conn.sql("select field, value from tabSingles where doctype=%s", doctype)
  537. return dict(dataset)
  538. def copy_common_fields(from_doc, to_doc):
  539. from webnotes.model import default_fields
  540. doctype_list = webnotes.get_doctype(to_doc.doctype)
  541. for fieldname, value in from_doc.fields.items():
  542. if fieldname in default_fields:
  543. continue
  544. if doctype_list.get_field(fieldname) and to_doc.fields[fieldname] != value:
  545. to_doc.fields[fieldname] = value