From f578bd198b4b04e168876928e490ca3bf139db2d Mon Sep 17 00:00:00 2001
From: Alex Shulgin <ash@commandprompt.com>
Date: Tue, 9 Aug 2011 10:43:17 +0300
Subject: [PATCH] Fixed attachments handling when receiving a new issue by
 mail.

Creates a new journal if there is no one already.
---
 app/models/issue.rb        |   13 ++++++++-----
 app/models/mail_handler.rb |   10 +++++++++-
 2 files changed, 17 insertions(+), 6 deletions(-)

diff --git a/app/models/issue.rb b/app/models/issue.rb
index 75a3cc4..3a39a2f 100644
--- a/app/models/issue.rb
+++ b/app/models/issue.rb
@@ -833,17 +833,20 @@ class Issue < ActiveRecord::Base
   end
 
   def attachment_added(obj)
+    init_journal(User.current) unless @current_journal
     @current_journal.details << JournalDetail.new(:property => 'attachment',
                                                   :prop_key => obj.id,
                                                   :value => obj.filename)
   end
 
   def attachment_removed(obj)
-    journal = init_journal(User.current)
-    journal.details << JournalDetail.new(:property => 'attachment',
-                                         :prop_key => obj.id,
-                                         :old_value => obj.filename)
-    journal.save
+    init_journal(User.current) unless @current_journal
+    @current_journal.details << JournalDetail.new(:property => 'attachment',
+                                                  :prop_key => obj.id,
+                                                  :old_value => obj.filename)
+    # Currently, this is only triggered from attachments#destroy, so
+    # there's no one else to save the issue's journal.
+    @current_journal.save
   end
 
   # Default assignment based on category
diff --git a/app/models/mail_handler.rb b/app/models/mail_handler.rb
index c75ba23..fde76c9 100644
--- a/app/models/mail_handler.rb
+++ b/app/models/mail_handler.rb
@@ -138,7 +138,12 @@ class MailHandler < ActionMailer::Base
     # add To and Cc as watchers before saving so the watchers can reply to Redmine
     add_watchers(issue)
     issue.save!
-    add_attachments(issue)
+
+    if add_attachments(issue)
+      # Adding attachments to a new issue creates a journal.  We need
+      # to save the record to trigger an issue update mail.
+      issue.save!
+    end
     logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info
     issue
   end
@@ -198,13 +203,16 @@ class MailHandler < ActionMailer::Base
   end
 
   def add_attachments(obj)
+    added = false
     if email.has_attachments? || email.multipart?
       email.attachments.each do |attachment|
         obj.attachments.create(:file => attachment,
                                :author => user,
                                :content_type => attachment.content_type)
+        added = true
       end
     end
+    added
   end
 
   # Adds To and Cc as watchers of the given object if the sender has the
-- 
1.7.5.4

