From e09cba5826123d0cdb863ac9aa5d80086d2697ae Mon Sep 17 00:00:00 2001
From: Arnaud Levy <contact@arnaudlevy.com>
Date: Mon, 13 Mar 2023 15:49:34 +0100
Subject: [PATCH] Duplicate posts

---
 .../communication/websites/posts_controller.rb     |  5 +++++
 app/models/communication/website/post.rb           | 14 ++++++++++++++
 .../communication/websites/posts/show.html.erb     |  1 +
 config/routes/admin/communication.rb               |  1 +
 4 files changed, 21 insertions(+)

diff --git a/app/controllers/admin/communication/websites/posts_controller.rb b/app/controllers/admin/communication/websites/posts_controller.rb
index 2bd77c053..f9c5a97ab 100644
--- a/app/controllers/admin/communication/websites/posts_controller.rb
+++ b/app/controllers/admin/communication/websites/posts_controller.rb
@@ -87,6 +87,11 @@ class Admin::Communication::Websites::PostsController < Admin::Communication::We
     end
   end
 
+  def duplicate
+    redirect_to [:admin, @post.duplicate],
+                notice: t('admin.successfully_duplicated_html', model: @post.to_s)
+  end
+
   def destroy
     @post.destroy_and_sync
     redirect_to admin_communication_website_posts_url, notice: t('admin.successfully_destroyed_html', model: @post.to_s)
diff --git a/app/models/communication/website/post.rb b/app/models/communication/website/post.rb
index e2095f2f0..723c144fa 100644
--- a/app/models/communication/website/post.rb
+++ b/app/models/communication/website/post.rb
@@ -145,6 +145,20 @@ class Communication::Website::Post < ApplicationRecord
     "#{Static.remove_trailing_slash website.url}#{Static.clean_path current_permalink_in_website(website).path}"
   end
 
+  def duplicate
+    post = self.dup
+    post.published = false
+    post.published_at = nil
+    post.save
+    blocks.ordered.each do |block|
+      b = block.duplicate
+      b.about = post
+      b.position = block.position
+      b.save
+    end
+    post
+  end
+
   def translated_author
     @translated_author ||= author.find_or_translate!(language)
   end
diff --git a/app/views/admin/communication/websites/posts/show.html.erb b/app/views/admin/communication/websites/posts/show.html.erb
index f1538493a..784067d93 100644
--- a/app/views/admin/communication/websites/posts/show.html.erb
+++ b/app/views/admin/communication/websites/posts/show.html.erb
@@ -53,6 +53,7 @@
 
 <% content_for :action_bar_left do %>
   <%= destroy_link @post %>
+  <%= duplicate_link @post %>
   <%= static_link static_admin_communication_website_post_path(@post) %>
 <% end %>
 
diff --git a/config/routes/admin/communication.rb b/config/routes/admin/communication.rb
index 1be8ac580..f6b9c1859 100644
--- a/config/routes/admin/communication.rb
+++ b/config/routes/admin/communication.rb
@@ -40,6 +40,7 @@ namespace :communication do
       member do
         get :static
         get :preview
+        post :duplicate
       end
     end
     resources :menus, controller: 'websites/menus', path: '/:lang/menus' do
-- 
GitLab