Data4Autos-Shopify-Backend/fulfillmentService.js
2026-04-13 05:23:25 +00:00

282 lines
7.5 KiB
JavaScript
Executable File

const axios = require('axios');
const { log } = require('./logger');
/**
* Logs messages with a shop context.
* @param {string} shop - Shopify store name.
* @param {string} message - Log message.
*/
const getLocationQuery = `
query {
locations(first: 1, query: "name:'Shop location'" ) {
nodes {
id
name
address {
address1
address2
city
province
provinceCode
country
countryCode
zip
phone
}
}
}
}
`;
async function getStoreAddress(client) {
const response = await client.post('', { query: getLocationQuery });
console.log('Store locations response:', response.data);
const location = response.data.data.locations.nodes[0];
return location.address;
}
const createLocationMutation = (address) => `
mutation {
locationAdd(input: {
name: "(App) Data4Autos Distribution API",
address: {
address1: "${address.address1 || ''}",
address2: "${address.address2 || ''}",
city: "${address.city}",
provinceCode: "${address.phone || 'ON'}",
countryCode: ${address.countryCode},
zip: "${address.zip || ''}",
phone: "${address.phone || ''}"
},
fulfillsOnlineOrders: true
}) {
location {
id
name
address {
address1
city
provinceCode
countryCode
zip
phone
}
}
userErrors {
code
field
message
}
}
}
`;
async function createCustomLocation(address, client) {
const mutation = createLocationMutation(address);
const response = await client.post('', { query: mutation });
// console.log('Location creation response:', response.data);
return response.data.data.locationAdd;
}
/**
* Create a Shopify fulfillment service.
* @param {string} shop - The Shopify store domain (e.g., myshop.myshopify.com).
* @param {string} accessToken - The Shopify Admin API access token.
* @returns {Promise<object>} The created fulfillment service or error details.
*/
async function createFulfillmentService(shop, accessToken) {
const client = axios.create({
baseURL: `https://${shop}/admin/api/2025-10/graphql.json`,
headers: {
'X-Shopify-Access-Token': accessToken,
'Content-Type': 'application/json',
},
});
const mutation = `
mutation {
fulfillmentServiceCreate(
name: "Data4Autos Distribution",
callbackUrl: "https://backend.data4autos.com/fulfillment"
) {
fulfillmentService {
id
serviceName
callbackUrl
handle
location {
id
}
}
userErrors {
field
message
}
}
}
`;
// const mutation = `
// mutation {
// fulfillmentServiceCreate(
// name: "Data4Autos Distribution",
// callbackUrl: "https://backend.data4autos.com/fulfillment",
// fulfillmentOrdersOptIn: true,
// inventoryManagement: true,
// trackingSupport: true,
// requiresShippingMethod: true
//
// ) {
// fulfillmentService {
// id
// serviceName
// callbackUrl
// handle
// location {
// id
// }
// }
// userErrors {
// field
// message
// }
// }
// }
// `;
try {
log(shop, `🚀 Creating fulfillment service...`);
const response = await client.post('', { query: mutation });
const data = response.data.data.fulfillmentServiceCreate;
if (data.userErrors && data.userErrors.length > 0) {
log(shop, `❌ User errors: ${JSON.stringify(data.userErrors)}`);
return { success: false, errors: data.userErrors };
}
log(shop, `✅ Fulfillment Service created: ${JSON.stringify(data.fulfillmentService)}`);
// Step 1: Get the store address
const address = await getStoreAddress(client);
// Step 2: Create a new location with a custom name and the same address
// console.log(address)
const result = await createCustomLocation(address, client);
// console.log('Result from creating custom location:', result);
if (result.userErrors && result.userErrors.length > 0) {
console.error('Location creation errors:', result.userErrors);
} else {
console.log('Created location:', result.location);
}
var locationId = result.location ? result.location.id : null;
return { success: true, fulfillmentService: data.fulfillmentService, locationId };
} catch (error) {
log(shop, `💥 Request failed: ${error.response ? JSON.stringify(error.response.data) : error.message}`);
return { success: false, error: error.response ? error.response.data : error.message };
}
}
module.exports = { createFulfillmentService };
// const axios = require('axios');
// const { log } = require('./logger');
// /**
// * Create a Shopify fulfillment service.
// * @param {string} shop - The Shopify store domain (e.g., myshop.myshopify.com).
// * @param {string} accessToken - The Shopify Admin API access token.
// * @returns {Promise<object>} The created fulfillment service or error details.
// */
// async function createFulfillmentService(shop, accessToken) {
// const client = axios.create({
// baseURL: `https://${shop}/admin/api/2024-01/graphql.json`,
// headers: {
// 'X-Shopify-Access-Token': accessToken,
// 'Content-Type': 'application/json',
// },
// });
// const mutation = `
// mutation {
// fulfillmentServiceCreate(
// name: "Data4Autos Distribution",
// callbackUrl: "https://backend.data4autos.com/fulfillment",
// fulfillmentOrdersOptIn: true,
// inventoryManagement: true,
// trackingSupport: true
// ) {
// fulfillmentService {
// id
// serviceName
// callbackUrl
// handle
// location {
// id
// }
// }
// userErrors {
// field
// message
// }
// }
// }
// `;
// try {
// log(shop, `🚀 Creating fulfillment service...`);
// const response = await client.post('', { query: mutation });
// console.log(`Response from Shopify: ${JSON.stringify(response.data, null, 2)}`);
// const data = response.data.data.fulfillmentServiceCreate;
// if (data.userErrors && data.userErrors.length > 0) {
// console.log(shop, `❌ User errors: ${JSON.stringify(data.userErrors)}`);
// return { success: false, errors: data.userErrors };
// }
// log(shop, `✅ Fulfillment Service created: ${JSON.stringify(data.fulfillmentService)}`);
// return { success: true, fulfillmentService: data.fulfillmentService };
// } catch (error) {
// log(shop, `💥 Request failed: ${error.response ? JSON.stringify(error.response.data) : error.message}`);
// return { success: false, error: error.response ? error.response.data : error.message };
// }
// }
// module.exports = { createFulfillmentService };
// // -------------------------------
// // Test call (comment out later)
// // -------------------------------
// // (async () => {
// // const shop = "veloxautomotive.myshopify.com"; // Replace with your shop domain
// // const accessToken = "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"; // Replace with your token
// // const result = await createFulfillmentService(shop, accessToken);
// // console.log("Result:", result);
// // })();