Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PRO-1800 - set powertrain from device definition #183

Merged
merged 7 commits into from
Aug 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/devices-api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ func main() {

subcommands.Register(&populateESDDDataCmd{logger: logger, settings: settings, pdb: pdb, esInstance: deps.getElasticSearchService(), ddSvc: deps.getDeviceDefinitionService()}, "populate data")
subcommands.Register(&populateESRegionDataCmd{logger: logger, settings: settings, pdb: pdb, esInstance: deps.getElasticSearchService(), ddSvc: deps.getDeviceDefinitionService()}, "populate data")
subcommands.Register(&populateUSAPowertrainCmd{logger: logger, settings: settings, pdb: pdb, nhtsaService: deps.getNHTSAService()}, "populate data")
subcommands.Register(&populateUSAPowertrainCmd{logger: logger, settings: settings, pdb: pdb, nhtsaService: deps.getNHTSAService(), deviceDefSvc: deps.getDeviceDefinitionService()}, "populate data")

subcommands.Register(&stopTaskByKeyCmd{logger: logger, settings: settings, container: deps}, "tasks")

Expand Down
64 changes: 56 additions & 8 deletions cmd/devices-api/populate_powertrain.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package main
import (
"context"
"flag"

"github.com/google/subcommands"

"github.com/DIMO-Network/devices-api/internal/config"
Expand All @@ -20,31 +19,39 @@ type populateUSAPowertrainCmd struct {
settings config.Settings
pdb db.Store
nhtsaService services.INHTSAService
deviceDefSvc services.DeviceDefinitionService

useNHTSA bool
}

func (*populateUSAPowertrainCmd) Name() string { return "populate-usa-powertrain" }
func (*populateUSAPowertrainCmd) Synopsis() string { return "populate-usa-powertrain args to stdout." }
func (*populateUSAPowertrainCmd) Usage() string {
return `populate-usa-powertrain:
populate-usa-powertrain args.
populate-usa-powertrain [-useNHTSA].
`
}

// nolint
func (p *populateUSAPowertrainCmd) SetFlags(f *flag.FlagSet) {

f.BoolVar(&p.useNHTSA, "useNHTSA", false, "Use useNHTSA")
}

func (p *populateUSAPowertrainCmd) Execute(ctx context.Context, _ *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
p.logger.Info().Msg("Populating USA powertrain data from VINs")
err := populateUSAPowertrain(ctx, &p.logger, p.pdb, p.nhtsaService)
err := populateUSAPowertrain(ctx, &p.logger, p.pdb, p.nhtsaService, p.deviceDefSvc, p.useNHTSA)
if err != nil {
p.logger.Fatal().Err(err).Msg("Error filling in powertrain data.")
}
return subcommands.ExitSuccess
}

func populateUSAPowertrain(ctx context.Context, logger *zerolog.Logger, pdb db.Store, nhtsaService services.INHTSAService) error {
func populateUSAPowertrain(ctx context.Context, logger *zerolog.Logger, pdb db.Store, nhtsaService services.INHTSAService, deviceDefSvc services.DeviceDefinitionService, useNHTSA bool) error {

const (
PowerTrainType = "powertrain_type"
)

devices, err := models.UserDevices(
models.UserDeviceWhere.CountryCode.EQ(null.StringFrom("USA")),
models.UserDeviceWhere.VinIdentifier.IsNotNull(),
Expand All @@ -53,7 +60,7 @@ func populateUSAPowertrain(ctx context.Context, logger *zerolog.Logger, pdb db.S
return err
}

process := func(device *models.UserDevice) error {
processFromNTHSA := func(device *models.UserDevice) error {
resp, err := nhtsaService.DecodeVIN(device.VinIdentifier.String)
if err != nil {
return err
Expand All @@ -78,10 +85,51 @@ func populateUSAPowertrain(ctx context.Context, logger *zerolog.Logger, pdb db.S
return nil
}

processFromDeviceDefinition := func(device *models.UserDevice) error {
resp, err := deviceDefSvc.GetDeviceDefinitionByID(ctx, device.DeviceDefinitionID)
if err != nil {
return err
}

md := new(services.UserDeviceMetadata)
if err := device.Metadata.Unmarshal(md); err != nil {
return err
}

if len(resp.DeviceAttributes) > 0 {
// Find device attribute (powertrain_type)
for _, item := range resp.DeviceAttributes {
if item.Name == PowerTrainType {
powertrainType := deviceDefSvc.ConvertPowerTrainStringToPowertrain(item.Value)
md.PowertrainType = &powertrainType
if err := device.Metadata.Marshal(md); err != nil {
return err
}

break
}
}
}

if _, err := device.Update(ctx, pdb.DBS().Writer, boil.Infer()); err != nil {
return err
}
return nil
}

for _, device := range devices {
if err := process(device); err != nil {
logger.Err(err).Str("userDeviceId", device.ID).Str("vin", device.VinIdentifier.String).Msg("Failed to update powertrain metadata.")
if useNHTSA {
if err := processFromNTHSA(device); err != nil {
logger.Err(err).Str("userDeviceId", device.ID).Str("vin", device.VinIdentifier.String).Msg("Failed to update powertrain metadata NHTSA.")
}
}

if !useNHTSA {
if err := processFromDeviceDefinition(device); err != nil {
logger.Err(err).Str("userDeviceId", device.ID).Str("vin", device.VinIdentifier.String).Msg("Failed to update powertrain metadata from DeviceDefinition.")
}
}

}

return nil
Expand Down
47 changes: 36 additions & 11 deletions internal/controllers/user_devices_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -1061,32 +1061,57 @@ func (udc *UserDevicesController) UpdateVIN(c *fiber.Ctx) error {

// TODO: Genericize this for more countries.
if userDevice.CountryCode.Valid && userDevice.CountryCode.String == "USA" {
if err := udc.updateUSAPowertrain(c.Context(), userDevice); err != nil {
if err := udc.updateUSAPowertrain(c.Context(), userDevice, false); err != nil {
logger.Err(err).Msg("Failed to update American powertrain type.")
}
}

return c.SendStatus(fiber.StatusNoContent)
}

func (udc *UserDevicesController) updateUSAPowertrain(ctx context.Context, userDevice *models.UserDevice) error {
func (udc *UserDevicesController) updateUSAPowertrain(ctx context.Context, userDevice *models.UserDevice, useNHTSA bool) error {
const (
PowerTrainType = "powertrain_type"
)

// todo grpc pull vin decoder via grpc from device definitions
resp, err := udc.nhtsaService.DecodeVIN(userDevice.VinIdentifier.String)
if err != nil {
md := new(services.UserDeviceMetadata)
if err := userDevice.Metadata.Unmarshal(md); err != nil {
return err
}

dt, err := resp.DriveType()
if err != nil {
return err
if useNHTSA {
resp, err := udc.nhtsaService.DecodeVIN(userDevice.VinIdentifier.String)
if err != nil {
return err
}

dt, err := resp.DriveType()
if err != nil {
return err
}

md.PowertrainType = &dt
}

md := new(services.UserDeviceMetadata)
if err := userDevice.Metadata.Unmarshal(md); err != nil {
return err
if !useNHTSA {
resp, err := udc.DeviceDefSvc.GetDeviceDefinitionByID(ctx, userDevice.DeviceDefinitionID)
if err != nil {
return err
}

if len(resp.DeviceAttributes) > 0 {
// Find device attribute (powertrain_type)
for _, item := range resp.DeviceAttributes {
if item.Name == PowerTrainType {
powertrainType := udc.DeviceDefSvc.ConvertPowerTrainStringToPowertrain(item.Value)
md.PowertrainType = &powertrainType
break
}
}
}
}

md.PowertrainType = &dt
if err := userDevice.Metadata.Marshal(md); err != nil {
return err
}
Expand Down
31 changes: 22 additions & 9 deletions internal/controllers/user_devices_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -593,19 +593,32 @@ func (s *UserDevicesControllerTestSuite) TestGetMyUserDevicesNoDuplicates() {
func (s *UserDevicesControllerTestSuite) TestPatchVIN() {
integration := test.BuildIntegrationGRPC(constants.AutoPiVendor, 10, 4)
dd := test.BuildDeviceDefinitionGRPC(ksuid.New().String(), "Ford", "Escape", 2020, integration)

const powertrainType = "powertrain_type"
powertrainValue := ""
for _, item := range dd[0].DeviceAttributes {
if item.Name == powertrainType {
powertrainValue = item.Value
break
}
}

ud := test.SetupCreateUserDevice(s.T(), s.testUserID, dd[0].DeviceDefinitionId, nil, "", s.pdb)
s.deviceDefSvc.EXPECT().GetIntegrations(gomock.Any()).Return([]*grpc.Integration{integration}, nil)

s.usersClient.EXPECT().GetUser(gomock.Any(), &pb.GetUserRequest{Id: s.testUserID}).Return(&pb.User{Id: s.testUserID, EthereumAddress: nil}, nil)
evID := "4"
s.nhtsaService.EXPECT().DecodeVIN("5YJYGDEE5MF085533").Return(&services.NHTSADecodeVINResponse{
Results: []services.NHTSAResult{
{
VariableID: 126,
ValueID: &evID,
},
},
}, nil)
//evID := "4"
//s.nhtsaService.EXPECT().DecodeVIN("5YJYGDEE5MF085533").Return(&services.NHTSADecodeVINResponse{
// Results: []services.NHTSAResult{
// {
// VariableID: 126,
// ValueID: &evID,
// },
// },
//}, nil)

s.deviceDefSvc.EXPECT().GetDeviceDefinitionByID(gomock.Any(), dd[0].DeviceDefinitionId).Times(1).Return(dd[0], nil)
s.deviceDefSvc.EXPECT().ConvertPowerTrainStringToPowertrain(powertrainValue).Times(1).Return(services.BEV)
payload := `{ "vin": "5YJYGDEE5MF085533" }`
request := test.BuildRequest("PATCH", "/user/devices/"+ud.ID+"/vin", payload)
response, responseError := s.app.Test(request)
Expand Down
18 changes: 18 additions & 0 deletions internal/services/device_definitions_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ type DeviceDefinitionService interface {
CreateIntegration(ctx context.Context, integrationType string, vendor string, style string) (*ddgrpc.Integration, error)
DecodeVIN(ctx context.Context, vin string, model string, year int, countryCode string) (*ddgrpc.DecodeVinResponse, error)
GetIntegrationByTokenID(ctx context.Context, tokenID uint64) (*ddgrpc.Integration, error)
ConvertPowerTrainStringToPowertrain(value string) PowertrainType
}

type deviceDefinitionService struct {
Expand Down Expand Up @@ -755,3 +756,20 @@ func (d *deviceDefinitionService) getDeviceLatLong(userDeviceID string) (lat, lo
}
return
}

func (d *deviceDefinitionService) ConvertPowerTrainStringToPowertrain(value string) PowertrainType {
switch value {
case "HEV":
return HEV
case "PHEV":
return PHEV
case "BEV":
return BEV
case "ICE":
return ICE
case "FCEV":
return FCEV
default:
return ICE
}
}
14 changes: 14 additions & 0 deletions internal/services/mocks/device_definitions_service_mock.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions internal/test/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,11 @@ func BuildDeviceDefinitionGRPC(deviceDefinitionID string, mk string, model strin
rp.DeviceIntegrations = integrationsToAdd
}

rp.DeviceAttributes = append(rp.DeviceAttributes, &ddgrpc.DeviceTypeAttribute{
Name: "powertrain_type",
Value: "ICE",
})

return []*ddgrpc.GetDeviceDefinitionItemResponse{rp}
}

Expand Down
Loading