Skip to content

Commit 651c235

Browse files
authored
feat: automatically archive envelopes when category is archived (#759)
With this change, envelopes are archived automatically if their parent category is archived.
1 parent 5ca0a5e commit 651c235

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

pkg/models/category.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,27 @@ func (c *Category) links(tx *gorm.DB) {
4848
c.Links.Self = fmt.Sprintf("%s/v1/categories/%s", url, c.ID)
4949
c.Links.Envelopes = fmt.Sprintf("%s/v1/envelopes?category=%s", url, c.ID)
5050
}
51+
52+
// BeforeUpdate archives all envelopes when the category is archived.
53+
func (c *Category) BeforeUpdate(tx *gorm.DB) (err error) {
54+
if tx.Statement.Changed("Hidden") && !c.Hidden {
55+
var envelopes []Envelope
56+
err = tx.Model(&Envelope{EnvelopeCreate: EnvelopeCreate{
57+
CategoryID: c.ID,
58+
}}).
59+
Find(&envelopes).Error
60+
if err != nil {
61+
return
62+
}
63+
64+
for _, e := range envelopes {
65+
e.Hidden = true
66+
err = tx.Model(&e).Updates(&e).Error
67+
if err != nil {
68+
return
69+
}
70+
}
71+
}
72+
73+
return nil
74+
}

pkg/models/category_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package models_test
2+
3+
import (
4+
"github.com/envelope-zero/backend/v3/pkg/models"
5+
"github.com/stretchr/testify/assert"
6+
)
7+
8+
func (suite *TestSuiteStandard) TestCategoryArchiveArchivesEnvelopes() {
9+
category := suite.createTestCategory(models.CategoryCreate{
10+
BudgetID: suite.createTestBudget(models.BudgetCreate{}).ID,
11+
})
12+
13+
envelope := suite.createTestEnvelope(models.EnvelopeCreate{
14+
CategoryID: category.ID,
15+
Hidden: false,
16+
})
17+
assert.False(suite.T(), envelope.Hidden, "Envelope archived on creation, it should not be")
18+
19+
// Archive the category
20+
err := suite.db.Model(&category).Select("Hidden").Updates(models.Category{CategoryCreate: models.CategoryCreate{Hidden: true}}).Error
21+
assert.Nil(suite.T(), err)
22+
23+
// Verify that the envelope is not archived
24+
err = suite.db.First(&envelope, envelope.ID).Error
25+
assert.Nil(suite.T(), err)
26+
assert.True(suite.T(), envelope.Hidden, "Envelope was not archived together with category")
27+
}

0 commit comments

Comments
 (0)