← back to Designer Wallcoverings
DW-Agents/dw-agents/agent-task-orchestrator/update-theme-quantity.js
177 lines
require('dotenv').config({ path: require('path').join(__dirname, '.env') });
const axios = require('axios');
const SHOPIFY_STORE = 'designer-laboratory-sandbox.myshopify.com';
const ACCESS_TOKEN = process.env.SHOPIFY_THEME_TOKEN;
const THEME_ID = 138914332723;
const API_VERSION = '2024-01';
const baseURL = `https://${SHOPIFY_STORE}/admin/api/${API_VERSION}`;
const quantityValidatorScript = `
{%- comment -%} DW Quantity Validator - Reads variant metafields {%- endcomment -%}
<script>
(function() {
'use strict';
console.log('🎯 DW Quantity Validator Initializing...');
function getVariantMetafields(variantId) {
const variantData = document.querySelector('[data-variant-id="' + variantId + '"]');
if (variantData) {
return {
min: parseInt(variantData.dataset.minQty) || 1,
step: parseInt(variantData.dataset.stepQty) || 1
};
}
return { min: 1, step: 1 };
}
function updateQuantityInput(minQty, stepQty) {
const qtyInputs = document.querySelectorAll('input[name="quantity"], input[type="number"][id*="Quantity"], .quantity__input');
qtyInputs.forEach(function(input) {
input.setAttribute('min', minQty);
input.setAttribute('step', stepQty);
input.setAttribute('data-min', minQty);
input.setAttribute('data-step', stepQty);
if (parseInt(input.value) < minQty) {
input.value = minQty;
}
input.removeEventListener('change', validateHandler);
input.removeEventListener('blur', validateHandler);
input.addEventListener('change', validateHandler);
input.addEventListener('blur', validateHandler);
});
console.log('✅ Quantity rules applied: min=' + minQty + ', step=' + stepQty);
}
function validateHandler(e) {
validateQuantity(e.target);
}
function validateQuantity(input) {
const minQty = parseInt(input.getAttribute('data-min')) || 1;
const stepQty = parseInt(input.getAttribute('data-step')) || 1;
let value = parseInt(input.value);
if (isNaN(value) || value < minQty) {
input.value = minQty;
showMessage('Minimum order quantity is ' + minQty);
return;
}
const remainder = (value - minQty) % stepQty;
if (remainder !== 0) {
value = value - remainder + stepQty;
input.value = value;
showMessage('Please order in increments of ' + stepQty);
}
}
function showMessage(msg) {
var notification = document.getElementById('dw-qty-msg');
if (!notification) {
notification = document.createElement('div');
notification.id = 'dw-qty-msg';
notification.style.cssText = 'position:fixed;top:20px;right:20px;background:#ff6b6b;color:white;padding:12px 20px;border-radius:6px;box-shadow:0 4px 12px rgba(0,0,0,0.15);z-index:999999;font-size:14px;font-weight:500;';
document.body.appendChild(notification);
}
notification.textContent = msg;
notification.style.display = 'block';
setTimeout(function() {
notification.style.display = 'none';
}, 3000);
}
function initQuantityRules() {
var variantId = null;
var urlParams = new URLSearchParams(window.location.search);
variantId = urlParams.get('variant');
if (!variantId) {
var variantInput = document.querySelector('select[name="id"], input[name="id"]:checked, input[name="id"][type="hidden"]');
if (variantInput) {
variantId = variantInput.value;
}
}
if (!variantId) {
console.log('⚠️ No variant ID found');
return;
}
console.log('📦 Variant ID:', variantId);
var metafields = getVariantMetafields(variantId);
updateQuantityInput(metafields.min, metafields.step);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initQuantityRules);
} else {
initQuantityRules();
}
document.addEventListener('change', function(e) {
if (e.target.matches('select[name="id"], input[name="id"]')) {
setTimeout(initQuantityRules, 100);
}
});
document.addEventListener('submit', function(e) {
if (e.target.matches('form[action*="/cart/add"]')) {
var qtyInput = e.target.querySelector('input[name="quantity"]');
if (qtyInput && qtyInput.dataset.min && qtyInput.dataset.step) {
var minQty = parseInt(qtyInput.dataset.min);
var stepQty = parseInt(qtyInput.dataset.step);
var value = parseInt(qtyInput.value);
if (value < minQty || (value - minQty) % stepQty !== 0) {
e.preventDefault();
showMessage('Invalid quantity. Min: ' + minQty + ', Increments: ' + stepQty);
validateQuantity(qtyInput);
return false;
}
}
}
});
})();
</script>
`;
async function updateThemeLiquid() {
try {
console.log('📥 Fetching theme.liquid...');
const response = await axios.get(
`${baseURL}/themes/${THEME_ID}/assets.json?asset[key]=layout/theme.liquid`,
{
headers: {
'X-Shopify-Access-Token': ACCESS_TOKEN,
'Content-Type': 'application/json'
}
}
);
let themeContent = response.data.asset.value;
// Check if script already exists
if (themeContent.includes('DW Quantity Validator')) {
console.log('⚠️ Script already exists in theme.liquid');
return;
}
// Insert script before </body>
themeContent = themeContent.replace('</body>', quantityValidatorScript + '\n</body>');
console.log('📤 Uploading updated theme.liquid...');
await axios.put(
`${baseURL}/themes/${THEME_ID}/assets.json`,
{
asset: {
key: 'layout/theme.liquid',
value: themeContent
}
},
{
headers: {
'X-Shopify-Access-Token': ACCESS_TOKEN,
'Content-Type': 'application/json'
}
}
);
console.log('✅ Successfully updated theme.liquid!');
console.log('🎯 Quantity validator script added');
} catch (error) {
console.error('❌ Error:', error.response?.data || error.message);
}
}
updateThemeLiquid();