builder.rb 11 KB

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