import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit"; import { uploadToS3 } from "../apis/awsUpload"; import { Action, AOP, GPTResponse, SlotItem, Step } from "../types/AOP"; import { captureAPI, captureServiceAPI } from "../apis/backendAPIConfig"; import { Configuration, Slot } from "../types/Configuration"; import configurationToAopConverter from "../utils/ConfigurationToAopConverter"; import { RootState } from "./store"; import { BoundingBox, setAvailableCategoryGroups, setBoundingBoxes, setImageArray, } from "./canvasSlice"; import axios from "axios"; import { DeviceEventEmitter } from "react-native"; import AsyncStorage from "@react-native-async-storage/async-storage"; export interface AOPState { steps: Step[]; imperfectionScreen: "camera" | "annotation"; stepsUploaded: boolean; defaultAOPComplete: boolean; activeStepIndex: number; activeSlotIndex: number; activeSlotItemIndex: number; activeSlotItemActionIndex: number; showPreview: boolean; aopIsLoaded: boolean; gpt: GPTResponse[][][]; } const initialState: AOPState = { steps: [], imperfectionScreen: "camera", activeStepIndex: 0, activeSlotIndex: 0, activeSlotItemIndex: 0, activeSlotItemActionIndex: -1, defaultAOPComplete: false, stepsUploaded: false, showPreview: false, aopIsLoaded: false, gpt: [[[]]], }; export interface DataUploadArgs { stepId: string; slotId: string; slotItemId?: string; filePath: string; } export interface LocalDataCacheArgs extends DataUploadArgs { productId: string; } export const addToUploadQueue = createAsyncThunk( "aop/addToUploadQueue", async (uploadItem: DataUploadArgs, ThunkAPI) => { const dataString = await AsyncStorage.getItem("@@capture-sdk/upload-queue"); const currentProductId = (ThunkAPI.getState() as RootState).App.productID; if (dataString) { const data = JSON.parse(dataString).items as LocalDataCacheArgs[]; await AsyncStorage.setItem( "@capture-sdk/upload-queue", JSON.stringify({ items: [ ...data, { ...uploadItem, productId: currentProductId, }, ], }) ); } else { await AsyncStorage.setItem( "@capture-sdk/upload-queue", JSON.stringify({ items: [ { ...uploadItem, productId: currentProductId, }, ], }) ); } } ); export const uploadLocalCacheQueue = createAsyncThunk( "aop/uploadLocalCacheQueue", async (_, ThunkAPI) => { const dataString = (await AsyncStorage.getItem( "@@capture-sdk/upload-queue" )) as string; const currentProductId = (ThunkAPI.getState() as RootState).App.productID; const data = (JSON.parse(dataString).items as LocalDataCacheArgs[]).filter( (data) => data.productId === currentProductId ); // marking it async allows for items to be uploaded sequentially data.forEach(async (item) => await ThunkAPI.dispatch(slotDataUpload(item))); } ); export const uploadDynamicSlots = createAsyncThunk( "aop/uploadDynamicSlots", async (slots: Slot[], ThunkAPI) => { const productId = (ThunkAPI.getState() as RootState).App .productID as string; ThunkAPI.dispatch(setAOPIsLoaded(false)); await captureAPI.post(`/capture/dynamic/${productId}`, { slots, }); const { data } = await captureAPI.get(`/capture/${productId}`); ThunkAPI.dispatch(setListOfSteps((data.captureInstance as AOP).steps)); ThunkAPI.dispatch(setAOPIsLoaded(true)); } ); export const slotDataUpload = createAsyncThunk( "aop/slotDataUpload", async (config: DataUploadArgs, ThunkAPI) => { const productId = (ThunkAPI.getState() as RootState).App .productID as string; let action = (ThunkAPI.getState() as RootState).AOP.steps .find((step) => step.stepId === config.stepId) ?.slots.find((slot) => slot.slotId === config.slotId)?.action; if ( ( (ThunkAPI.getState() as RootState).AOP.steps .find((step) => step.stepId === config.stepId) ?.slots.find((slot) => slot.slotId === config.slotId) ?.slotItems as SlotItem[] ).length > 0 ) { action = (ThunkAPI.getState() as RootState).AOP.steps .find((step) => step.stepId === config.stepId) ?.slots.find((slot) => slot.slotId === config.slotId) ?.slotItems.find( (slotItem) => slotItem.slotItemId === config.slotItemId )?.availableActions[0] as Action; } if (action) { const awsResponse = await uploadToS3({ filePath: config.filePath, mimeType: config.filePath.split("/").pop()?.split(".").pop() === "jpeg" ? "image/jpeg" : "video/mp4", }); await captureAPI.put(`/capture/${productId}`, { items: [ { action, stepId: config.stepId, slotId: config.slotId, slotItemId: config.slotItemId ? config.slotItemId : undefined, uploadURL: (awsResponse as any).body.postResponse.location, uploadURI: (awsResponse as any).body.postResponse.key, }, ], }); return { stepId: config.stepId, slotId: config.slotId, slotItemId: config.slotItemId ? config.slotItemId : undefined, uploadURL: (awsResponse as any).body.postResponse.location, uploadURI: (awsResponse as any).body.postResponse.key, }; } } ); type initiateAOPProps = { productId: string; deviceId: string; configuration?: Configuration; sopTitle?: string; }; export const fetchHotspotDataForKey = createAsyncThunk( "aop/fetchHotspotDataForKey", async (key: string, ThunkAPI) => { const { productID } = (ThunkAPI.getState() as RootState).App; const { data: serviceData } = await captureAPI.get( `/capture-service/${productID}/${key}/inference` ); const boxes: BoundingBox[][] = serviceData[0].service.outputData.prediction_list.map((data: any) => { return data.raw_inferences.map((inference: any) => { return { x: inference.xyxyn[0], y: inference.xyxyn[1], width: inference.xywhn[2], height: inference.xywhn[3], label: inference.class_name as string, xywh: inference.xywh, xyxy: inference.xyxy, xyxyn: inference.xyxyn, xywhn: inference.xywhn, image_size: inference.image_size, class: inference.class, class_name: inference.class_name, confidence: inference.confidence, } as BoundingBox; }) as BoundingBox[]; }) as BoundingBox[][]; const urls = serviceData[0].service.outputData.prediction_list.map( (data: any) => data.src as string ); ThunkAPI.dispatch(setBoundingBoxes(boxes)); ThunkAPI.dispatch(setImageArray(urls as string[])); ThunkAPI.dispatch(unlockSlaveSlots(key)); } ); export const initiateAOP = createAsyncThunk( "aop/fetchProductIdBasedAOP", async (args: initiateAOPProps, ThunkAPI) => { const { data: tokenData } = await axios.post( "https://safecam360.s20.ai/api/auth", { email: "delta@s20.ai", password: "abcde12345", } ); const { token } = tokenData; // set headers for all instances captureAPI.interceptors.request.use( (config) => { config.headers["x-auth-token"] = token; return config; }, (err) => Promise.reject(err) ); captureServiceAPI.interceptors.request.use( (config) => { config.headers["x-auth-token"] = token; return config; }, (err) => Promise.reject(err) ); const { data } = await captureAPI.get(`/capture/${args.productId}`); if (data.captureInstance) { ThunkAPI.dispatch(setListOfSteps((data.captureInstance as AOP).steps)); ThunkAPI.dispatch(setCurrentStep(0)); ThunkAPI.dispatch(setCurrentSlot(0)); ThunkAPI.dispatch(setGPTChatData((data.captureInstance as AOP).gpt)); } else { const initiateAfterFormingAOP = async (aop: AOP) => { ThunkAPI.dispatch(setListOfSteps(aop.steps)); ThunkAPI.dispatch(setCurrentStep(0)); ThunkAPI.dispatch(setCurrentSlot(0)); ThunkAPI.dispatch(setGPTChatData(aop.gpt)); await captureAPI.post(`/capture/${args.productId}`, { ...aop, deviceId: args.deviceId, }); }; let aop: AOP; if (args.sopTitle) { const { data } = await captureAPI.get(`/configuration/${args.sopTitle}/true`); const sop = data.captureConfigurationInstances[0] as Configuration; aop = configurationToAopConverter( data.captureConfigurationInstances[0] as Configuration ); await initiateAfterFormingAOP(aop); } else if (args.configuration) { aop = configurationToAopConverter(args.configuration); await initiateAfterFormingAOP(aop); } } // const { data: categoryGroups } = await captureServiceAPI.get( // "/getCategoryGroups" // ); // ThunkAPI.dispatch(setAvailableCategoryGroups(categoryGroups)); } ); export const AOPSlice = createSlice({ name: "steps", initialState, reducers: { setListOfSteps: (state, action: PayloadAction) => { state.steps = action.payload; }, setGPTChatData: (state, action: PayloadAction) => { state.gpt = action.payload; }, appendStepToList: (state, action: PayloadAction) => { state.steps = [...state.steps, ...action.payload]; }, setDefaultAOPComplete: (state, action: PayloadAction) => { state.defaultAOPComplete = action.payload; }, setAOPIsLoaded: (state, action: PayloadAction) => { state.aopIsLoaded = action.payload; }, setCurrentStep: (state, action: PayloadAction) => { if ( !state.steps[state.activeStepIndex].slots[state.activeSlotIndex].lock ) { state.activeStepIndex = action.payload; DeviceEventEmitter.emit( "@s20/sequence-event/onStepChange", action.payload ); state.activeSlotIndex = 0; DeviceEventEmitter.emit("@s20/sequence-event/onSlotChange", 0); DeviceEventEmitter.emit("@s20/sequence-event/onSlotStart", 0); setTimeout(() => {}, 500); DeviceEventEmitter.emit("@s20/sequence-event/onSlotEnd", 0); setTimeout(() => {}, 500); } else { DeviceEventEmitter.emit("@s20/sequence-event/info", { message: "slot is locked, please complete capture to proceed", }); } }, setCurrentSlot: (state, action: PayloadAction) => { if ( !state.steps[state.activeStepIndex].slots[state.activeSlotIndex].lock ) { state.activeSlotIndex = action.payload; state.imperfectionScreen = "annotation"; DeviceEventEmitter.emit( "@s20/sequence-event/onSlotChange", action.payload ); setTimeout(() => { DeviceEventEmitter.emit("@s20/sequence-event/onSlotEnd"); DeviceEventEmitter.emit("@s20/sequence-event/onSlotStart"); }); } else { DeviceEventEmitter.emit("@s20/sequence-event/info", { message: "slot is locked, please complete capture to proceed", }); } }, setCurrentSlotItemAction: (state, action: PayloadAction) => { state.activeSlotItemActionIndex = action.payload; DeviceEventEmitter.emit( "@s20/sequence-event/onSlotItemChange", action.payload ); }, setActionData: (state, action: PayloadAction) => { // for slotItems if ( state.steps[state.activeStepIndex].slots[state.activeSlotIndex] .slotItems.length > 0 ) { const slotItemAction = { ...state.steps[state.activeStepIndex].slots[state.activeSlotIndex] .slotItems[state.activeSlotItemIndex].availableActions[ state.activeSlotItemActionIndex ], }; slotItemAction.actionData = action.payload; slotItemAction.storagePath = action.payload.path; state.steps[state.activeStepIndex].slots[ state.activeSlotIndex ].slotItems[state.activeSlotItemIndex].usedAction = slotItemAction; } // normal slot case else { const actionData = action.payload; actionData.storagePath = action.payload.path; if ( state.steps[state.activeStepIndex].slots[state.activeSlotIndex] .action !== undefined ) { state.steps[state.activeStepIndex].slots[ state.activeSlotIndex ].usedAction = actionData; state.steps[state.activeStepIndex].slots[ state.activeSlotIndex ].action = { ...state.steps[state.activeStepIndex].slots[state.activeSlotIndex] .action, ...actionData, }; } } state.showPreview = true; }, setSlotImperfectionData: (state, action: PayloadAction) => { state.steps[state.activeStepIndex].slots[ state.activeSlotIndex ].imperfectionData = action.payload; }, unlockSlaveSlots: (state, action: PayloadAction) => { state.steps.forEach((step) => { step.slots.forEach((slot) => { if (slot.refKey && slot.refKey === action.payload) { slot.locked = false; } }); }); }, setAOPIncrement: (state, _: PayloadAction) => { const checkStepCompletion = () => { const defaultSlots = state.steps[state.activeStepIndex].slots.filter( (slot) => slot.slotType === "DEFAULT" ); const isStepNotComplete = defaultSlots.find((slot) => !slot.isComplete); if (!isStepNotComplete) { state.steps[state.activeStepIndex].isComplete = true; } }; // for slots with slotItems if ( state.steps[state.activeStepIndex].slots[state.activeSlotIndex] .slotItems.length > 0 ) { if ( state.steps[state.activeStepIndex].slots[state.activeSlotIndex] .slotItems.length > state.activeSlotItemIndex + 1 ) { state.activeSlotItemIndex += 1; state.activeSlotItemActionIndex = -1; } else { state.activeSlotItemIndex = 0; state.activeSlotItemActionIndex = -1; if ( state.steps[state.activeStepIndex].slots.length > state.activeSlotIndex + 1 ) { state.activeSlotIndex += 1; } else if (state.steps.length > state.activeStepIndex + 1) { checkStepCompletion(); state.activeStepIndex += 1; state.activeSlotIndex = 0; } else { checkStepCompletion(); } } } // handling default slot completion on state else { state.steps[state.activeStepIndex].slots[ state.activeSlotIndex ].isComplete = true; state.steps[state.activeStepIndex].slots[ state.activeSlotIndex ].isUploaded = false; if ( state.steps[state.activeStepIndex].slots[state.activeSlotIndex].lock ) { state.steps[state.activeStepIndex].slots[state.activeSlotIndex].lock = false; } if ( state.steps[state.activeStepIndex].slots.length > state.activeSlotIndex + 1 ) { state.activeSlotIndex += 1; checkStepCompletion(); } else if (state.steps.length > state.activeStepIndex + 1) { checkStepCompletion(); state.activeStepIndex += 1; state.activeSlotIndex = 0; checkStepCompletion(); } else { checkStepCompletion(); } } DeviceEventEmitter.emit( "@s20/sequence-event/onSlotItemChange", state.activeSlotItemIndex ); DeviceEventEmitter.emit( "@s20/sequence-event/onSlotChange", state.activeSlotIndex ); DeviceEventEmitter.emit("@s20/sequence-event/onSlotEnd"); DeviceEventEmitter.emit("@s20/sequence-event/onSlotStart"); DeviceEventEmitter.emit( "@s20/sequence-event/onStepChange", state.activeStepIndex ); state.showPreview = false; state.imperfectionScreen = "annotation"; }, setImperfectionScreen: ( state, action: PayloadAction<"camera" | "annotation"> ) => { state.imperfectionScreen = action.payload; }, setShowPreview: (state, action: PayloadAction) => { state.showPreview = action.payload; }, }, extraReducers: (builder) => { builder.addCase(slotDataUpload.fulfilled, (state, action) => { if (action.payload) { // change scope of data upload URL and URI to match slotItems const stepIndex = state.steps.findIndex( (step) => step.stepId === action.payload?.stepId ); const slotIndex = state.steps[stepIndex].slots.findIndex( (slot) => slot.slotId === action.payload?.slotId ); if (action.payload.slotItemId) { const slotItemIndex = state.steps[stepIndex].slots[ slotIndex ].slotItems.findIndex( (slotItem) => slotItem.slotItemId === action.payload?.slotItemId ); state.steps[stepIndex].slots[slotIndex].slotItems[ slotItemIndex ].isComplete = true; state.steps[stepIndex].slots[slotIndex].slotItems[ slotItemIndex ].isUploaded = true; state.steps[stepIndex].slots[slotIndex].slotItems[ slotItemIndex ].uploadURI = action.payload.uploadURI; state.steps[stepIndex].slots[slotIndex].slotItems[ slotItemIndex ].uploadURL = action.payload.uploadURL; const isSlotNotComplete = state.steps[stepIndex].slots[ slotIndex ].slotItems.findIndex((slotItem) => !slotItem.isComplete); if (isSlotNotComplete === -1) { state.steps[stepIndex].slots[slotIndex].isUploaded = true; } } else { state.steps[stepIndex].slots[slotIndex].isUploaded = true; state.steps[stepIndex].slots[slotIndex].uploadURL = action.payload.uploadURL; state.steps[stepIndex].slots[slotIndex].uploadURI = action.payload.uploadURI; } const defaultSlots = state.steps[stepIndex].slots.filter( (slot) => slot.slotType === "DEFAULT" ); const isStepUploadComplete = defaultSlots.findIndex((slot) => !slot.isUploaded) < 0; if (isStepUploadComplete) state.steps[stepIndex].isUploaded = true; const defaultSteps = state.steps.filter( (step) => step.stepType === "DEFAULT" ); const isStepsUploaded = defaultSteps.findIndex( (step) => !step.isUploaded ); if (!(isStepsUploaded > -1)) state.stepsUploaded = true; DeviceEventEmitter.emit( "@s20/sequence-event/onDataUpload", action.payload ); } }); builder.addCase(initiateAOP.fulfilled, (state, __) => { state.aopIsLoaded = true; }); builder.addCase(initiateAOP.rejected, (state, payload) => { //TODO add proper error message console.log(payload); console.log("ok no"); }); }, }); export const getCurrentSlot = (state: RootState) => state.AOP.steps[state.AOP.activeStepIndex].slots[state.AOP.activeSlotIndex]; export const { setListOfSteps, setGPTChatData, setCurrentSlot, setCurrentStep, appendStepToList, setActionData, setCurrentSlotItemAction, setAOPIncrement, setDefaultAOPComplete, setShowPreview, unlockSlaveSlots, setAOPIsLoaded, setImperfectionScreen, setSlotImperfectionData, } = AOPSlice.actions; // side-effect based middleware to dispatch actions when required // setCurrentStep will waterfall dispatching a list to set active step slots export default AOPSlice.reducer;