Skip to content

Commit

Permalink
Fix #41 - Created date should not get reset when updating a detached …
Browse files Browse the repository at this point in the history
…object.
  • Loading branch information
snimavat committed Oct 6, 2017
1 parent c4e8cbf commit 46a449b
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 8 deletions.
27 changes: 22 additions & 5 deletions src/groovy/grails/plugin/audittrail/AuditTrailHelper.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,28 @@ class AuditTrailHelper implements ApplicationContextAware, InitializingBean {
return valToSet
}

boolean isNewEntity(entity) {

def session = applicationContext.sessionFactory.currentSession
def entry = session.persistenceContext.getEntry(entity)
return !entry
/**
* Checks if the given domain instance is new
*
* it first checks for the createdDate property, if property exists and is not null, returns false.
* else If createdDate property is not defined, it checks if the domain is attached to session and exists in persistence context.
*
* @param entity
* @return boolean
*/
boolean isNewEntity(def entity) {
String createdDateFieldName = fieldPropsMap.get("createdDate").name
MetaProperty createdDateProperty = entity.hasProperty(createdDateFieldName)

//see issue#41
if(createdDateProperty != null) {
Date existingValue = entity.getProperty(createdDateFieldName)
return (existingValue == null)
} else {
def session = applicationContext.sessionFactory.currentSession
def entry = session.persistenceContext.getEntry(entity)
return !entry
}
}

boolean isDisableAuditStamp(entity) {
Expand Down
45 changes: 43 additions & 2 deletions test/integration/nine/tests/AuditStampTests.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ import grails.test.mixin.integration.IntegrationTestMixin
import groovy.sql.Sql
import org.apache.commons.lang.time.DateUtils
import org.codehaus.groovy.grails.commons.GrailsApplication
import org.codehaus.groovy.grails.plugins.DomainClassGrailsPlugin
import org.codehaus.groovy.grails.web.binding.DefaultASTDatabindingHelper
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.authority.AuthorityUtils
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.context.SecurityContextHolder as SCH
import spock.lang.Issue

/**
* Uses the doms domain to test the created by and edited by fields and CreateEditeStamp ASTrandformer
Expand Down Expand Up @@ -53,8 +55,11 @@ class AuditStampTests {
assert art.constraints.updatedBy.getAppliedConstraint('max').maxValue == 90000l

def l = TestDomain."${DefaultASTDatabindingHelper.DEFAULT_DATABINDING_WHITELIST}"
assert l == ['name']
assert l.size() == 1
assert l.contains("name")
assert !l.contains("createdDate")
assert !l.contains("createdBy")
assert !l.contains("editedDate")
assert !l.contains("updatedBy")

//def prop= art.getPropertyByName("updatedBy")
}
Expand Down Expand Up @@ -144,6 +149,42 @@ class AuditStampTests {
assert authUser.id == data.whoUpdated
}

@Issue("https://github.com/9ci/grails-audit-trail/issues/41")
void test_update_doesnot_change_createdDate_when_session_is_cleared() {
Date today = new Date()
Date yesterday = today - 1
java.sql.Date yesterdaySQL = new java.sql.Date(yesterday.getTime())
Sql sql = new Sql(sessionFactory.getCurrentSession().connection())

sql.execute("insert into TestDomains (oid,version,name, createdBy, createdDate, whoUpdated, editedDate) "+
" values (?,?,?,?,?,?,?)", [2,0,"xxx", 0, yesterdaySQL,0, yesterdaySQL])


TestDomain dom = TestDomain.get(2)
assert dom != null
dom.name="new name"

//clear session to test that createdDate does not get reset for detached objects.
sessionFactory.currentSession.clear()
DomainClassGrailsPlugin.PROPERTY_INSTANCE_MAP.get().clear()

dom.save(flush:true,failOnError:true)

String sqlCall = 'select oid, createdBy, createdDate, whoUpdated, editedDate from TestDomains where oid = ' + dom.id

Map data = sql.firstRow(sqlCall)
assert data != null
assert dom.id == data.oid
assert data.editedDate != null
assert data.createdDate != null

assert DateUtils.isSameDay(data.editedDate, new Date()), "edited Date should have been set to today"
assert DateUtils.isSameDay(data.createdDate, yesterday), "Created date should have been changed"

def authUser = login()
assert authUser.id == data.whoUpdated
}

void test_disableAuditTrailStamp_fail(){
def d = new TestDomain()
d.properties = [name:'test']
Expand Down
5 changes: 4 additions & 1 deletion test/integration/nine/tests/ChildDomTests.groovy
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package nine.tests

import org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass
import org.codehaus.groovy.grails.commons.GrailsDomainClass

class ChildDomTests extends BaseInt {

def grailsApplication

void testConstaints() {
def art = grailsApplication.getDomainClass("nine.tests.ChildDom")
DefaultGrailsDomainClass art = grailsApplication.getDomainClass("nine.tests.ChildDom")
assert art
assert art.constraints.childProp.getAppliedConstraint('nullable').isNullable() == false
assert art.constraints.childProp.getAppliedConstraint('blank').isBlank() == false
Expand Down

0 comments on commit 46a449b

Please sign in to comment.