Skip to content

Commit

Permalink
Updated: job service action (hotwax#285)
Browse files Browse the repository at this point in the history
  • Loading branch information
R-Sourabh committed May 29, 2024
1 parent faf1697 commit d144daf
Show file tree
Hide file tree
Showing 5 changed files with 109 additions and 78 deletions.
11 changes: 10 additions & 1 deletion src/services/UploadService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ const uploadAndImportFile = async (payload: any): Promise <any> => {
});
}

const createIncomingShipment = async (payload: any): Promise <any> => {
return api({
url: "/service/createIncomingShipment",
method: "post",
data: payload
});
}

const prepareUploadJsonPayload = (request: UploadRequest) => {
const blob = new Blob([JSON.stringify(request.uploadData)], { type: 'application/json'});
const formData = new FormData();
Expand All @@ -38,5 +46,6 @@ const prepareUploadJsonPayload = (request: UploadRequest) => {
export const UploadService = {
prepareUploadJsonPayload,
uploadAndImportFile,
uploadJsonFile
uploadJsonFile,
createIncomingShipment
}
90 changes: 62 additions & 28 deletions src/store/modules/stock/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { hasError } from "@/adapter";
import { StockService } from "@/services/StockService";
import { translate } from "@hotwax/dxp-components";
import logger from "@/logger";
import { DateTime } from 'luxon'
import router from '@/router'

const actions: ActionTree<StockState, RootState> = {
async processUpdateStockItems ({ commit, rootGetters }, items) {
Expand Down Expand Up @@ -113,14 +115,19 @@ const actions: ActionTree<StockState, RootState> = {
commit(types.STOCK_SHOPIFY_SHOPS_UPDATED, payload)
},

async scheduleService({ commit }, params) {
async scheduleService({ dispatch, state }, { params, restockName }) {
let resp;

const job = params.job
const job = await dispatch("fetchDraftJob")

if(!job.jobId) {
showToast(translate("Configuration missing"))
return;
}

const payload = {
'JOB_NAME': job.jobName,
'SERVICE_NAME': job.serviceName,
'JOB_NAME': restockName || state.schedule.restockName || `Created ${DateTime.now().toLocaleString(DateTime.DATETIME_MED)}`,
'SERVICE_NAME': "shipPackedOrders", // TODO: make dynamic
'SERVICE_COUNT': '0',
'SERVICE_TEMP_EXPR': job.jobStatus,
'SERVICE_RUN_AS_SYSTEM':'Y',
Expand All @@ -136,38 +143,25 @@ const actions: ActionTree<StockState, RootState> = {
},
'statusId': "SERVICE_PENDING",
'systemJobEnumId': job.systemJobEnumId,
...params.jobCustomParameters
}


const jobRunTimeDataKeys = job?.runtimeData ? Object.keys(job?.runtimeData) : [];
if (jobRunTimeDataKeys.includes('shopifyConfigId') || jobRunTimeDataKeys.includes('shopId')) {
const shopifyConfig = this.state.user.currentShopifyConfig
if (Object.keys(shopifyConfig).length == 0) {
showToast(translate('Shopify configuration not found. Scheduling failed.'))
return;
}

jobRunTimeDataKeys.includes('shopifyConfigId') && (payload['shopifyConfigId'] = shopifyConfig?.shopifyConfigId);
jobRunTimeDataKeys.includes('shopId') && (payload['shopId'] = shopifyConfig?.shopId);
payload['jobFields']['shopId'] = shopifyConfig?.shopId;
...params
}

job?.priority && (payload['SERVICE_PRIORITY'] = job.priority.toString())
job?.runTime && (payload['SERVICE_TIME'] = job.runTime.toString())
payload['SERVICE_TIME'] = state.schedule.scheduledTime.toString()
job?.sinceId && (payload['sinceId'] = job.sinceId)

try {
resp = await StockService.scheduleJob({ ...payload });
if (resp.status == 200 && !hasError(resp)) {
showToast(translate('Service has been scheduled'));
await store.dispatch('fetchJobs', {
inputFields: {
'systemJobEnumId': payload.systemJobEnumId,
'systemJobEnumId_op': 'equals',
},
orderBy: "runTime ASC"
})
// await dispatch('fetchJobs', {
// inputFields: {
// 'systemJobEnumId': payload.systemJobEnumId,
// 'systemJobEnumId_op': 'equals',
// },
// orderBy: "runTime ASC"
// })
router.push('/scheduled-restock')
} else {
showToast(translate('Something went wrong'))
}
Expand All @@ -177,6 +171,46 @@ const actions: ActionTree<StockState, RootState> = {
}
return {};
},

async fetchDraftJob() {
let resp, job: any = {};

const payload = {
"inputFields": {
"statusId": "SERVICE_DRAFT",
"statusId_op": "equals",
"systemJobEnumId": "JOB_RST_STK",
"systemJobEnumId_op": "equals"
},
"fieldList": [ "systemJobEnumId", "runTime", "tempExprId", "parentJobId", "serviceName", "jobId", "jobName", "currentRetryCount", "statusId", "runtimeDataId", "productStoreId", "priority"],
"noConditionFind": "Y",
"viewSize": 1,
"orderBy": "runTime ASC"
}

try {
resp = await StockService.fetchJobInformation(payload)

if(!hasError(resp) && resp.data.docs.length) {
job = resp.data.docs[0]

job = {
...job,
status: job.statusId,
enumId: job.systemJobEnumId,
frequency: job.tempExprId,
id: job.jobId
}
} else {
throw resp.data
}
} catch(err) {
logger.error('Failed to fetcg draft job')
job = {}
}

return job;
},

async fetchJobs ({ commit }) {
let resp;
Expand All @@ -185,7 +219,7 @@ const actions: ActionTree<StockState, RootState> = {
const params = {
"inputFields": {
"statusId": "SERVICE_PENDING",
'systemJobEnumId': "JOB_BKR_ORD",
'systemJobEnumId': "JOB_RST_STK",
'systemJobEnumId_op': 'equals',
'orderBy': 'runTime ASC',
'tempExprId_op': 'not-empty'
Expand Down
2 changes: 1 addition & 1 deletion src/theme/variables.css
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,6 @@ http://ionicframework.com/docs/theming/ */

.date-time-modal {
--width: 320px;
--height: 385px;
--height: 445px;
--border-radius: 8px;
}
4 changes: 3 additions & 1 deletion src/views/ScheduledRestock.vue
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@
</ion-select>
</ion-item>
<ion-item lines="full">
<ion-input label="Restock name" placeholder="Created" v-model="restockName"></ion-input>
<ion-input label="Restock name" placeholder='Created' v-model="restockName"></ion-input>
</ion-item>
</ion-list>

Expand Down Expand Up @@ -270,6 +270,8 @@ export default defineComponent({
externalFacilityId: item[this.fieldMapping.facility]
}
})
console.log('this.schedule', this.schedule)
this.store.dispatch('stock/processUpdateRestockItems', restockItems);
this.store.dispatch('stock/scheduledStock', {
shopId: this.shopId,
Expand Down
80 changes: 33 additions & 47 deletions src/views/ScheduledRestockReview.vue
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@

<script>
import { defineComponent } from "vue";
import { IonBackButton, IonButton, IonButtons, IonCheckbox, IonChip, IonContent, IonHeader, IonIcon, IonInput, IonItem, IonLabel, IonList, IonPage, IonSearchbar, IonSelect, IonSelectOption, IonThumbnail, IonTitle, IonToolbar, alertController} from "@ionic/vue";
import { IonBackButton, IonButton, IonButtons, IonCheckbox, IonChip, IonContent,IonFab,IonFabButton, IonHeader, IonIcon, IonInput, IonItem, IonLabel, IonList, IonPage, IonSearchbar, IonSelect, IonSelectOption, IonThumbnail, IonTitle, IonToolbar, alertController} from "@ionic/vue";
import { translate } from "@hotwax/dxp-components";
import { DxpShopifyImg } from "@hotwax/dxp-components";
import { arrowUndoOutline, checkboxOutline, timerOutline, businessOutline, cloudUploadOutline, globeOutline} from "ionicons/icons"
Expand All @@ -93,6 +93,7 @@ import { DateTime } from 'luxon';
import { jsonToCsv, showToast } from '@/utils';
import { UploadService } from "@/services/UploadService";
import { hasError } from "@/adapter";
import logger from "@/logger";
export default defineComponent({
name: 'ScheduledRestockDetail',
Expand All @@ -104,6 +105,8 @@ export default defineComponent({
IonCheckbox,
IonChip,
IonContent,
IonFab,
IonFabButton,
IonHeader,
IonIcon,
IonInput,
Expand Down Expand Up @@ -174,6 +177,7 @@ export default defineComponent({
methods: {
getFilteredRestockItems() {
const filteredItems = {};
this.restockItems.map((item) => {
if(filteredItems[item.externalFacilityId]) filteredItems[item.externalFacilityId].push(item)
else filteredItems[item.externalFacilityId] = [item];
Expand All @@ -198,22 +202,25 @@ export default defineComponent({
}
result[item.externalFacilityId].push({
itemSeqId: '',
sku: item.product,
productId: item.productId,
quantity: parseInt(item.quantity, 10)
});
});
return result;
}, {});
const uploadData = Object.entries(groupedItems).map(([externalFacilityId, items]) => ({
destinationFacilityId: externalFacilityId,
items: items
}));
const params = {
"configId": "RESET_INVENTORY"
}
const destinationFacilityId = Object.keys(groupedItems)[0];
const items = groupedItems[destinationFacilityId];
const uploadData = {
payload: {
destinationFacilityId: destinationFacilityId,
items: items
}
};
console.log(uploadData);
const alert = await alertController.create({
header: translate("Reset inventory"),
message: translate("Make sure all the data you have entered is correct."),
Expand All @@ -224,41 +231,23 @@ export default defineComponent({
},
{
text: translate("Upload"),
handler: () => {
const data = jsonToCsv(uploadData)
const formData = new FormData();
formData.append("uploadedFile", data, this.fileName);
if(Object.keys(params)) {
for(const key in params) {
formData.append(key, params[key]);
handler: async () => {
try{
const resp = await UploadService.createIncomingShipment(uploadData)
if(!hasError(resp) && resp.data.shipmentId) {
this.store.dispatch("stock/scheduleService", { params: {
shipmentId: resp.data.shipmentId,
shopId: this.schedule.shopId
},
restockName: this.restockName
})
} else {
throw resp.data;
}
} catch(err) {
showToast(translate("Failed to create shipment"))
console.error(err)
}
UploadService.uploadAndImportFile({
data: formData,
headers: {
'Content-Type': 'multipart/form-data;'
}
}).then((resp) => {
if(hasError(resp)) {
throw resp.data
}
this.scheduleService();
this.isCsvUploadedSuccessfully = true;
showToast(translate("The inventory has been updated successfully"), [{
text: translate('View'),
role: 'view',
handler: () => {
const omsURL = (this.instanceUrl.startsWith('http') ? this.instanceUrl.replace(/\/api\/?|\/$/, "") : `https://${this.instanceUrl}.hotwax.io`) + `/commerce/control/ImportData?configId=RESET_INVENTORY`
window.open(omsURL, '_blank');
}
}])
this.router.push("/scheduled-restock");
this.store.dispatch('stock/clearRetockItems');
}).catch(() => {
showToast(translate("Something went wrong, please try again"));
})
}
},
],
Expand Down Expand Up @@ -299,10 +288,7 @@ export default defineComponent({
showToast("No product found")
}
this.parsedItems = filteredItems;
},
async scheduleService( params ) {
this.shore.dispatch('stock/scheduleService', { params })
},
}
},
setup() {
const store = useStore();
Expand Down

0 comments on commit d144daf

Please sign in to comment.