Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

132 рядки
4.9 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. # Search
  23. from __future__ import unicode_literals
  24. import webnotes
  25. import webnotes.widgets.query_builder
  26. from webnotes.utils import cstr
  27. from startup.query_handlers import standard_queries
  28. # this is called when a new doctype is setup for search - to set the filters
  29. @webnotes.whitelist()
  30. def getsearchfields():
  31. sf = webnotes.conn.sql("""\
  32. SELECT value FROM `tabProperty Setter`
  33. WHERE doc_type=%s AND property='search_fields'""", \
  34. (webnotes.form_dict.get("doctype")))
  35. if not (sf and len(sf)>0 and sf[0][0]):
  36. sf = webnotes.conn.sql("select search_fields from tabDocType where name=%s", webnotes.form_dict.get("doctype"))
  37. sf = sf and sf[0][0] or ''
  38. sf = [s.strip() for s in sf.split(',')]
  39. if sf and sf[0]:
  40. res = webnotes.conn.sql("select fieldname, label, fieldtype, options from tabDocField where parent='%s' and fieldname in (%s)" % (webnotes.form_dict.get("doctype","_NA"), '"'+'","'.join(sf)+'"'))
  41. else:
  42. res = []
  43. res = [[c or '' for c in r] for r in res]
  44. for r in res:
  45. if r[2]=='Select' and r[3] and r[3].startswith('link:'):
  46. dt = r[3][5:]
  47. ol = webnotes.conn.sql("select name from `tab%s` where docstatus!=2 order by name asc" % dt)
  48. r[3] = '\n'.join([''] + [o[0] for o in ol])
  49. webnotes.response['searchfields'] = [['name', 'ID', 'Data', '']] + res
  50. # this is called by the Link Field
  51. @webnotes.whitelist()
  52. def search_link(dt, txt, query=None):
  53. search_widget(dt, txt, query, page_len=10)
  54. webnotes.response['results'] = build_for_autosuggest(webnotes.response["values"])
  55. # this is called by the search box
  56. @webnotes.whitelist()
  57. def search_widget(doctype, txt, query=None, searchfield="name", start=0, page_len=50):
  58. if query and query.split()[0].lower()!="select":
  59. webnotes.response["values"] = webnotes.get_method(query)(doctype, txt,
  60. searchfield, start, page_len)
  61. elif not query and doctype in standard_queries:
  62. search_widget(doctype, txt, standard_queries[doctype], searchfield, start, page_len)
  63. else:
  64. if query:
  65. webnotes.response["values"] = webnotes.conn.sql(scrub_custom_query(query,
  66. searchfield, txt))
  67. else:
  68. query = make_query(', '.join(get_std_fields_list(doctype, searchfield)), doctype,
  69. searchfield, txt, start, page_len)
  70. webnotes.widgets.query_builder.runquery(query)
  71. def make_query(fields, dt, key, txt, start, length):
  72. doctype = webnotes.get_doctype(dt)
  73. enabled_condition = ""
  74. if doctype.get({"parent":dt, "fieldname":"enabled", "fieldtype":"Check"}):
  75. enabled_condition = " AND ifnull(`tab%s`.`enabled`,0)=1" % dt
  76. if doctype.get({"parent":dt, "fieldname":"disabled", "fieldtype":"Check"}):
  77. enabled_condition = " AND ifnull(`tab%s`.`disabled`,0)!=1" % dt
  78. query = """select %(fields)s
  79. FROM `tab%(dt)s`
  80. WHERE `tab%(dt)s`.`%(key)s` LIKE '%(txt)s'
  81. AND `tab%(dt)s`.docstatus != 2 %(enabled_condition)s
  82. ORDER BY `tab%(dt)s`.`%(key)s`
  83. ASC LIMIT %(start)s, %(len)s """ % {
  84. 'fields': fields,
  85. 'dt': dt,
  86. 'key': key,
  87. 'txt': txt + '%',
  88. 'start': start,
  89. 'len': length,
  90. 'enabled_condition': enabled_condition
  91. }
  92. return query
  93. def get_std_fields_list(dt, key):
  94. # get additional search fields
  95. sflist = webnotes.conn.sql("select search_fields from tabDocType where name = '%s'" % dt)
  96. sflist = sflist and sflist[0][0] and sflist[0][0].split(',') or []
  97. sflist = ['name'] + sflist
  98. if not key in sflist:
  99. sflist = sflist + [key]
  100. return ['`tab%s`.`%s`' % (dt, f.strip()) for f in sflist]
  101. def build_for_autosuggest(res):
  102. results = []
  103. for r in res:
  104. info = ''
  105. if len(r) > 1:
  106. info = ', '.join([cstr(t) for t in r[1:]])
  107. if len(info) > 50:
  108. info = "<span title=\"%s\">%s...</span>" % (info, info[:50])
  109. results.append({'label':r[0], 'value':r[0], 'info':info})
  110. return results
  111. def scrub_custom_query(query, key, txt):
  112. if '%(key)s' in query:
  113. query = query.replace('%(key)s', key)
  114. if '%s' in query:
  115. query = query.replace('%s', ((txt or '') + '%'))
  116. return query