add places operations

This commit is contained in:
2026-07-14 01:25:57 +07:00
parent 2b11c49b3c
commit 7a657926f1
12 changed files with 502 additions and 175 deletions
@@ -19,8 +19,8 @@ func mapScenarios(o []*repos.Scenario) ([]*Scenario, error) {
}
func mapScenario(o *repos.Scenario) (*Scenario, error) {
story := &storytelling.Story{}
if err := json.Unmarshal([]byte(o.Scenario), story); err != nil {
story, err := mapStory(o.Scenario)
if err != nil {
return nil, err
}
return &Scenario{
@@ -37,3 +37,19 @@ func mapScenario(o *repos.Scenario) (*Scenario, error) {
IsDeleted: o.IsDeleted,
}, nil
}
func mapStory(o string) (*storytelling.Story, error) {
res := &storytelling.Story{}
if err := json.Unmarshal([]byte(o), res); err != nil {
return nil, err
}
return res, nil
}
func convertStory(o *storytelling.Story) (string, error) {
b, err := json.Marshal(o)
if err != nil {
return "", err
}
return string(b), nil
}
@@ -2,6 +2,8 @@ package scenarios_service
import (
"context"
"errors"
"evening_detective_server/internal/modules/storytelling"
"evening_detective_server/internal/repos/scenarios_repo"
)
@@ -67,3 +69,81 @@ func (s *ScenarioService) DeleteScenarioByID(
) error {
return s.scenariosRepo.DeleteScenarioByID(ctx, id)
}
func (s *ScenarioService) AddScenarioPlace(
ctx context.Context,
id int,
place *storytelling.Place,
) error {
story, err := s.getStory(ctx, id)
if err != nil {
return err
}
story.Places = append(
story.Places,
place,
)
return s.updateStory(ctx, id, story)
}
func (s *ScenarioService) UpdateScenarioPlace(
ctx context.Context,
id int,
code string,
place *storytelling.Place,
) error {
story, err := s.getStory(ctx, id)
if err != nil {
return err
}
for i := range story.Places {
if story.Places[i].Code == code {
story.Places[i] = place
break
}
}
return s.updateStory(ctx, id, story)
}
func (s *ScenarioService) DeleteScenarioPlace(
ctx context.Context,
id int,
code string,
) error {
story, err := s.getStory(ctx, id)
if err != nil {
return err
}
for i := range story.Places {
if story.Places[i].Code == code {
story.Places = append(story.Places[:i], story.Places[i+1:]...)
break
}
}
return s.updateStory(ctx, id, story)
}
func (s *ScenarioService) getStory(ctx context.Context, id int) (*storytelling.Story, error) {
storyString, err := s.scenariosRepo.GetStoryByScenarioID(ctx, id)
if err != nil {
return nil, err
}
return mapStory(storyString)
}
func (s *ScenarioService) updateStory(ctx context.Context, id int, story *storytelling.Story) error {
mapCodes := map[string]struct{}{}
for _, place := range story.Places {
mapCodes[place.Code] = struct{}{}
}
if len(mapCodes) != len(story.Places) {
return errors.New("Такой код точки уже существует")
}
storyString, err := convertStory(story)
if err != nil {
return err
}
return s.scenariosRepo.UpdateStoryByScenarioID(ctx, id, storyString)
}