|
| 1 | +// Copyright (c) 2025 Probo Inc <hello@getprobo.com>. |
| 2 | +// |
| 3 | +// Permission to use, copy, modify, and/or distribute this software for any |
| 4 | +// purpose with or without fee is hereby granted, provided that the above |
| 5 | +// copyright notice and this permission notice appear in all copies. |
| 6 | +// |
| 7 | +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH |
| 8 | +// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY |
| 9 | +// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, |
| 10 | +// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM |
| 11 | +// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR |
| 12 | +// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR |
| 13 | +// PERFORMANCE OF THIS SOFTWARE. |
| 14 | + |
| 15 | +package probo |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "fmt" |
| 20 | + "time" |
| 21 | + |
| 22 | + "github.com/getprobo/probo/pkg/gid" |
| 23 | + "github.com/getprobo/probo/pkg/probo/coredata" |
| 24 | + "go.gearno.de/kit/pg" |
| 25 | +) |
| 26 | + |
| 27 | +type ( |
| 28 | + CreateControlRequest struct { |
| 29 | + FrameworkID gid.GID |
| 30 | + Name string |
| 31 | + Description string |
| 32 | + ContentRef string |
| 33 | + } |
| 34 | +) |
| 35 | + |
| 36 | +func (s Service) CreateControl( |
| 37 | + ctx context.Context, |
| 38 | + req CreateControlRequest, |
| 39 | +) (*coredata.Control, error) { |
| 40 | + now := time.Now() |
| 41 | + controlID, err := gid.NewGID(coredata.ControlEntityType) |
| 42 | + if err != nil { |
| 43 | + return nil, fmt.Errorf("cannot create global id: %w", err) |
| 44 | + } |
| 45 | + |
| 46 | + framework := &coredata.Framework{} |
| 47 | + control := &coredata.Control{ |
| 48 | + ID: controlID, |
| 49 | + FrameworkID: req.FrameworkID, |
| 50 | + Name: req.Name, |
| 51 | + Description: req.Description, |
| 52 | + ContentRef: req.ContentRef, |
| 53 | + CreatedAt: now, |
| 54 | + UpdatedAt: now, |
| 55 | + } |
| 56 | + |
| 57 | + err = s.pg.WithTx( |
| 58 | + ctx, |
| 59 | + func(conn pg.Conn) error { |
| 60 | + if err := framework.LoadByID(ctx, conn, s.scope, req.FrameworkID); err != nil { |
| 61 | + return fmt.Errorf("cannot load framework %q: %w", req.FrameworkID, err) |
| 62 | + } |
| 63 | + |
| 64 | + if err := control.Insert(ctx, conn); err != nil { |
| 65 | + return fmt.Errorf("cannot insert control: %w", err) |
| 66 | + } |
| 67 | + |
| 68 | + return nil |
| 69 | + }, |
| 70 | + ) |
| 71 | + |
| 72 | + if err != nil { |
| 73 | + return nil, err |
| 74 | + } |
| 75 | + |
| 76 | + return control, nil |
| 77 | +} |
0 commit comments