builder.rb 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. class CustomWizard::Builder
  2. attr_accessor :wizard, :updater, :submissions
  3. def initialize(user, wizard_id)
  4. data = PluginStore.get('custom_wizard', wizard_id)
  5. return if data.blank?
  6. @steps = data['steps']
  7. @wizard = CustomWizard::Wizard.new(user, data)
  8. @submissions = Array.wrap(PluginStore.get("#{wizard_id}_submissions", user.id))
  9. end
  10. def self.sorted_handlers
  11. @sorted_handlers ||= []
  12. end
  13. def self.step_handlers
  14. sorted_handlers.map { |h| { wizard_id: h[:wizard_id], block: h[:block] } }
  15. end
  16. def self.add_step_handler(priority = 0, wizard_id, &block)
  17. sorted_handlers << { priority: priority, wizard_id: wizard_id, block: block }
  18. @sorted_handlers.sort_by! { |h| -h[:priority] }
  19. end
  20. def self.sorted_field_validators
  21. @sorted_field_validators ||= []
  22. end
  23. def self.field_validators
  24. sorted_field_validators.map { |h| { type: h[:type], block: h[:block] } }
  25. end
  26. def self.add_field_validator(priority = 0, type, &block)
  27. sorted_field_validators << { priority: priority, type: type, block: block }
  28. @sorted_field_validators.sort_by! { |h| -h[:priority] }
  29. end
  30. USER_FIELDS = ['name', 'username', 'email', 'date_of_birth', 'title', 'locale']
  31. PROFILE_FIELDS = ['location', 'website', 'bio_raw', 'profile_background', 'card_background']
  32. def self.fill_placeholders(string, user, data)
  33. result = string.gsub(/u\{(.*?)\}/) do |match|
  34. result = ''
  35. result = user.send($1) if USER_FIELDS.include?($1)
  36. result = user.user_profile.send($1) if PROFILE_FIELDS.include?($1)
  37. result
  38. end
  39. result.gsub!(/w\{(.*?)\}/) { |match| data[$1.to_sym] }
  40. end
  41. def build
  42. unless (@wizard.completed? && !@wizard.multiple_submissions && !@wizard.user.admin) || !@steps || !@wizard.permitted?
  43. @steps.each do |step_template|
  44. @wizard.append_step(step_template['id']) do |step|
  45. step.title = step_template['title'] if step_template['title']
  46. step.description = step_template['description'] if step_template['description']
  47. step.banner = step_template['banner'] if step_template['banner']
  48. step.key = step_template['key'] if step_template['key']
  49. if step_template['fields'] && step_template['fields'].length
  50. step_template['fields'].each do |field_template|
  51. append_field(step, step_template, field_template)
  52. end
  53. end
  54. step.on_update do |updater|
  55. @updater = updater
  56. user = @wizard.user
  57. if step_template['fields'] && step_template['fields'].length
  58. step_template['fields'].each do |field|
  59. validate_field(field, updater, step_template) if field['type'] != 'text-only'
  60. end
  61. end
  62. next if updater.errors.any?
  63. CustomWizard::Builder.step_handlers.each do |handler|
  64. if handler[:wizard_id] == @wizard.id
  65. handler[:block].call(self)
  66. end
  67. end
  68. next if updater.errors.any?
  69. data = updater.fields.to_h
  70. ## if the wizard has data from the previous steps make that accessible to the actions.
  71. if @submissions && @submissions.last && !@submissions.last.key?("submitted_at")
  72. submission = @submissions.last
  73. data = submission.merge(data)
  74. end
  75. if step_template['actions'] && step_template['actions'].length && data
  76. step_template['actions'].each do |action|
  77. self.send(action['type'].to_sym, user, action, data)
  78. end
  79. end
  80. final_step = updater.step.next.nil?
  81. if @wizard.save_submissions && updater.errors.empty?
  82. save_submissions(data, final_step)
  83. elsif final_step
  84. PluginStore.remove("#{@wizard.id}_submissions", @wizard.user.id)
  85. end
  86. if final_step && @wizard.id === @wizard.user.custom_fields['redirect_to_wizard']
  87. @wizard.user.custom_fields.delete('redirect_to_wizard');
  88. @wizard.user.save_custom_fields(true)
  89. end
  90. if updater.errors.empty?
  91. redirect_to = data['redirect_to']
  92. updater.result = { redirect_to: redirect_to } if redirect_to
  93. end
  94. end
  95. end
  96. end
  97. end
  98. @wizard
  99. end
  100. def append_field(step, step_template, field_template)
  101. params = {
  102. id: field_template['id'],
  103. type: field_template['type'],
  104. required: field_template['required']
  105. }
  106. params[:label] = field_template['label'] if field_template['label']
  107. params[:description] = field_template['description'] if field_template['description']
  108. params[:image] = field_template['image'] if field_template['image']
  109. params[:key] = field_template['key'] if field_template['key']
  110. ## Load previously submitted values
  111. if @submissions.last && !@submissions.last.key?("submitted_at")
  112. submission = @submissions.last
  113. params[:value] = submission[field_template['id']] if submission[field_template['id']]
  114. end
  115. ## If a field updates a profile field, load the current value
  116. if step_template['actions'] && step_template['actions'].any?
  117. profile_actions = step_template['actions'].select { |a| a['type'] === 'update_profile' }
  118. if profile_actions.any?
  119. profile_actions.each do |action|
  120. if update = action['profile_updates'].select { |u| u['key'] === field_template['id'] }.first
  121. params[:value] = prefill_profile_field(update)
  122. end
  123. end
  124. end
  125. end
  126. if field_template['type'] === 'checkbox'
  127. params[:value] = standardise_boolean(params[:value])
  128. end
  129. field = step.add_field(params)
  130. if field_template['type'] === 'dropdown'
  131. build_dropdown_list(field, field_template)
  132. end
  133. end
  134. def prefill_profile_field(update)
  135. attribute = update['value']
  136. custom_field = update['value_custom']
  137. user_field = update['user_field']
  138. if user_field || custom_field
  139. UserCustomField.where(user_id: @wizard.user.id, name: user_field || custom_field).pluck(:value)
  140. elsif UserProfile.column_names.include? attribute
  141. UserProfile.find_by(user_id: @wizard.user.id).send(attribute)
  142. elsif User.column_names.include? attribute
  143. User.find(@wizard.user.id).send(attribute)
  144. end
  145. end
  146. def build_dropdown_list(field, field_template)
  147. field.dropdown_none = field_template['dropdown_none'] if field_template['dropdown_none']
  148. if field_template['choices'] && field_template['choices'].length > 0
  149. field_template['choices'].each do |c|
  150. field.add_choice(c['key'], label: c['value'])
  151. end
  152. elsif field_template['choices_key'] && field_template['choices_key'].length > 0
  153. choices = I18n.t(field_template['choices_key'])
  154. if choices.is_a?(Hash)
  155. choices.each { |k, v| field.add_choice(k, label: v) }
  156. end
  157. elsif field_template['choices_preset'] && field_template['choices_preset'].length > 0
  158. objects = []
  159. if field_template['choices_preset'] === 'categories'
  160. objects = Site.new(Guardian.new(@wizard.user)).categories
  161. end
  162. if field_template['choices_filters'] && field_template['choices_filters'].length > 0
  163. field_template['choices_filters'].each do |f|
  164. objects.reject! do |o|
  165. if f['key'].include? 'custom_fields'
  166. o.custom_fields[f['key'].split('.')[1]].to_s != f['value'].to_s
  167. else
  168. o[prop].to_s != f['value'].to_s
  169. end
  170. end
  171. end
  172. end
  173. if objects.length > 0
  174. objects.each do |o|
  175. field.add_choice(o.id, label: o.name)
  176. end
  177. end
  178. end
  179. end
  180. def validate_field(field, updater, step_template)
  181. value = updater.fields[field['id']]
  182. min_length = field['min_length']
  183. if min_length && value.is_a?(String) && value.length < min_length.to_i
  184. label = field['label'] || I18n.t("#{field['key']}.label")
  185. updater.errors.add(field['id'].to_s, I18n.t('wizard.field.too_short', label: label, min: min_length.to_i))
  186. end
  187. ## ensure all checkboxes are booleans
  188. if field['type'] === 'checkbox'
  189. updater.fields[field['id']] = standardise_boolean(value)
  190. end
  191. CustomWizard::Builder.field_validators.each do |validator|
  192. if field['type'] === validator[:type]
  193. validator[:block].call(field, updater, step_template)
  194. end
  195. end
  196. end
  197. def standardise_boolean(value)
  198. !!HasCustomFields::Helpers::CUSTOM_FIELD_TRUE.include?(value)
  199. end
  200. def create_topic(user, action, data)
  201. if action['custom_title']
  202. title = CustomWizard::Builder.fill_placeholders(action['custom_title'], user, data)
  203. else
  204. title = data[action['title']]
  205. end
  206. if action['post_builder']
  207. post = CustomWizard::Builder.fill_placeholders(action['post_template'], user, data)
  208. else
  209. post = data[action['post']]
  210. end
  211. if title
  212. params = {
  213. title: title,
  214. raw: post,
  215. skip_validations: true
  216. }
  217. if action['custom_category_enabled'] &&
  218. !action['custom_category_wizard_field'] &&
  219. action['custom_category_user_field_key']
  220. if action['custom_category_user_field_key'].include?('custom_fields')
  221. field = action['custom_category_user_field_key'].split('.').last
  222. category_id = user.custom_fields[field]
  223. else
  224. category_id = user.send(action['custom_category_user_field_key'])
  225. end
  226. else
  227. category_id = action['category_id']
  228. end
  229. params[:category] = category_id
  230. topic_custom_fields = {}
  231. if action['add_fields']
  232. action['add_fields'].each do |field|
  233. value = field['value_custom'] ? field['value_custom'] : data[field['value']]
  234. key = field['key']
  235. if key && (value.present? || value === false)
  236. if key.include?('custom_fields')
  237. keyArr = key.split('.')
  238. if keyArr.length === 3
  239. custom_key = keyArr.last
  240. type = keyArr.first
  241. if type === 'topic'
  242. topic_custom_fields[custom_key] = value
  243. elsif type === 'post'
  244. params[:custom_fields] ||= {}
  245. params[:custom_fields][custom_key.to_sym] = value
  246. end
  247. end
  248. else
  249. params[key.to_sym] = value
  250. end
  251. end
  252. end
  253. end
  254. creator = PostCreator.new(user, params)
  255. post = creator.create
  256. if creator.errors.present?
  257. updater.errors.add(:create_topic, creator.errors.full_messages.join(" "))
  258. else
  259. if topic_custom_fields.present?
  260. topic_custom_fields.each do |k, v|
  261. post.topic.custom_fields[k] = v
  262. end
  263. post.topic.save_custom_fields(true)
  264. end
  265. unless action['skip_redirect']
  266. data['redirect_to'] = post.topic.url
  267. end
  268. end
  269. end
  270. end
  271. def send_message(user, action, data)
  272. title = data[action['title']]
  273. if action['post_builder']
  274. post = CustomWizard::Builder.fill_placeholders(action['post_template'], user, data)
  275. else
  276. post = data[action['post']]
  277. end
  278. if title && post
  279. creator = PostCreator.new(user,
  280. title: title,
  281. raw: post,
  282. archetype: Archetype.private_message,
  283. target_usernames: action['username']
  284. )
  285. post = creator.create
  286. if creator.errors.present?
  287. updater.errors.add(:send_message, creator.errors.full_messages.join(" "))
  288. else
  289. unless action['skip_redirect']
  290. data['redirect_to'] = post.topic.url
  291. end
  292. end
  293. end
  294. end
  295. def update_profile(user, action, data)
  296. return unless action['profile_updates'].length
  297. attributes = {}
  298. custom_fields = {}
  299. action['profile_updates'].each do |pu|
  300. value = pu['value']
  301. custom_field = pu['value_custom']
  302. user_field = pu['user_field']
  303. key = pu['key']
  304. if user_field || custom_field
  305. custom_fields[user_field || custom_field] = data[key]
  306. else
  307. attributes[value.to_sym] = data[key]
  308. end
  309. end
  310. if custom_fields.present?
  311. attributes[:custom_fields] = custom_fields
  312. end
  313. if attributes.present?
  314. user_updater = UserUpdater.new(user, user)
  315. user_updater.update(attributes)
  316. end
  317. end
  318. def save_submissions(data, final_step)
  319. if final_step
  320. data['submitted_at'] = Time.now.iso8601
  321. end
  322. if data.present?
  323. @submissions.pop(1) if @wizard.unfinished?
  324. @submissions.push(data)
  325. PluginStore.set("#{@wizard.id}_submissions", @wizard.user.id, @submissions)
  326. end
  327. end
  328. end