builder.rb 11 KB

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