Skip to content

Commit

Permalink
both dropdowns are linked now, second dropdown filters value based on…
Browse files Browse the repository at this point in the history
… first, mirage-> new teams routes to be added ->> TODO, frontend complete
  • Loading branch information
sharma.yash committed Jul 7, 2023
1 parent 0d8ba7a commit e5e71d6
Show file tree
Hide file tree
Showing 13 changed files with 180 additions and 204 deletions.
55 changes: 27 additions & 28 deletions internal/api/products.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package api
import (
"encoding/json"
"fmt"
"github.com/hashicorp-forge/hermes/internal/structs"
"gorm.io/gorm"
"net/http"

Expand Down Expand Up @@ -120,33 +119,33 @@ func getProductsData(db *gorm.DB) (map[string]struct {
func AddNewProducts(ar *algolia.Client,
aw *algolia.Client, db *gorm.DB, req ProductRequest) error {

// Step 1: Update the algolia object
var productsObj = structs.Products{
ObjectID: "products",
Data: make(map[string]structs.ProductData, 0),
}
// Retrieve the existing productsObj from Algolia
err := ar.Internal.GetObject("products", &productsObj)
if err != nil {
return fmt.Errorf("error retrieving existing products object from Algolia : %w", err)
}

// Add the new value to the productsObj
productsObj.Data[req.ProductName] = structs.ProductData{
Abbreviation: req.ProductAbbreviation,
}

// Save the updated productsObj back to Algolia
// this replaces the old object completely
// Save Algolia products object.
res, err := aw.Internal.SaveObject(&productsObj)
if err != nil {
return fmt.Errorf("error saving Algolia products object: %w", err)
}
err = res.Wait()
if err != nil {
return fmt.Errorf("error saving Algolia products object: %w", err)
}
//// Step 1: Update the algolia object
//var productsObj = structs.Products{
// ObjectID: "products",
// Data: make(map[string]structs.ProductData, 0),
//}
//// Retrieve the existing productsObj from Algolia
//err := ar.Internal.GetObject("products", &productsObj)
//if err != nil {
// return fmt.Errorf("error retrieving existing products object from Algolia : %w", err)
//}
//
//// Add the new value to the productsObj
//productsObj.Data[req.ProductName] = structs.ProductData{
// Abbreviation: req.ProductAbbreviation,
//}
//
//// Save the updated productsObj back to Algolia
//// this replaces the old object completely
//// Save Algolia products object.
//res, err := aw.Internal.SaveObject(&productsObj)
//if err != nil {
// return fmt.Errorf("error saving Algolia products object: %w", err)
//}
//err = res.Wait()
//if err != nil {
// return fmt.Errorf("error saving Algolia products object: %w", err)
//}

// Step 2: upsert in the db
pm := models.Product{
Expand Down
13 changes: 12 additions & 1 deletion internal/api/teams.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/hashicorp-forge/hermes/pkg/models"
"github.com/hashicorp/go-hclog"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"net/http"
)

Expand Down Expand Up @@ -93,10 +94,20 @@ func getTeamsData(db *gorm.DB) (map[string]struct {
}, error) {
var teams []models.Team

if err := db.Find(&teams).Error; err != nil {
if err := db.Preload(clause.Associations).Find(&teams).Error; err != nil {
return nil, fmt.Errorf("failed to fetch teams: %w", err)
}

// Just for printing
//for _, team := range teams {
// fmt.Printf("Team ID: %d\n", team.ID)
// fmt.Printf("Team Name: %s\n", team.Name)
// fmt.Printf("Team Abbreviation: %s\n", team.Abbreviation)
// fmt.Printf("BU: %s\n", team.BU)
// // Print other columns as needed
// fmt.Println("-------------") // Separate each team
//}

teamsData := make(map[string]struct {
Abbreviation string `json:"abbreviation"`
BU string `json:"BU"`
Expand Down
1 change: 1 addition & 0 deletions pkg/models/gorm.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,6 @@ func ModelsToAutoMigrate() []interface{} {
&Product{},
&ProductLatestDocumentNumber{},
&User{},
&Team{},
}
}
2 changes: 2 additions & 0 deletions pkg/models/product.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ func (p *Product) Upsert(db *gorm.DB) error {
return db.Transaction(func(tx *gorm.DB) error {
// Upsert the BU.
if err := tx.
Where(Product{Name: p.Name}).
Omit(clause.Associations).
Assign(*p).
Clauses(clause.OnConflict{DoNothing: true}).
Expand All @@ -100,6 +101,7 @@ func (p *Product) Upsert(db *gorm.DB) error {

// Upsert the team.
if err := tx.
Where(Team{Name: team.Name}).
Omit(clause.Associations).
Clauses(clause.OnConflict{DoNothing: true}).
Create(&team).
Expand Down
19 changes: 18 additions & 1 deletion pkg/models/team.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@ type Team struct {
BU Product
}

//this function prints pretty json
//func PrettyStruct(data interface{}) (string, error) {
// val, err := json.MarshalIndent(data, "", " ")
// if err != nil {
// return "", err
// }
// return string(val), nil
//}

// Upsert upserts a team along with its associated BU into the database.
// If a BU with the given name already exists, it is used; otherwise, an error is returned.
func (t *Team) Upsert(db *gorm.DB, prdName string) error {
Expand All @@ -41,8 +50,16 @@ func (t *Team) Upsert(db *gorm.DB, prdName string) error {
t.BUID = existingPrd.ID
t.BU = existingPrd

//res, err := PrettyStruct(t)
//if err != nil {
// log.Fatal(err)
//}
//fmt.Println(res)

// Upsert the team.
if err := tx.Omit(clause.Associations).
if err := tx.Where(Team{Name: t.Name}).
Preload("BU").
Omit(clause.Associations).
Assign(*t).
Clauses(clause.OnConflict{DoNothing: true}).
FirstOrCreate(&t).Error; err != nil {
Expand Down
9 changes: 1 addition & 8 deletions web/app/components/inputs/product-select/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ interface InputsProductSelectSignature {
placement?: Placement;
isSaving?: boolean;
renderOut?: boolean;
onSelectBU: (selectedBU: string) => void;
};
}

Expand All @@ -37,11 +36,6 @@ export default class InputsProductSelectComponent extends Component<InputsProduc

@tracked products: ProductAreas | undefined = undefined;

@action
selectBU(selectedBU: string) {
this.args.onSelectBU(selectedBU) // Pass the selected BU to the parent component
}

get icon(): string {
let icon = "folder";
if (this.selected && getProductId(this.selected)) {
Expand All @@ -61,7 +55,6 @@ export default class InputsProductSelectComponent extends Component<InputsProduc

@action onChange(newValue: any, attributes?: ProductArea) {
this.selected = newValue;
this.selectBU(newValue);
this.args.onChange(newValue, attributes);
}

Expand All @@ -71,7 +64,7 @@ export default class InputsProductSelectComponent extends Component<InputsProduc
.fetch("/api/v1/products")
.then((resp) => resp?.json());
this.products = products;
console.log(this.products);
// console.log(this.products);
} catch (err) {
console.error(err);
throw err;
Expand Down
5 changes: 2 additions & 3 deletions web/app/components/inputs/team-select/index.hbs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
{{! @glint-nocheck - not typesafe yet }}
{{! https://www.w3.org/WAI/ARIA/apg/patterns/combobox/examples/combobox-select-only/ }}

<div data-test-product-select>
{{#if this.teams}}
{{#if @formatIsBadge}}
<Inputs::BadgeDropdownList
@items={{this.teams}}
@items={{this.filteredOptions}}
@listIsOrdered={{true}}
@onItemClick={{this.onChange}}
@selected={{@selected}}
Expand All @@ -27,7 +26,7 @@
</Inputs::BadgeDropdownList>
{{else}}
<X::DropdownList
@items={{this.teams}}
@items={{this.filteredOptions}}
@listIsOrdered={{true}}
@onItemClick={{this.onChange}}
@selected={{@selected}}
Expand Down
114 changes: 28 additions & 86 deletions web/app/components/inputs/team-select/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { assert } from "@ember/debug";
import { action } from "@ember/object";
import {action, computed} from "@ember/object";
import { inject as service } from "@ember/service";
import { Placement } from "@floating-ui/dom";
import Component from "@glimmer/component";
Expand Down Expand Up @@ -35,9 +35,7 @@ export default class InputsTeamSelectComponent extends Component<InputsTeamSelec
@service("fetch") declare fetchSvc: FetchService;

@tracked selected = this.args.selected;

@tracked teams: TeamAreas | undefined = undefined;
@tracked selectedBU: string | null = null;

get icon(): string {
let icon = "folder";
Expand All @@ -61,93 +59,37 @@ export default class InputsTeamSelectComponent extends Component<InputsTeamSelec
this.args.onChange(newValue, attributes);
}

// @action onBUChange(){
// this.selectedBU = this.args.selectedBU;
// this.fetchteams.perform();
// }
@computed('args.selectedBU', 'teams')
get filteredOptions() {
if (!this.args.selectedBU) {
return this.teams;
}

// Filter the teams based on the selected business unit
const filteredTeams: TeamAreas = {};
let teams: TeamAreas | undefined= this.teams;

for (const team in teams) {
if (Object.prototype.hasOwnProperty.call(teams, team)) {
const teamData: TeamArea | undefined = teams[team];
if (teamData && teamData.BU === this.args.selectedBU) {
filteredTeams[team] = teamData;
}
}
}
return filteredTeams;
}

// protected fetchProducts = task(async () => {
// try {
// let products = await this.fetchSvc
// .fetch("/api/v1/products")
// .then((resp) => resp?.json());
// this.products = products;
// } catch (err) {
// console.error(err);
// throw err;
// }
// });
protected fetchteams = task(async () => {
try {
// this.selectedBU = this.args.selectedBU;
// Filter the teams based on the selected business unit
// console.log("parent injected value is: ",this.selectedBU)
// let teams: TeamAreas = {
// "Spinage": {
// "abbreviation": "SPI",
// "perDocDataType": null,
// "BU": "Platform"
// },
// "RECON": {
// "abbreviation": "RCN",
// "perDocDataType": null,
// "BU": "Platform"
// },
// "Dev-Prod": {
// "abbreviation": "DP",
// "perDocDataType": null,
// "BU": "Platform"
// },
// "Team A-cap": {
// "abbreviation": "A-Cap",
// "perDocDataType": null,
// "BU": "Capital"
// },
// "Team B-cap": {
// "abbreviation": "B-cap",
// "perDocDataType": null,
// "BU": "Capital"
// },
// "Team A-X": {
// "abbreviation": "A-x",
// "perDocDataType": null,
// "BU": "X"
// },
// "Team B-x": {
// "abbreviation": "bx",
// "perDocDataType": null,
// "BU": "X"
// },
// "Team d-paymnt": {
// "abbreviation": "d-pay",
// "perDocDataType": null,
// "BU": "Payments"
// },
// };
// // Filter the teams based on the selected business unit
// const filteredTeams: TeamAreas = {};
//
// for (const team in teams) {
// if (Object.prototype.hasOwnProperty.call(teams, team)) {
// const teamData: TeamArea | undefined = teams[team];
// if (teamData && teamData.BU === this.selectedBU) {
// filteredTeams[team] = teamData;
// }
// }
// }
// console.log("Here i am");
// console.log(filteredTeams)
// this.teams = filteredTeams;
let teams = await this.fetchSvc
.fetch("/api/v1/teams")
.then((resp) => resp?.json());
this.teams = teams;
console.log(this.teams);
} catch (err) {
console.error(err);
throw err;
}
});
this.teams = await this.fetchSvc
.fetch("/api/v1/teams")
.then((resp) => resp?.json());
} catch (err) {
throw err;
}
});

}

Expand Down
2 changes: 1 addition & 1 deletion web/app/components/new/doc-form.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@
/>
</div>

{{! Testing new functionality }}
{{! Testing new functionality for Teams}}
{{!-- Render the team dropdown only when BU is selected --}}
<div>
<div class="mb-2">
Expand Down
11 changes: 3 additions & 8 deletions web/app/components/new/doc-form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ export default class NewDocFormComponent extends Component<NewDocFormComponentSi
@tracked protected teamAbbreviation: string | null = null;
@tracked protected contributors: HermesUser[] = [];

@tracked selectedBU: string | null = null;

@tracked protected _form: HTMLFormElement | null = null;

/**
Expand Down Expand Up @@ -186,6 +188,7 @@ export default class NewDocFormComponent extends Component<NewDocFormComponentSi
attributes: ProductArea
) {
this.productArea = productName;
this.selectedBU = productName;
this.productAbbreviation = attributes.abbreviation;
this.maybeValidate();
}
Expand All @@ -212,14 +215,6 @@ export default class NewDocFormComponent extends Component<NewDocFormComponentSi
}
}

@tracked selectedBU: string | null = null;
@action
updateSelectedBU(selectedBU: string) {
this.selectedBU = selectedBU;
// Trigger the necessary actions, such as fetching filtered teams
// ...
}

/**
* Creates a document draft, then redirects to the document.
* On error, show a flashMessage and allow users to try again.
Expand Down
Loading

0 comments on commit e5e71d6

Please sign in to comment.