From 22d3fd707380dbdccfae281af4eb74991350c292 Mon Sep 17 00:00:00 2001 From: Bruce Denham Date: Wed, 10 Dec 2025 22:56:06 -0600 Subject: [PATCH 1/3] CRITICAL: Restore lost enrichment files 26 B2B enrichment JSON files were accidentally deleted during merges. Restored from releases/b2b-nov-release. --- .../company-management/events.json | 48 +++ .../company-management/functions.json | 139 +++++++++ .../company-management/initialization.json | 24 ++ .../company-management/overview.json | 99 ++++++ .../company-management/quick-start.json | 4 + .../purchase-order/events.json | 69 +++++ .../purchase-order/functions.json | 171 +++++++++++ .../purchase-order/initialization.json | 16 + .../purchase-order/overview.json | 116 +++++++ .../purchase-order/quick-start.json | 4 + .../quote-management/containers.json | 284 ++++++++++++++++++ .../quote-management/events.json | 232 ++++++++++++++ .../quote-management/functions.json | 186 ++++++++++++ .../quote-management/initialization.json | 19 ++ .../quote-management/overview.json | 106 +++++++ .../quote-management/quick-start.json | 4 + .../requisition-list/events.json | 72 +++++ .../requisition-list/functions.json | 139 +++++++++ .../requisition-list/initialization.json | 20 ++ .../requisition-list/overview.json | 98 ++++++ .../requisition-list/quick-start.json | 4 + 21 files changed, 1854 insertions(+) create mode 100644 _dropin-enrichments/company-management/events.json create mode 100644 _dropin-enrichments/company-management/functions.json create mode 100644 _dropin-enrichments/company-management/initialization.json create mode 100644 _dropin-enrichments/company-management/overview.json create mode 100644 _dropin-enrichments/company-management/quick-start.json create mode 100644 _dropin-enrichments/purchase-order/events.json create mode 100644 _dropin-enrichments/purchase-order/functions.json create mode 100644 _dropin-enrichments/purchase-order/initialization.json create mode 100644 _dropin-enrichments/purchase-order/overview.json create mode 100644 _dropin-enrichments/purchase-order/quick-start.json create mode 100644 _dropin-enrichments/quote-management/containers.json create mode 100644 _dropin-enrichments/quote-management/events.json create mode 100644 _dropin-enrichments/quote-management/functions.json create mode 100644 _dropin-enrichments/quote-management/initialization.json create mode 100644 _dropin-enrichments/quote-management/overview.json create mode 100644 _dropin-enrichments/quote-management/quick-start.json create mode 100644 _dropin-enrichments/requisition-list/events.json create mode 100644 _dropin-enrichments/requisition-list/functions.json create mode 100644 _dropin-enrichments/requisition-list/initialization.json create mode 100644 _dropin-enrichments/requisition-list/overview.json create mode 100644 _dropin-enrichments/requisition-list/quick-start.json diff --git a/_dropin-enrichments/company-management/events.json b/_dropin-enrichments/company-management/events.json new file mode 100644 index 000000000..37eff466b --- /dev/null +++ b/_dropin-enrichments/company-management/events.json @@ -0,0 +1,48 @@ +{ + "overview": "The **Company Management** drop-in uses the [event bus](/sdk/reference/events) to emit and listen to events for communication between drop-ins and external integrations. These events enable real-time updates for company administration, including company structure changes, user management, team operations, and permission updates.", + "company/updated": { + "whenTriggered": [ + "After successful company profile update", + "After updating company legal address", + "After updating company contact information", + "After updating sales representative information" + ], + "examples": [ + { + "title": "Basic company update handler", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\n\n// Listen for company updates\nevents.on('company/updated', (payload) => {\n console.log('Company updated:', payload.data);\n \n // Update UI or trigger other actions\n refreshCompanyDisplay();\n});\n```" + }, + { + "title": "Update with notification and error handling", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\nimport { updateCompany } from '@dropins/storefront-company-management/api.js';\n\nasync function updateCompanyProfile(updates) {\n try {\n // Show loading state\n showLoadingIndicator('Updating company profile...');\n \n // Update the company\n await updateCompany(updates);\n \n // Listen for successful update\n events.once('company/updated', (payload) => {\n hideLoadingIndicator();\n showSuccessNotification('Company profile updated successfully');\n \n // Update the displayed company information\n document.querySelector('.company-name').textContent = payload.data.companyName;\n document.querySelector('.company-email').textContent = payload.data.email;\n \n // Track the update in analytics\n trackEvent('company_profile_updated', {\n companyId: payload.data.id,\n fieldsUpdated: Object.keys(updates)\n });\n });\n \n } catch (error) {\n hideLoadingIndicator();\n showErrorNotification('Failed to update company profile: ' + error.message);\n console.error('Company update error:', error);\n }\n}\n\n// Usage\nupdateCompanyProfile({\n companyName: 'Acme Corporation',\n email: 'info@acme.com',\n telephone: '+1-555-0123'\n});\n```" + }, + { + "title": "Real-time multi-component sync", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\n\n// Central company data manager\nclass CompanyDataManager {\n constructor() {\n this.subscribers = [];\n \n // Listen for company updates\n events.on('company/updated', this.handleCompanyUpdate.bind(this));\n }\n \n handleCompanyUpdate(payload) {\n const companyData = payload.data;\n \n // Update all subscribed components\n this.subscribers.forEach(callback => {\n try {\n callback(companyData);\n } catch (error) {\n console.error('Error updating subscriber:', error);\n }\n });\n \n // Update local storage for offline support\n localStorage.setItem('companyData', JSON.stringify(companyData));\n \n // Sync with external CRM\n this.syncWithCRM(companyData);\n }\n \n subscribe(callback) {\n this.subscribers.push(callback);\n }\n \n async syncWithCRM(companyData) {\n try {\n await fetch('/api/crm/update-company', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(companyData)\n });\n } catch (error) {\n console.error('CRM sync failed:', error);\n }\n }\n}\n\n// Initialize manager\nconst companyManager = new CompanyDataManager();\n\n// Subscribe components\ncompanyManager.subscribe((data) => {\n // Update header component\n document.querySelector('.header-company-name').textContent = data.companyName;\n});\n\ncompanyManager.subscribe((data) => {\n // Update sidebar widget\n updateCompanySidebarWidget(data);\n});\n```" + } + ], + "usageScenarios": "- Refresh company profile display after edits.\n- Trigger analytics tracking for profile changes.\n- Update related UI components (headers, sidebars, widgets).\n- Sync company data with external systems (CRM, ERP).\n- Show success notifications to users.\n- Update cached data and local storage.\n- Refresh company-dependent permissions.\n- Update breadcrumbs and navigation with company name.\n\n---" + }, + "companyStructure/updated": { + "whenTriggered": [ + "After creating a new team", + "After updating team information", + "After deleting a team", + "After creating a new user", + "After updating user details", + "After moving users between teams", + "After changing team hierarchy" + ], + "examples": [ + { + "title": "Interactive structure tree with live updates", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\nimport { getCompanyStructure } from '@dropins/storefront-company-management/api.js';\n\nclass CompanyStructureTree {\n constructor(containerElement) {\n this.container = containerElement;\n this.structureData = null;\n \n // Listen for structure updates\n events.on('companyStructure/updated', this.handleUpdate.bind(this));\n \n // Initial load\n this.loadStructure();\n }\n \n async loadStructure() {\n try {\n this.showLoading();\n this.structureData = await getCompanyStructure();\n this.render();\n } catch (error) {\n this.showError('Failed to load company structure');\n console.error(error);\n }\n }\n \n async handleUpdate(payload) {\n console.log('Structure updated:', payload.data);\n \n // Highlight the updated section\n const updatedNodeId = payload.data.updatedNodeId;\n if (updatedNodeId) {\n this.highlightNode(updatedNodeId);\n }\n \n // Reload the full structure\n await this.loadStructure();\n \n // Show success message\n this.showNotification('Organization structure updated', 'success');\n \n // Refresh permissions for all users in the tree\n await this.refreshPermissions();\n }\n \n highlightNode(nodeId) {\n const nodeElement = this.container.querySelector(`[data-node-id=\"${nodeId}\"]`);\n if (nodeElement) {\n nodeElement.classList.add('highlight-update');\n setTimeout(() => nodeElement.classList.remove('highlight-update'), 2000);\n }\n }\n \n render() {\n // Render the structure tree\n this.container.innerHTML = this.buildTreeHTML(this.structureData);\n this.attachEventListeners();\n }\n \n buildTreeHTML(structure) {\n // Build hierarchical HTML for the structure\n return `
...
`;\n }\n \n async refreshPermissions() {\n // Refresh permissions after structure change\n events.emit('permissions/refresh-needed');\n }\n \n showLoading() {\n this.container.innerHTML = '
Loading structure...
';\n }\n \n showError(message) {\n this.container.innerHTML = `
${message}
`;\n }\n \n showNotification(message, type) {\n // Show toast notification\n const notification = document.createElement('div');\n notification.className = `notification notification-${type}`;\n notification.textContent = message;\n document.body.appendChild(notification);\n setTimeout(() => notification.remove(), 3000);\n }\n \n attachEventListeners() {\n // Add drag-and-drop, expand/collapse, etc.\n }\n}\n\n// Initialize the tree\nconst tree = new CompanyStructureTree(document.querySelector('#company-structure'));\n```" + }, + { + "title": "Team-based notification system", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\n\n// Track structure changes and notify affected users\nevents.on('companyStructure/updated', async (payload) => {\n const { data } = payload;\n \n // Determine what changed\n const changeType = determineChangeType(data);\n \n switch (changeType) {\n case 'team-created':\n notifyTeamCreation(data.newTeam);\n break;\n case 'team-deleted':\n notifyTeamDeletion(data.deletedTeam);\n break;\n case 'user-moved':\n notifyUserReassignment(data.user, data.oldTeam, data.newTeam);\n break;\n case 'hierarchy-changed':\n notifyHierarchyChange(data.affectedTeams);\n break;\n }\n \n // Update all team-based UI components\n updateTeamSelectors();\n updateUserFilters();\n refreshTeamDashboards();\n \n // Log for audit trail\n logStructureChange({\n timestamp: new Date(),\n changeType,\n userId: getCurrentUserId(),\n details: data\n });\n});\n\nfunction determineChangeType(data) {\n // Logic to determine what type of change occurred\n if (data.newTeam) return 'team-created';\n if (data.deletedTeam) return 'team-deleted';\n if (data.userMoved) return 'user-moved';\n return 'hierarchy-changed';\n}\n\nasync function notifyUserReassignment(user, oldTeam, newTeam) {\n const message = `${user.name} has been moved from ${oldTeam.name} to ${newTeam.name}`;\n \n // Notify team managers\n await sendNotification([oldTeam.managerId, newTeam.managerId], message);\n \n // Notify the user\n await sendNotification([user.id], `You have been assigned to ${newTeam.name}`);\n \n // Update UI\n showToast(message, 'info');\n}\n\nfunction logStructureChange(logEntry) {\n // Send to audit log\n fetch('/api/audit/log', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(logEntry)\n });\n}\n```" + } + ], + "usageScenarios": "- Refresh the company structure tree display in real-time.\n- Update user access controls based on new hierarchy.\n- Trigger notifications to affected team members.\n- Log organizational changes for audit and compliance.\n- Update cached structure data and local storage.\n- Refresh team-based dropdowns and filters.\n- Update permission matrices after reassignments.\n- Highlight changes in the structure visualization.\n- Trigger workflow updates (approval chains, and so on).\n- Sync organizational structure with external HR systems.\n\n---\n\n## Listening to events\n\nAll Company Management events are emitted through the centralized event bus. Subscribe to events using the `events.on()` method:\n\n```js\nimport { events } from '@dropins/tools/event-bus.js';\n\n// Single event listener\nevents.on('company/updated', (payload) => {\n // Handle company update\n});\n\n// Multiple event listeners\nevents.on('company/updated', handleCompanyUpdate);\nevents.on('companyStructure/updated', handleStructureUpdate);\n\n// Remove listeners when no longer needed\nevents.off('company/updated', handleCompanyUpdate);\n```\n\n\n\n## Related documentation\n\n- [Functions](/dropins-b2b/company-management/functions/) - API functions that emit these events\n- [Containers](/dropins-b2b/company-management/containers/) - UI components that respond to events\n- [Event bus documentation](/sdk/reference/events/) - Learn more about the event system\n\n{/* This documentation is manually curated based on: https://github.com/adobe-commerce/storefront-company-management */}" + } +} diff --git a/_dropin-enrichments/company-management/functions.json b/_dropin-enrichments/company-management/functions.json new file mode 100644 index 000000000..873df5e74 --- /dev/null +++ b/_dropin-enrichments/company-management/functions.json @@ -0,0 +1,139 @@ +{ + "overview": "The Company Management drop-in provides **26 API functions** for managing company structures, users, roles, permissions, and credit, enabling complete B2B company administration workflows.", + "createCompanyRole": { + "parameters": { + "formData": { + "description": "An object containing the role configuration including role name, permissions array, and any custom attributes. The structure depends on your company's role configuration requirements." + } + } + }, + "deleteCompanyRole": { + "parameters": { + "variables": { + "description": "An object of type `DeleteCompanyRoleVariables` containing the role ID to delete. See the type definition for the exact structure." + } + } + }, + "deleteCompanyStructureNode": { + "parameters": { + "id": { + "description": "The unique identifier for the company structure node (team or division) to delete. This removes the node and may reassign users depending on your company's configuration." + } + } + }, + "deleteCompanyUser": { + "parameters": { + "params": { + "description": "An object of type `DeleteCompanyUserParams` containing the user ID to delete and any additional parameters required for user deletion." + } + } + }, + "getCompany": { + "description": "Retrieves complete information about the current company including name, structure, settings, and metadata. Returns the full company profile for the authenticated user's company context.", + "returns": "Returns a Promise that resolves to a `CompanyModel` object containing comprehensive company details." + }, + "getCompanyCredit": { + "description": "Retrieves the company's credit information including available credit, credit limit, outstanding balance, and currency. This is used to display company credit status and validate purchase limits.", + "returns": "Returns a Promise that resolves to a `CompanyCreditModel` object containing credit details." + }, + "getCompanyCreditHistory": { + "parameters": { + "params": { + "description": "An optional object of type `GetCompanyCreditHistoryParams` containing pagination parameters (currentPage, pageSize) and optional filters. Omit to retrieve history with default pagination." + } + } + }, + "getCompanyRole": { + "parameters": { + "variables": { + "description": "An object of type `GetCompanyRoleVariables` containing the role ID to retrieve. Returns complete role details including permissions and assigned users." + } + } + }, + "getCompanyRoles": { + "parameters": { + "variables": { + "description": "An optional object of type `GetCompanyRolesVariables` containing pagination and filter parameters. Omit to retrieve all company roles with default pagination." + } + } + }, + "getCompanyStructure": { + "description": "Retrieves the hierarchical organization structure of the company including all teams, divisions, and reporting relationships. Returns the complete company tree structure.", + "returns": "Returns a Promise that resolves to a `CompanyStructureModel` object representing the organizational hierarchy." + }, + "getCompanyStructureNode": { + "parameters": { + "id": { + "description": "The unique identifier for a specific company structure node (team or division). Returns detailed information about that node including its position in the hierarchy and assigned users." + } + } + }, + "getCompanyUser": { + "parameters": { + "id": { + "description": "The unique identifier for the company user to retrieve. Returns complete user profile including role, team assignment, and permissions." + } + } + }, + "getCompanyUsers": { + "parameters": { + "params": { + "description": "An optional object of type `CompanyUsersParams` containing pagination and filter criteria (currentPage, pageSize, filter). Omit to retrieve all users with default pagination." + } + } + }, + "getCustomerRolePermissions": { + "description": "Retrieves the current customer's role-based permissions within the company. Returns permission flags indicating what company management actions the user is authorized to perform (manage users, approve purchases, view reports, etc.).", + "returns": "Returns a Promise that resolves to a `CustomerRolePermissionsModel` object containing boolean permission flags for various company actions." + }, + "initialize": { + "parameters": { + "config": { + "description": "An optional configuration object of type `CompanyDropinConfig` containing initialization settings such as langDefinitions for internationalization. If omitted, default configuration is used." + } + } + }, + "isCompanyRoleNameAvailable": { + "parameters": { + "variables": { + "description": "An object of type `IsCompanyRoleNameAvailableVariables` containing the role name to check for availability. Returns a boolean indicating whether the name can be used for a new role." + } + } + }, + "updateCompanyRole": { + "parameters": { + "params": { + "description": "An object of type `UpdateCompanyRoleParams` containing the role ID and fields to update (name, permissions array, status). See the type definition for complete structure." + } + } + }, + "updateCompanyUserStatus": { + "parameters": { + "params": { + "description": "An object of type `UpdateCompanyUserStatusParams` containing the user ID and the new status value (active, inactive). Used to enable or disable user access to company resources." + } + } + }, + "createCompany": { + "parameters": { + "formData": { + "description": "An object containing the company registration information including company name, legal name, email, VAT/TAX ID, and resale number. The structure depends on your store's company registration requirements." + } + } + }, + "deleteCompanyTeam": { + "parameters": { + "id": { + "description": "The unique identifier for the company team (structure node) to delete. This removes the team and may reassign team members depending on your company's configuration." + } + } + }, + "getCompanyTeam": { + "parameters": { + "id": { + "description": "The unique identifier for the company team to retrieve. Returns detailed information about the team including its name, members, and position in the company hierarchy." + } + } + } +} + diff --git a/_dropin-enrichments/company-management/initialization.json b/_dropin-enrichments/company-management/initialization.json new file mode 100644 index 000000000..82bcd1cb9 --- /dev/null +++ b/_dropin-enrichments/company-management/initialization.json @@ -0,0 +1,24 @@ +{ + "intro": "The **Company Management initializer** configures the drop-in for managing company accounts, organizational structures, user roles, and permissions. Use initialization to customize how company data is displayed and enable internationalization for multi-language B2B storefronts.", + "config": { + "langDefinitions": { + "description": "Language definitions for internationalization (i18n). Override dictionary keys for localization or branding." + } + }, + "customModelExample": "const models = {\n CompanyModel: {\n transformer: (data) => ({\n // Add formatted display name with legal name fallback\n displayName: data?.legalName || data?.name,\n // Add admin contact full name\n adminFullName: data?.companyAdmin ? \n `${data.companyAdmin.firstName} ${data.companyAdmin.lastName}` : null,\n // Add formatted VAT/Tax ID display\n taxIdDisplay: data?.vatTaxId ? `VAT: ${data.vatTaxId}` : null,\n }),\n },\n};\n\nawait initializers.mountImmediately(initialize, { models });", + "models": { + "CompanyModel": { + "description": "Transforms company data from GraphQL including company profile, legal address, contact information, and settings. Use this to add custom fields or modify existing company data structures.", + "definition": "export interface CompanyModel extends Company {\n // Extended properties for UI and permissions (from Customer context)\n canEditAccount: boolean;\n canEditAddress: boolean;\n customerRole?: CompanyRoleModel;\n customerStatus?: string;\n permissionsFlags: {\n canViewAccount: boolean;\n canEditAccount: boolean;\n canViewAddress: boolean;\n canEditAddress: boolean;\n canViewContacts: boolean;\n canViewPaymentInformation: boolean;\n canViewShippingInformation: boolean;\n // Structure permissions for users/teams\n canViewUsers: boolean;\n canEditUsers: boolean;\n canViewRoles: boolean;\n canManageRoles: boolean;\n };\n}\n\nexport interface Company {\n id: string;\n name: string;\n email: string;\n legalName?: string;\n vatTaxId?: string;\n resellerId?: string;\n legalAddress?: CompanyLegalAddressModel;\n companyAdmin?: CompanyContact;\n salesRepresentative?: CompanySalesRepresentative;\n availablePaymentMethods?: { code: string; title: string }[];\n availableShippingMethods?: { code: string; title: string }[];\n}" + }, + "CompanyUserModel": { + "description": "Transforms company user data including user details, roles, permissions, and team assignments. Use this to add custom fields or modify user data structures.", + "definition": "export interface CompanyUserModel extends CompanyUser {\n isCompanyAdmin?: boolean;\n}\n\nexport interface CompanyUser {\n id: string;\n email: string;\n firstName: string;\n lastName: string;\n jobTitle?: string | null;\n telephone?: string | null;\n status?: string | null;\n role?: {\n id: string;\n name: string;\n } | null;\n}" + }, + "CompanyStructureNode": { + "description": "Transforms company organizational structure data including teams, hierarchy, and user assignments. Use this to add custom fields or modify structure data.", + "definition": "export interface CompanyStructureNode {\n id: string; // structure uid (base64)\n parentId: string | null; // structure uid (base64) or null for root\n label: string;\n type: CompanyStructureNodeType;\n entityId?: string; // entity uid for team/customer\n description?: string | null; // team description if available\n}\n\nexport type CompanyStructureNodeType = 'team' | 'user';" + } + } +} + diff --git a/_dropin-enrichments/company-management/overview.json b/_dropin-enrichments/company-management/overview.json new file mode 100644 index 000000000..159e0efdd --- /dev/null +++ b/_dropin-enrichments/company-management/overview.json @@ -0,0 +1,99 @@ +{ + "introduction": "The Company Management drop-in enables company profile management and role-based permissions for Adobe Commerce storefronts. It also supports legal address management and company contact information.", + "supported_features": [ + { + "feature": "Company profile management", + "status": "Supported" + }, + { + "feature": "Role-based permissions", + "status": "Supported" + }, + { + "feature": "Legal address management", + "status": "Supported" + }, + { + "feature": "Company contact information", + "status": "Supported" + }, + { + "feature": "Payment methods configuration", + "status": "Supported" + }, + { + "feature": "Shipping methods configuration", + "status": "Supported" + }, + { + "feature": "Multi-language support", + "status": "Supported" + }, + { + "feature": "Custom regions for international addresses", + "status": "Supported" + }, + { + "feature": "Email validation", + "status": "Supported" + }, + { + "feature": "GraphQL API integration", + "status": "Supported" + }, + { + "feature": "Company hierarchy management", + "status": "Supported" + }, + { + "feature": "Advanced user role management", + "status": "Supported" + } + ], + "section_topics": { + "intro": "The topics in this section will help you understand how to customize and use the Company Management effectively within your storefront.", + "sections": [ + { + "title": "Quick Start", + "description": "Provides quick reference information and getting started guide for the Company Management drop-in. This topic covers package details, import paths, and basic usage examples to help you integrate Company Management functionality into your site.", + "link": "/dropins-b2b/company-management/quick-start/" + }, + { + "title": "Initialization", + "description": "**[Drop-in developer]:** Add 1-2 sentences describing what configuration options are available and what needs to be set up before using this drop-in.", + "link": "/dropins-b2b/company-management/initialization/" + }, + { + "title": "Containers", + "description": "**[Drop-in developer]:** Add 1-2 sentences listing the main UI containers and what they're used for.", + "link": "/dropins-b2b/company-management/containers/" + }, + { + "title": "Functions", + "description": "**[Drop-in developer]:** Add 1-2 sentences describing the main API functions and what operations they enable.", + "link": "/dropins-b2b/company-management/functions/" + }, + { + "title": "Events", + "description": "**[Drop-in developer]:** Add 1-2 sentences describing what events are emitted and when they trigger.", + "link": "/dropins-b2b/company-management/events/" + }, + { + "title": "Slots", + "description": "**[Drop-in developer]:** Add 1-2 sentences describing what parts of the UI can be customized with slots.", + "link": "/dropins-b2b/company-management/slots/" + }, + { + "title": "Dictionary", + "description": "**[Drop-in developer]:** Add 1-2 sentences describing the i18n keys and what they're used for.", + "link": "/dropins-b2b/company-management/dictionary/" + }, + { + "title": "Styles", + "description": "**[Drop-in developer]:** Add 1-2 sentences describing what visual elements can be styled.", + "link": "/dropins-b2b/company-management/styles/" + } + ] + } +} + diff --git a/_dropin-enrichments/company-management/quick-start.json b/_dropin-enrichments/company-management/quick-start.json new file mode 100644 index 000000000..b3b1cbe13 --- /dev/null +++ b/_dropin-enrichments/company-management/quick-start.json @@ -0,0 +1,4 @@ +{ + "intro": "Get started with the Company Management drop-in to enable self-service company administration in your B2B storefront." +} + diff --git a/_dropin-enrichments/purchase-order/events.json b/_dropin-enrichments/purchase-order/events.json new file mode 100644 index 000000000..8234af518 --- /dev/null +++ b/_dropin-enrichments/purchase-order/events.json @@ -0,0 +1,69 @@ +{ + "overview": "The **Purchase Order** drop-in uses the [event bus](/sdk/reference/events) to emit and listen to events for communication between drop-ins and external integrations. These events enable real-time updates for purchase order operations, including order creation, approval workflows, status tracking, and approval rule management.", + "order/data": { + "whenTriggered": [ + "When the Purchase Order Details page loads with a poRef parameter", + "After purchase-order/refresh event (emitted together with purchase-order/data)" + ], + "examples": [ + { + "title": "Display purchase order details", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\n\nevents.on('order/data', (payload) => {\n console.log('Purchase order data for Order containers:', payload.data);\n \n // Initialize Order Drop-In containers with PO data\n displayPurchaseOrderDetailsInOrderContainers(payload.data);\n \n // Extract purchase order information\n const { number, status, items } = payload.data;\n});\n```" + } + ], + "usageScenarios": "- Initialize Order Drop-In containers with purchase order data.\n- Display purchase order details on the PO Details page.\n- Sync PO data after refresh events.\n- Update UI when PO data loads.\n\n---" + }, + "purchase-order/data": { + "whenTriggered": [ + "After loading a purchase order", + "After approving a purchase order", + "After rejecting a purchase order", + "After canceling a purchase order", + "After adding comments to a purchase order", + "After updating purchase order status" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\n\nevents.on('purchase-order/data', (payload) => {\n const po = payload.data;\n console.log('Purchase order updated:', po.number, po.status);\n \n // Update the UI to reflect current status\n updatePurchaseOrderStatus(po.status);\n \n // Show approval flow if needed\n if (po.requiresApproval) {\n displayApprovalFlow(po.approvalFlow);\n }\n});\n```" + } + ], + "usageScenarios": "- Refresh the purchase order details view.\n- Update purchase order lists.\n- Display the approval flow progress.\n- Show status-specific actions.\n- Update cached purchase order data.\n\n---" + }, + "purchase-order/placed": { + "whenTriggered": [ + "After successfully calling `placePurchaseOrder()`", + "After converting a cart to a purchase order" + ], + "examples": [ + { + "title": "Basic purchase order placement", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\n\nevents.on('purchase-order/placed', (payload) => {\n const { number: purchaseOrderNumber, status } = payload.data;\n const requiresApproval = status !== \"APPROVED\";\n \n console.log(`Purchase order ${purchaseOrderNumber} placed with status: ${status}`);\n \n // Show appropriate confirmation message\n if (requiresApproval) {\n showMessage('Purchase order submitted for approval');\n redirectToApprovalStatus(purchaseOrderNumber);\n } else {\n showMessage('Purchase order placed successfully');\n redirectToOrderConfirmation(purchaseOrderNumber);\n }\n \n // Track analytics\n trackPurchaseOrderPlacement(purchaseOrderNumber, requiresApproval);\n});\n```" + }, + { + "title": "Complete checkout workflow with notifications", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\nimport { placePurchaseOrder } from '@dropins/storefront-purchase-order/api.js';\n\nasync function completePurchaseOrderCheckout(cartId) {\n try {\n // Show checkout processing\n showCheckoutModal('Processing your purchase order...');\n \n // Place the purchase order\n await placePurchaseOrder(cartId);\n \n // Listen for successful placement\n events.once('purchase-order/placed', async (payload) => {\n const { number: purchaseOrderNumber, status } = payload.data;\n const requiresApproval = status !== \"APPROVED\";\n \n // Close processing modal\n hideCheckoutModal();\n \n // Clear cart UI\n clearCartDisplay();\n \n // Show success modal with details\n if (requiresApproval) {\n showSuccessModal({\n title: 'Purchase Order Submitted',\n message: `Your purchase order #${purchaseOrderNumber} has been submitted for approval.`,\n details: [\n `Status: Pending Approval`,\n `You will be notified when it's reviewed.`,\n `Track your order in the Purchase Orders section.`\n ],\n primaryAction: {\n label: 'View Purchase Order',\n onClick: () => window.location.href = `/purchase-orders/${purchaseOrderNumber}`\n },\n secondaryAction: {\n label: 'Continue Shopping',\n onClick: () => window.location.href = '/products'\n }\n });\n \n // Send notification email\n await sendNotification({\n type: 'purchase-order-submitted',\n purchaseOrderNumber,\n approvers: payload.data.approvers\n });\n \n } else {\n showSuccessModal({\n title: 'Order Placed Successfully',\n message: `Your purchase order #${purchaseOrderNumber} has been placed.`,\n details: [\n `Status: ${status}`,\n `You will receive a confirmation email shortly.`\n ],\n primaryAction: {\n label: 'View Order',\n onClick: () => window.location.href = `/orders/${purchaseOrderNumber}`\n }\n });\n }\n \n // Track conversion\n trackConversion({\n type: 'purchase-order',\n orderNumber: purchaseOrderNumber,\n requiresApproval,\n value: payload.data.total,\n currency: payload.data.currency\n });\n \n // Update user's PO history count\n incrementPurchaseOrderCount();\n });\n \n } catch (error) {\n hideCheckoutModal();\n showErrorModal({\n title: 'Failed to Place Purchase Order',\n message: error.message || 'An error occurred while processing your order.',\n action: {\n label: 'Try Again',\n onClick: () => completePurchaseOrderCheckout(cartId)\n }\n });\n console.error('Purchase order placement error:', error);\n }\n}\n```" + }, + { + "title": "Multi-approval workflow dashboard", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\n\n// Dashboard for tracking all purchase orders\nclass PurchaseOrderDashboard {\n constructor() {\n this.pendingOrders = [];\n this.completedOrders = [];\n \n // Listen for new purchase orders\n events.on('purchase-order/placed', this.handleNewOrder.bind(this));\n events.on('purchase-order/data', this.handleOrderUpdate.bind(this));\n \n this.init();\n }\n \n async init() {\n await this.loadExistingOrders();\n this.render();\n }\n \n handleNewOrder(payload) {\n const { number: purchaseOrderNumber, status } = payload.data;\n const requiresApproval = status !== \"APPROVED\";\n \n const order = {\n number: purchaseOrderNumber,\n status: status,\n requiresApproval,\n placedAt: new Date(),\n ...payload.data\n };\n \n if (requiresApproval) {\n this.pendingOrders.unshift(order);\n \n // Show real-time notification\n this.showNotificationBanner({\n type: 'info',\n message: `New PO #${purchaseOrderNumber} awaiting approval`,\n action: () => this.viewOrder(purchaseOrderNumber)\n });\n \n // Play notification sound\n this.playNotificationSound();\n \n // Update pending count badge\n this.updatePendingBadge(this.pendingOrders.length);\n \n } else {\n this.completedOrders.unshift(order);\n }\n \n // Refresh dashboard display\n this.render();\n }\n \n handleOrderUpdate(payload) {\n const updatedOrder = payload.data;\n \n // Remove from pending if approved/rejected\n if (['approved', 'rejected', 'canceled'].includes(updatedOrder.status)) {\n this.pendingOrders = this.pendingOrders.filter(\n o => o.number !== updatedOrder.number\n );\n this.completedOrders.unshift(updatedOrder);\n this.updatePendingBadge(this.pendingOrders.length);\n }\n \n this.render();\n }\n \n render() {\n document.querySelector('#pending-orders').innerHTML = \n this.renderOrderList(this.pendingOrders, 'pending');\n document.querySelector('#completed-orders').innerHTML = \n this.renderOrderList(this.completedOrders, 'completed');\n }\n \n renderOrderList(orders, type) {\n if (orders.length === 0) {\n return `
No ${type} purchase orders
`;\n }\n \n return orders.map(order => `\n
\n
\n #${order.number}\n ${order.status}\n
\n
\n Total: $${order.total}\n Date: ${formatDate(order.placedAt)}\n
\n
\n `).join('');\n }\n \n showNotificationBanner(options) {\n // Show slide-in notification\n const banner = document.createElement('div');\n banner.className = `notification-banner notification-${options.type}`;\n banner.innerHTML = `\n ${options.message}\n \n `;\n if (options.action) {\n banner.onclick = options.action;\n }\n document.body.appendChild(banner);\n setTimeout(() => banner.remove(), 5000);\n }\n \n playNotificationSound() {\n const audio = new Audio('/sounds/notification.mp3');\n audio.play().catch(() => {});\n }\n \n updatePendingBadge(count) {\n const badge = document.querySelector('.pending-count-badge');\n if (badge) {\n badge.textContent = count;\n badge.style.display = count > 0 ? 'block' : 'none';\n }\n }\n \n viewOrder(orderNumber) {\n window.location.href = `/purchase-orders/${orderNumber}`;\n }\n \n async loadExistingOrders() {\n // Load existing orders from API\n const { pendingOrders, completedOrders } = await fetchPurchaseOrders();\n this.pendingOrders = pendingOrders;\n this.completedOrders = completedOrders;\n }\n}\n\n// Initialize dashboard\nconst dashboard = new PurchaseOrderDashboard();\n```" + } + ], + "usageScenarios": "- Display success confirmation with order details.\n- Redirect to the success page (approval or direct order).\n- Clear shopping cart after successful placement.\n- Send email notifications to approvers.\n- Track analytics and conversion events.\n- Update purchase order history and counts.\n- Show real-time notifications for new orders.\n- Update dashboard widgets and badges.\n- Trigger approval workflow notifications.\n- Log purchase order creation for audit.\n- Update budget tracking systems.\n- Sync with ERP/accounting systems.\n\n---" + }, + "purchase-order/refresh": { + "whenTriggered": [ + "After approval rule changes", + "After permission updates", + "On user request (manual refresh)", + "After significant state changes" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\n\n// Emit refresh event\nevents.emit('purchase-order/refresh', {\n purchaseOrderId: 'PO123456'\n});\n\n// Listen for refresh requests\nevents.on('purchase-order/refresh', async (payload) => {\n if (payload.data.purchaseOrderId) {\n // Refresh specific purchase order\n await refreshPurchaseOrder(payload.data.purchaseOrderId);\n } else {\n // Refresh all purchase orders\n await refreshAllPurchaseOrders();\n }\n});\n```" + } + ], + "usageScenarios": "- Force reload after external updates.\n- Implement pull-to-refresh functionality.\n- Sync data after background changes.\n- Refresh after approval rule modifications.\n\n---\n\n## Listening to events\n\nAll Purchase Order events are emitted through the centralized event bus. Subscribe to events using the `events.on()` method:\n\n```js\nimport { events } from '@dropins/tools/event-bus.js';\n\n// Listen to purchase order lifecycle events\nevents.on('purchase-order/placed', handlePurchaseOrderPlaced);\nevents.on('purchase-order/data', handlePurchaseOrderData);\nevents.on('purchase-order/refresh', handleRefreshRequest);\n\n// Remove listeners when done\nevents.off('purchase-order/placed', handlePurchaseOrderPlaced);\n```\n\n\n\n\n\n## Related documentation\n\n- [Functions](/dropins-b2b/purchase-order/functions/) - API functions that emit these events\n- [Containers](/dropins-b2b/purchase-order/containers/) - UI components that respond to events\n- [Event bus documentation](/sdk/reference/events/) - Learn more about the event system\n\n{/* This documentation is manually curated based on: https://github.com/adobe-commerce/storefront-purchase-order */}" + } +} diff --git a/_dropin-enrichments/purchase-order/functions.json b/_dropin-enrichments/purchase-order/functions.json new file mode 100644 index 000000000..9bbc8dd50 --- /dev/null +++ b/_dropin-enrichments/purchase-order/functions.json @@ -0,0 +1,171 @@ +{ + "overview": "The Purchase Order drop-in provides **12 API functions** for managing the complete purchase order workflow, including adding items to cart, approving, rejecting, canceling, and tracking purchase order status.", + "addPurchaseOrderComment": { + "parameters": { + "uid": { + "description": "The unique identifier for the purchase order to which the comment will be added." + }, + "comment": { + "description": "The text content of the comment to add to the purchase order. Use this to provide context, approval notes, or communication between team members reviewing the purchase order." + } + } + }, + "addPurchaseOrderItemsToCart": { + "parameters": { + "purchaseOrderUid": { + "description": "The unique identifier for the purchase order containing the items to add to the cart." + }, + "cartId": { + "description": "The unique identifier for the shopping cart. This ID is used to track and persist cart data across sessions." + }, + "replaceExistingCartItems": { + "description": "A boolean flag controlling cart merge behavior. When `true`, replaces all existing cart items with the purchase order items. When `false` (default), appends the purchase order items to existing cart contents." + } + } + }, + "approvePurchaseOrders": { + "parameters": { + "uids": { + "description": "One or more purchase order unique identifiers to approve. Can be a single UID string or an array of UIDs for batch approval operations." + } + } + }, + "cancelPurchaseOrders": { + "parameters": { + "uids": { + "description": "One or more purchase order unique identifiers to cancel. Can be a single UID string or an array of UIDs for batch cancellation operations." + } + } + }, + "getApprovalFlowMetadata": { + "description": "Retrieves approval flow metadata for the current company. Returns approval rule configurations, required approval levels, and workflow settings that govern purchase order approval requirements.", + "returns": "Returns a Promise that resolves to an `ApprovalFlowMetadataModel` object containing approval rules, spending limits, and workflow configuration." + }, + "getApprovalRules": { + "parameters": { + "uids": { + "description": "One or more approval rule unique identifiers to retrieve. Can be a single UID string or an array of UIDs to fetch multiple approval rules." + } + } + }, + "getCustomerRolePermissions": { + "description": "Retrieves the current customer's role permissions within the company. Returns permission flags indicating what purchase order actions the user is authorized to perform (view, create, approve, reject, etc.).", + "returns": "Returns a Promise that resolves to a `CustomerRolePermissionsModel` object containing boolean permission flags." + }, + "getPurchaseOrderDetails": { + "parameters": { + "uid": { + "description": "The unique identifier for the purchase order to retrieve. Returns complete purchase order details including items, status, history, comments, and approval information." + } + } + }, + "getPurchaseOrderInCheckout": { + "parameters": { + "id": { + "description": "The purchase order identifier to retrieve during the checkout process. Used to display purchase order context and validation in the checkout flow." + } + } + }, + "getPurchaseOrders": { + "parameters": { + "currentPage": { + "description": "The page number for pagination (1-indexed). Used to navigate through multiple pages of purchase orders." + }, + "pageSize": { + "description": "The number of purchase orders to return per page. Controls how many orders appear on each page of results." + } + } + }, + "getPurchaseOrdersList": { + "parameters": { + "filter": { + "description": "An optional filter object to narrow purchase order results by criteria such as status, date range, or requester. The structure depends on the GraphQL query's filter input type." + }, + "pageSize": { + "description": "The number of purchase orders to return per page." + }, + "currentPage": { + "description": "The page number for pagination (1-indexed)." + } + } + }, + "rejectPurchaseOrder": { + "parameters": { + "purchaseOrderUid": { + "description": "The unique identifier for the purchase order to reject. This action moves the purchase order to rejected status and prevents further processing." + } + } + }, + "rejectPurchaseOrders": { + "parameters": { + "uids": { + "description": "One or more purchase order unique identifiers to reject. Can be a single UID string or an array of UIDs for batch rejection operations." + } + } + }, + "validatePurchaseOrderNumber": { + "parameters": { + "uids": { + "description": "One or more purchase order unique identifiers to validate. Returns validation status indicating whether the purchase orders exist and are in a valid state for the requested operation." + } + } + }, + "getPurchaseOrder": { + "parameters": { + "uid": { + "description": "The unique identifier for the purchase order to retrieve. Returns complete purchase order details including items, status, history, comments, and approval information." + } + } + }, + "getPurchaseOrderApprovalRule": { + "parameters": { + "uids": { + "description": "One or more approval rule unique identifiers to retrieve. Returns approval rule configurations including conditions, approval levels, and spending limits." + } + } + }, + "placeOrderForPurchaseOrder": { + "parameters": { + "id": { + "description": "The purchase order identifier to convert into a placed order. This completes the purchase order workflow by creating an actual order in the system." + } + } + }, + "validatePurchaseOrders": { + "parameters": { + "uids": { + "description": "One or more purchase order unique identifiers to validate. Checks whether the purchase orders exist, are in a valid state, and can be processed for the requested operation." + }, + "currentPage": { + "description": "The page number for pagination (1-indexed). Used when retrieving paginated validation results." + }, + "pageSize": { + "description": "The number of validation results to return per page." + } + } + }, + "deletePurchaseOrderApprovalRule": { + "parameters": { + "uids": { + "description": "One or more approval rule unique identifiers to delete. Can be a single UID string or an array of UIDs for batch deletion. This permanently removes the approval rules from the purchase order workflow." + }, + "currentPage": { + "description": "The page number for pagination (1-indexed) in the response listing remaining approval rules after deletion." + }, + "pageSize": { + "description": "The number of approval rules to return per page in the response after deletion." + } + } + }, + "getPurchaseOrderApprovalRules": { + "parameters": { + "currentPage": { + "description": "The page number for pagination (1-indexed). Used to navigate through multiple pages of approval rules." + }, + "pageSize": { + "description": "The number of approval rules to return per page. Controls how many rules appear on each page of results." + } + } + } +} + diff --git a/_dropin-enrichments/purchase-order/initialization.json b/_dropin-enrichments/purchase-order/initialization.json new file mode 100644 index 000000000..d03ac8e5a --- /dev/null +++ b/_dropin-enrichments/purchase-order/initialization.json @@ -0,0 +1,16 @@ +{ + "intro": "The **Purchase Order initializer** configures the drop-in for managing purchase order workflows, approval rules, and order tracking. Use initialization to set the purchase order reference, customize data models, and enable internationalization for multi-language B2B storefronts.", + "config": { + "poRef": { + "description": "Purchase order reference identifier used to load and display a specific purchase order. Pass this to initialize the drop-in with purchase order details on page load." + } + }, + "customModelExample": "const models = {\n PurchaseOrderModel: {\n transformer: (data) => ({\n // Add approval status badge text\n approvalStatusDisplay: data?.status === 'PENDING' ? 'Awaiting Approval' : \n data?.status === 'APPROVED' ? 'Approved - Ready to Order' : \n data?.status,\n // Add formatted approval flow summary\n approvalSummary: data?.approvalFlow?.map(rule => \n `${rule.ruleName}: ${rule.events?.length || 0} events`\n ).join(', '),\n // Add created by full name\n createdByName: data?.createdBy ? \n `${data.createdBy.firstname} ${data.createdBy.lastname}` : null,\n }),\n },\n};\n\nawait initializers.mountImmediately(initialize, { models });", + "models": { + "PurchaseOrderModel": { + "description": "Transforms purchase order data from GraphQL including order details, approval status, items, totals, and history. Use this to add custom fields or modify existing purchase order data structures.", + "definition": "interface PurchaseOrderModel {\n typename: string;\n uid: string;\n number: string;\n status: string;\n availableActions: string[];\n approvalFlow:\n | {\n ruleName: string;\n events: Array<{\n message: string;\n name: string;\n role: string;\n status: string;\n updatedAt: string;\n }>;\n }[]\n | [];\n comments?: Array<{\n uid: string;\n createdAt: string;\n author: {\n firstname: string;\n lastname: string;\n email: string;\n };\n text: string;\n }>;\n createdAt: string;\n updatedAt: string;\n createdBy: {\n firstname: string;\n lastname: string;\n email: string;\n };\n historyLog?: Array<{\n activity: string;\n createdAt: string;\n message: string;\n uid: string;\n }>;\n quote: QuoteProps | null;\n order: {\n orderNumber: string;\n id: string;\n };\n}" + } + } +} + diff --git a/_dropin-enrichments/purchase-order/overview.json b/_dropin-enrichments/purchase-order/overview.json new file mode 100644 index 000000000..d067dc31d --- /dev/null +++ b/_dropin-enrichments/purchase-order/overview.json @@ -0,0 +1,116 @@ +{ + "introduction": "The Purchase Order B2B drop-in enables full purchase order functionality, including purchase order creation, approval rules, conditional checkout logic for placing purchase orders, the purchase order list, and the purchase order details containers.", + "supported_features": [ + { + "feature": "Purchase order creation", + "status": "Supported" + }, + { + "feature": "Purchase order approval rules", + "status": "Supported" + }, + { + "feature": "Purchase order approval workflows", + "status": "Supported" + }, + { + "feature": "Purchase order comments and history", + "status": "Supported" + }, + { + "feature": "Purchase order list views", + "status": "Supported" + }, + { + "feature": "Purchase order details view", + "status": "Supported" + }, + { + "feature": "Conditional checkout logic", + "status": "Supported" + }, + { + "feature": "Company and subordinate views", + "status": "Supported" + }, + { + "feature": "Bulk approve/reject actions", + "status": "Supported" + }, + { + "feature": "Convert purchase order to order", + "status": "Supported" + }, + { + "feature": "ACL permission-based access control", + "status": "Supported" + }, + { + "feature": "GraphQL API integration", + "status": "Supported" + } + ], + "key_events": [ + { + "name": "purchase-order/data", + "description": "Emitted by the purchase order initializer.", + "details": [ + "Requires passing a `poRef` (Purchase Order UID) to the initializer.", + "The event contains the full purchase order payload used by the purchase order details container.", + "After loading and transforming the purchase order data, it also emits an `order/data` event, which is required to initialize the following Order drop-in containers (used on the purchase order details page):", + " - **CustomerDetails**", + " - **OrderCostSummary**", + " - **OrderProductList**" + ] + }, + { + "name": "purchase-order/refresh", + "description": "Should be emitted when all purchase order containers need to refresh their data (e.g., when the company context changes)." + } + ], + "section_topics": { + "intro": "The topics in this section will help you understand how to customize and use the Purchase Order effectively within your storefront.", + "sections": [ + { + "title": "Quick Start", + "description": "Provides quick reference information and getting started guide for the Purchase Order drop-in. This topic covers package details, import paths, and basic usage examples to help you integrate Purchase Order functionality into your site.", + "link": "/dropins-b2b/purchase-order/quick-start/" + }, + { + "title": "Initialization", + "description": "Explains how to initialize the Purchase Order drop-in with configuration options including language definitions for internationalization, custom data models for type transformations, and the `poRef` parameter for loading specific purchase order details. The initializer emits key events (`purchase-order/data` and `order/data`) that are used by containers to display purchase order information.", + "link": "/dropins-b2b/purchase-order/initialization/" + }, + { + "title": "Containers", + "description": "Describes the 12 UI containers including: approval rule management (ApprovalRuleDetails, ApprovalRuleForm, ApprovalRulesList), purchase order lists (CompanyPurchaseOrders, CustomerPurchaseOrders, RequireApprovalPurchaseOrders), and purchase order details components (PurchaseOrderStatus, PurchaseOrderApprovalFlow, PurchaseOrderCommentForm, PurchaseOrderCommentsList, PurchaseOrderHistoryLog, PurchaseOrderConfirmation). Each container is optimized for specific user roles and workflows based on ACL permissions.", + "link": "/dropins-b2b/purchase-order/containers/" + }, + { + "title": "Functions", + "description": "Documents the 17 API functions for managing purchase orders including creating and placing purchase orders, managing approval rules (create, update, delete, retrieve), performing purchase order actions (approve, reject, cancel, validate), adding comments, converting purchase orders to orders, and retrieving purchase order data with filtering and pagination support.", + "link": "/dropins-b2b/purchase-order/functions/" + }, + { + "title": "Events", + "description": "Explains the events emitted during purchase order lifecycle: `purchase-order/data` (emitted by the initializer with full purchase order payload), `purchase-order/refresh` (triggers data refresh across all containers), and `purchase-order/placed` (emitted when a new purchase order is created from a cart). The `purchase-order/data` event also triggers an `order/data` event to initialize Order drop-in containers on the details page.", + "link": "/dropins-b2b/purchase-order/events/" + }, + { + "title": "Slots", + "description": "Describes the customization slots available for extending UI functionality, including the PurchaseOrderActions slot in the PurchaseOrderStatus container for customizing action buttons (approve, reject, cancel, place order) or adding additional custom actions with business logic.", + "link": "/dropins-b2b/purchase-order/slots/" + }, + { + "title": "Dictionary", + "description": "Explains the 251 internationalization keys for translating purchase order UI text including approval rule labels, purchase order status messages, form field labels, action button text, validation errors, and empty state messages. Supports full localization for multi-language B2B storefronts.", + "link": "/dropins-b2b/purchase-order/dictionary/" + }, + { + "title": "Styles", + "description": "Describes how to customize the appearance of purchase order containers including approval rule forms and lists, purchase order tables, status badges, action buttons, comment forms, history logs, and approval flow displays using CSS variables and design tokens. Covers styling for all 12 container components with detailed CSS class references.", + "link": "/dropins-b2b/purchase-order/styles/" + } + ] + } +} diff --git a/_dropin-enrichments/purchase-order/quick-start.json b/_dropin-enrichments/purchase-order/quick-start.json new file mode 100644 index 000000000..ad4fc5ed6 --- /dev/null +++ b/_dropin-enrichments/purchase-order/quick-start.json @@ -0,0 +1,4 @@ +{ + "intro": "Get started with the Purchase Order drop-in to enable purchase order approval workflows in your B2B storefront." +} + diff --git a/_dropin-enrichments/quote-management/containers.json b/_dropin-enrichments/quote-management/containers.json new file mode 100644 index 000000000..03c571aa5 --- /dev/null +++ b/_dropin-enrichments/quote-management/containers.json @@ -0,0 +1,284 @@ +{ + "ItemsQuoted": { + "description": "The ItemsQuoted container displays a summary of items that have been quoted, providing a quick overview of quoted products. It shows product information and pricing, quantity and discount details, subtotal calculations, and action buttons for quote management. The component includes responsive design for mobile and desktop viewing.", + "features": [ + "Product information and pricing display", + "Quantity and discount details", + "Subtotal calculations", + "Action buttons for quote management", + "Responsive design for mobile and desktop" + ] + }, + "ItemsQuotedTemplate": { + "description": "The ItemsQuotedTemplate container displays items stored in a quote template for reuse in future quote requests." + }, + "ManageNegotiableQuote": { + "description": "The ManageNegotiableQuote container provides comprehensive quote management capabilities for existing quotes. It displays quote details (creation date, sales rep, expiration), manages quote status and updates, shows the product list with pricing and quantity controls, provides quote actions (print, copy, delete, send for review), displays shipping information, and includes a quote comments section. All actions respect permission-based access control.", + "features": [ + "Quote details display (creation date, sales rep, expiration)", + "Quote status management and updates", + "Product list with pricing and quantity controls", + "Quote actions (print, copy, delete, send for review)", + "Shipping information display", + "Quote comments section", + "Permission-based action availability" + ], + "parameters": { + "maxFiles": { + "description": "Maximum number of files that can be attached when sending a quote for review. Use to enforce company policies on attachment limits." + }, + "maxFileSize": { + "description": "Maximum file size in bytes for attachments. Use to prevent large file uploads that could impact performance or storage." + }, + "acceptedFileTypes": { + "description": "Array of MIME types allowed for file attachments (for example ['application/pdf', 'image/jpeg', 'image/png']). Use to restrict uploads to specific document types required by your quote approval process." + } + }, + "slots": { + "QuoteName": { + "description": "Customize the quote name display and rename functionality. Use to add custom icons, styling, or additional metadata next to the quote name." + }, + "QuoteStatus": { + "description": "Customize how the quote status is displayed. Use to add custom status badges, colors, or additional status information." + }, + "Banner": { + "description": "Customize the alert banner shown for specific quote states (submitted, pending, expired). Use to provide custom messaging or styling for different quote statuses." + }, + "Details": { + "description": "Customize the quote metadata display (created date, sales rep, expiration). Use to add additional fields, reorder information, or apply custom formatting." + }, + "ActionBar": { + "description": "Customize the action buttons and dropdown menu for quote operations. Use to add custom actions, reorder existing actions, or integrate with external systems." + }, + "QuoteContent": { + "description": "Customize the entire tabbed content area containing items, comments, and history. Use to add new tabs, reorder tabs, or completely replace the tabbed interface." + }, + "ItemsQuotedTab": { + "description": "Customize the Items Quoted tab content. Use to add additional product information, custom filtering, or integrate with inventory systems." + }, + "CommentsTab": { + "description": "Customize the Comments tab displaying quote discussions. Use to add custom comment filters, sorting, or rich text formatting." + }, + "HistoryLogTab": { + "description": "Customize the History Log tab showing quote activity. Use to add custom filtering, grouping by action type, or export functionality." + }, + "ShippingInformationTitle": { + "description": "Customize the shipping section heading. Use to add icons, tooltips, or additional contextual information about shipping requirements." + }, + "ShippingInformation": { + "description": "Customize the shipping address display and selection. Use to integrate with third-party shipping services, add address validation, or provide custom address formatting." + }, + "QuoteCommentsTitle": { + "description": "Customize the quote comments section heading. Use to add help text, character limits, or formatting guidelines." + }, + "QuoteComments": { + "description": "Customize the comment input field. Use to add rich text editing, @mentions, file attachments inline, or comment templates." + }, + "AttachFilesField": { + "description": "Customize the file attachment input control. Use to integrate with document management systems, add drag-and-drop functionality, or provide custom file previews." + }, + "AttachedFilesList": { + "description": "Customize how attached files are displayed. Use to add file previews, virus scanning status, or integration with external document viewers." + }, + "Footer": { + "description": "Customize the Send for Review button and footer actions. Use to add additional submission options, validation steps, or approval workflow controls." + } + } + }, + "ManageNegotiableQuoteTemplate": { + "description": "The ManageNegotiableQuoteTemplate container provides the interface for managing quote templates with template-specific actions and details." + }, + "OrderSummary": { + "description": "The OrderSummary container displays a comprehensive pricing breakdown for quotes including subtotal calculations, applied discounts, tax information, and grand total. This component provides transparency in quote pricing.", + "features": [ + "Subtotal calculations", + "Applied discounts display", + "Tax information", + "Grand total display" + ] + }, + "OrderSummaryLine": { + "description": "The OrderSummaryLine container renders individual line items within the order summary such as subtotal, shipping, or tax rows." + }, + "QuoteCommentsList": { + "description": "The QuoteCommentsList container displays all comments and communications between buyer and seller for a negotiable quote.", + "parameters": { + "quoteData": { + "description": "The negotiable quote data object containing the comments history. Required to display the conversation thread between buyer and seller throughout the negotiation process." + } + } + }, + "QuoteHistoryLog": { + "description": "The QuoteHistoryLog container shows the complete history of actions, status changes, and updates for a quote throughout its lifecycle.", + "parameters": { + "quoteData": { + "description": "The negotiable quote data object containing the history log. Required to display the audit trail of all actions, status changes, and modifications made to the quote." + } + } + }, + "QuoteSummaryList": { + "description": "The QuoteSummaryList container displays quote metadata including quote ID, status, dates, buyer information, and shipping details.", + "parameters": { + "hideHeading": { + "description": "Use when embedding the quote summary within a layout that already provides its own heading, such as in a modal dialog, sidebar, or tabbed interface." + }, + "hideFooter": { + "description": "Use when you want to manage the footer actions yourself or when embedding the summary in a layout where the default 'View More' footer is not needed." + }, + "routeProduct": { + "description": "Provide a custom function to generate product URLs. Useful when implementing custom routing logic or when product links need query parameters or specific URL structures." + }, + "showMaxItems": { + "description": "When true (default), limits the display to 5 items initially with a 'View More' button to expand. Set to false to show all items immediately, useful for print views or detailed quote pages." + }, + "attributesToHide": { + "description": "Array of attribute names to hide from the item display. Use to create simplified views for specific contexts, such as hiding SKU and price for mobile layouts or hiding quantity for summary views. Available attributes: name, image, configurations, warning, alert, sku, price, quantity, total, totalDiscount, totalExcludingTax." + }, + "accordion": { + "description": "When true, renders the quote items in a collapsible accordion. Useful for mobile layouts, multi-quote comparison pages, or dashboards where multiple quote summaries are displayed and space is limited." + }, + "variant": { + "description": "Controls the background styling. Use 'primary' for standard pages and 'secondary' for alternate contexts like sidebars or embedded widgets." + }, + "showDiscount": { + "description": "When true, displays the discount percentage next to discounted items. Useful for highlighting negotiated savings to buyers and providing transparency in pricing." + }, + "showSavings": { + "description": "When true, displays the total savings amount for discounted items. Complements showDiscount by showing the dollar value of savings, helping buyers understand the value of the quote." + } + }, + "slots": { + "Heading": { + "description": "Customize the heading displaying the item count. Receives the total quantity and quote ID. Use to add custom branding, icons, or additional quote metadata in the header." + }, + "Footer": { + "description": "Customize the footer section below individual quote items. Receives the item data. Use to add custom actions like add to cart, remove, or item-specific notes for each line item." + }, + "Thumbnail": { + "description": "Customize the product image display for each item. Receives the item and default image props. Use to add image overlays, badges for discounted items, or custom image loading behavior." + }, + "ProductAttributes": { + "description": "Customize how product attributes (size, color) are displayed for each item. Receives the item data. Use to add custom formatting, grouping, or additional attribute information." + }, + "QuoteSummaryFooter": { + "description": "Customize the View More button and footer actions for the entire quote list. Receives the display state. Use to add additional actions like export to PDF or email quote." + }, + "QuoteItem": { + "description": "Customize the entire quote item row. Receives comprehensive item data and formatting functions. Use for complete control over item rendering, such as custom layouts for mobile versus desktop." + }, + "ItemTitle": { + "description": "Customize the product title display for each item. Receives the item data. Use to add product badges, custom linking, or additional product information inline with the title." + }, + "ItemPrice": { + "description": "Customize the unit price display for each item. Receives the item data. Use to add price comparison, original pricing with strikethrough, or custom currency formatting." + }, + "ItemTotal": { + "description": "Customize the line total display for each item. Receives the item data. Use to add savings calculations, tax breakdowns, or custom total formatting with discounts highlighted." + }, + "ItemSku": { + "description": "Customize the SKU display for each item. Receives the item data. Use to add copy-to-clipboard functionality, links to product pages, or custom SKU formatting." + } + } + }, + "QuoteTemplateCommentsList": { + "description": "The QuoteTemplateCommentsList container displays all comments associated with a quote template.", + "parameters": { + "quoteData": { + "description": "The quote template data object containing the comments history. Required to display discussions and notes related to the template that can be reused across multiple quote requests." + } + } + }, + "QuoteTemplateHistoryLog": { + "description": "The QuoteTemplateHistoryLog container shows the complete history of changes and updates for a quote template.", + "parameters": { + "quoteData": { + "description": "The quote template data object containing the history log. Required to track when the template was created, modified, used, or archived for audit and governance purposes." + } + } + }, + "QuoteTemplatesListTable": { + "description": "The QuoteTemplatesListTable container displays all quote templates in a paginated table with search, filter, and action capabilities." + }, + "QuotesListTable": { + "description": "The QuotesListTable container displays a comprehensive list of quotes with advanced filtering, sorting, and management capabilities. It includes quote list display with status indicators, pagination and sorting controls, search and filtering options, bulk actions for multiple quotes, quote selection and navigation, and responsive table design.", + "features": [ + "Quote list display with status indicators", + "Pagination and sorting controls", + "Search and filtering options", + "Bulk actions for multiple quotes", + "Quote selection and navigation", + "Responsive table design" + ] + }, + "RequestNegotiableQuoteForm": { + "description": "The RequestNegotiableQuoteForm container enables customers to request new negotiable quotes from their cart contents. This component handles quote name and comment input, draft saving functionality, form validation and error handling, and success/error messaging. It includes support for file attachments and integrates with cart contents.", + "features": [ + "Quote name and comment input fields", + "Form validation with error handling", + "Draft saving functionality", + "Success/error messaging", + "Integration with cart contents", + "Authentication checks" + ], + "parameters": { + "cartId": { + "description": "The unique identifier for the shopping cart to convert into a quote. Required to associate the quote request with specific cart items and pricing." + }, + "maxFiles": { + "description": "Maximum number of files that can be attached to the quote request. Use to enforce company policies on attachment limits or prevent excessive file uploads." + }, + "maxFileSize": { + "description": "Maximum file size in bytes for each attachment. Use to prevent large file uploads that could impact performance or storage costs." + }, + "acceptedFileTypes": { + "description": "Array of MIME types allowed for file attachments (for example ['application/pdf', 'image/jpeg']). Use to restrict uploads to specific document types required by your quote workflow." + } + }, + "slots": { + "ErrorBanner": { + "description": "Customize the error message display when quote submission fails. Receives the error message. Use to add custom error tracking, retry mechanisms, or support contact information." + }, + "SuccessBanner": { + "description": "Customize the success message display after quote submission. Receives the success message. Use to add next steps, links to the quote details page, or custom celebration animations." + }, + "Title": { + "description": "Customize the form heading. Receives the title text. Use to add custom branding, help icons, or contextual information about the quote process." + }, + "CommentField": { + "description": "Customize the comment input field. Receives form state and error handlers. Use to add character counters, rich text editing, comment templates, or AI-assisted comment generation." + }, + "QuoteNameField": { + "description": "Customize the quote name input field. Receives form state and error handlers. Use to add auto-naming logic based on cart contents, validation rules, or naming conventions specific to your organization." + }, + "AttachFileField": { + "description": "Customize the file attachment input control. Receives upload handler and form state. Use to add drag-and-drop functionality, file previews, or integration with document management systems." + }, + "AttachedFilesList": { + "description": "Customize how attached files are displayed. Receives the file list and removal handler. Use to add file previews, virus scanning status, download links, or file metadata display." + }, + "RequestButton": { + "description": "Customize the primary submit button for requesting a quote. Receives the submission handler and form state. Use to add confirmation dialogs, custom loading states, or multi-step submission workflows." + }, + "SaveDraftButton": { + "description": "Customize the draft save button for saving incomplete quote requests. Receives the save handler and form state. Use to add auto-save functionality, draft naming conventions, or draft management interfaces." + } + } + }, + "ShippingAddressDisplay": { + "description": "The ShippingAddressDisplay container shows the selected shipping address for a quote with options to change or add new addresses. This component integrates with the company address book for B2B customers." + }, + "integration": { + "description": "These containers are designed to work together to provide a complete quote management experience. Use RequestNegotiableQuoteForm on cart pages or product pages to initiate quote requests, ManageNegotiableQuote on dedicated quote management pages for comprehensive quote handling, ItemsQuoted on quote summary pages or as a sidebar component, and QuotesListTable on quotes listing pages for browsing and managing multiple quotes." + }, + "customization": { + "description": "Each container can be customized through configuration props passed to the container, slots for content areas that can be customized with your own components, events as callback functions for handling user interactions, and styles through CSS customization for visual appearance." + }, + "best_practices": [ + "Use RequestNegotiableQuoteForm on cart pages to enable easy quote requests", + "Implement ManageNegotiableQuote on dedicated quote management pages", + "Use ItemsQuoted as a summary component in quote lists or sidebars", + "Handle errors gracefully with appropriate callback functions", + "Ensure proper authentication checks before rendering containers", + "Test all quote workflows thoroughly in your B2B environment" + ] +} diff --git a/_dropin-enrichments/quote-management/events.json b/_dropin-enrichments/quote-management/events.json new file mode 100644 index 000000000..3b00e72f1 --- /dev/null +++ b/_dropin-enrichments/quote-management/events.json @@ -0,0 +1,232 @@ +{ + "overview": "The **Quote Management** drop-in uses the [event bus](/sdk/reference/events) to emit and listen to events for communication between drop-ins and external integrations. These events enable real-time updates for quote lifecycle operations, including quote creation, negotiation, approval workflows, and status changes.", + "quote-management/initialized": { + "whenTriggered": [ + "After `initialize()` function completes", + "On drop-in first load" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\n\nevents.on('quote-management/initialized', () => {\n console.log('Quote Management ready');\n loadQuotesList();\n});\n```\n\n---" + } + ] + }, + "quote-management/line-item-note-set": { + "whenTriggered": [ + "After calling `setLineItemNote()`", + "When merchant or buyer adds/updates item notes" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nevents.on('quote-management/line-item-note-set', (payload) => {\n console.log(`Note set on item ${payload.data.itemId}:`, payload.data.note);\n refreshQuoteItemsList();\n});\n```\n\n---" + } + ] + }, + "quote-management/negotiable-quote-closed": { + "whenTriggered": [ + "After calling `closeNegotiableQuote()`", + "When quote reaches final state" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nevents.on('quote-management/negotiable-quote-closed', (payload) => {\n console.log(`Quote ${payload.data.quoteId} closed`);\n redirectToQuotesList();\n});\n```\n\n---" + } + ] + }, + "quote-management/negotiable-quote-deleted": { + "whenTriggered": [ + "After calling `deleteQuote()`", + "After successful quote deletion" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nevents.on('quote-management/negotiable-quote-deleted', (payload) => {\n console.log(`Quote ${payload.data.quoteId} deleted`);\n removeQuoteFromList(payload.data.quoteId);\n});\n```\n\n---" + } + ] + }, + "quote-management/negotiable-quote-requested": { + "whenTriggered": [ + "After calling `requestNegotiableQuote()`", + "When buyer submits quote request" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nevents.on('quote-management/negotiable-quote-requested', (payload) => {\n console.log(`Quote ${payload.data.quoteName} requested`);\n showSuccessMessage('Quote request submitted');\n redirectToQuoteDetails(payload.data.quoteId);\n});\n```\n\n---" + } + ] + }, + "quote-management/permissions": { + "whenTriggered": [ + "After permission changes", + "On user role updates", + "After company context switches" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nevents.on('quote-management/permissions', (payload) => {\n const canRequestQuote = payload.data.permissions.includes('request_quote');\n updateQuoteActions(canRequestQuote);\n});\n```\n\n---" + } + ] + }, + "quote-management/quantities-updated": { + "whenTriggered": [ + "After calling `updateQuantities()`", + "When buyer or merchant updates quantities" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nevents.on('quote-management/quantities-updated', (payload) => {\n console.log(`Quantities updated for quote ${payload.data.quoteId}`);\n refreshQuoteTotals();\n});\n```\n\n---" + } + ] + }, + "quote-management/quote-data": { + "whenTriggered": [ + "After loading quote details", + "After any quote modification", + "After status changes" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nevents.on('quote-management/quote-data', (payload) => {\n console.log('Quote data updated:', payload.data);\n updateQuoteDisplay(payload.data);\n});\n```\n\n---" + } + ] + }, + "quote-management/quote-data/initialized": { + "whenTriggered": [ + "On first load of quote details", + "After quote context is established" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nevents.on('quote-management/quote-data/initialized', (payload) => {\n console.log('Quote initialized:', payload.data.number);\n setupQuoteWorkflow(payload.data);\n});\n```\n\n---" + } + ] + }, + "quote-management/quote-duplicated": { + "whenTriggered": [ + "After calling `duplicateQuote()`", + "When creating copy of existing quote" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nevents.on('quote-management/quote-duplicated', (payload) => {\n console.log(`Quote duplicated: ${payload.data.originalQuoteId} -> ${payload.data.newQuoteId}`);\n redirectToQuote(payload.data.newQuoteId);\n});\n```\n\n---" + } + ] + }, + "quote-management/quote-items-removed": { + "whenTriggered": [ + "After calling `removeNegotiableQuoteItems()`", + "When items are deleted from quote" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nevents.on('quote-management/quote-items-removed', (payload) => {\n console.log(`Removed ${payload.data.removedItemIds.length} items`);\n refreshQuoteItemsList();\n});\n```\n\n---" + } + ] + }, + "quote-management/quote-renamed": { + "whenTriggered": [ + "After calling `renameNegotiableQuote()`", + "When quote name is updated" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nevents.on('quote-management/quote-renamed', (payload) => {\n console.log(`Quote renamed to: ${payload.data.newName}`);\n updateQuoteHeader(payload.data.newName);\n});\n```\n\n---" + } + ] + }, + "quote-management/quote-sent-for-review": { + "whenTriggered": [ + "After calling `sendForReview()`", + "When buyer submits quote for negotiation" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nevents.on('quote-management/quote-sent-for-review', (payload) => {\n console.log(`Quote ${payload.data.quoteId} sent for review`);\n showSuccessMessage('Quote submitted for merchant review');\n updateQuoteStatus('pending');\n});\n```\n\n---" + } + ] + }, + "quote-management/quote-template-data": { + "whenTriggered": [ + "After loading template details", + "After template modifications", + "After template status changes" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nevents.on('quote-management/quote-template-data', (payload) => {\n console.log('Template data updated:', payload.data);\n updateTemplateDisplay(payload.data);\n});\n```\n\n---" + } + ] + }, + "quote-management/quote-template-deleted": { + "whenTriggered": [ + "After calling `deleteQuoteTemplate()`", + "After successful template deletion" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nevents.on('quote-management/quote-template-deleted', (payload) => {\n console.log(`Template ${payload.data.templateId} deleted`);\n removeTemplateFromList(payload.data.templateId);\n});\n```\n\n---" + } + ] + }, + "quote-management/quote-template-generated": { + "whenTriggered": [ + "After calling `generateQuoteFromTemplate()`", + "When creating quote from template" + ], + "examples": [ + { + "title": "Basic template generation", + "code": "```js\nevents.on('quote-management/quote-template-generated', (payload) => {\n console.log(`Quote ${payload.data.quoteId} generated from template ${payload.data.templateId}`);\n redirectToQuote(payload.data.quoteId);\n});\n```" + }, + { + "title": "Template catalog with quick-quote generation", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\nimport { generateQuoteFromTemplate, getQuoteTemplates } from '@dropins/storefront-quote-management/api.js';\n\nclass QuoteTemplateCatalog {\n constructor(containerElement) {\n this.container = containerElement;\n this.templates = [];\n \n // Listen for template generation\n events.on('quote-management/quote-template-generated', this.handleQuoteGenerated.bind(this));\n \n this.init();\n }\n \n async init() {\n try {\n // Load all available templates\n const response = await getQuoteTemplates({\n currentPage: 1,\n pageSize: 50,\n sort: { field: 'name', direction: 'ASC' }\n });\n \n this.templates = response.items;\n this.render();\n \n } catch (error) {\n this.showError('Failed to load quote templates');\n console.error(error);\n }\n }\n \n render() {\n this.container.innerHTML = `\n
\n

Quote Templates

\n
\n ${this.templates.map(template => this.renderTemplateCard(template)).join('')}\n
\n
\n `;\n \n // Attach event listeners\n this.container.querySelectorAll('.generate-quote-btn').forEach(btn => {\n btn.addEventListener('click', (e) => {\n const templateUid = e.target.dataset.templateUid;\n this.generateQuote(templateUid);\n });\n });\n }\n \n renderTemplateCard(template) {\n return `\n
\n
\n

${template.name}

\n ${template.items.length} items\n
\n
\n Total: $${template.prices.grandTotal.value}\n Created: ${formatDate(template.createdAt)}\n
\n
\n \n \n
\n
\n `;\n }\n \n async generateQuote(templateUid) {\n const template = this.templates.find(t => t.uid === templateUid);\n if (!template) return;\n \n try {\n // Show loading state\n this.showLoadingOverlay(`Generating quote from \"${template.name}\"...`);\n \n // Generate quote from template\n await generateQuoteFromTemplate(templateUid);\n \n // Event handler will redirect when complete\n \n } catch (error) {\n this.hideLoadingOverlay();\n this.showError('Failed to generate quote: ' + error.message);\n console.error(error);\n }\n }\n \n handleQuoteGenerated(payload) {\n const { templateId, quoteId } = payload.data;\n \n this.hideLoadingOverlay();\n \n // Get template name for notification\n const template = this.templates.find(t => t.uid === templateId);\n const templateName = template ? template.name : 'template';\n \n // Show success notification\n this.showSuccess(`Quote generated from \"${templateName}\"`);\n \n // Track analytics\n trackAnalytics('quote_generated_from_template', {\n templateId,\n quoteId,\n templateName\n });\n \n // Redirect to the new quote for editing\n setTimeout(() => {\n window.location.href = `/quotes/${quoteId}`;\n }, 1500);\n }\n \n showLoadingOverlay(message) {\n const overlay = document.createElement('div');\n overlay.id = 'loading-overlay';\n overlay.innerHTML = `\n
\n
${message}
\n `;\n document.body.appendChild(overlay);\n }\n \n hideLoadingOverlay() {\n const overlay = document.getElementById('loading-overlay');\n if (overlay) overlay.remove();\n }\n \n showSuccess(message) {\n this.showToast(message, 'success');\n }\n \n showError(message) {\n this.showToast(message, 'error');\n }\n \n showToast(message, type) {\n const toast = document.createElement('div');\n toast.className = `toast toast-${type}`;\n toast.textContent = message;\n document.body.appendChild(toast);\n setTimeout(() => toast.remove(), 3000);\n }\n}\n\n// Initialize template catalog\nconst catalog = new QuoteTemplateCatalog(document.querySelector('#template-catalog'));\n```" + }, + { + "title": "Recurring order workflow using templates", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\nimport { generateQuoteFromTemplate, submitNegotiableQuote } from '@dropins/storefront-quote-management/api.js';\n\n/**\n * Automated recurring order system using quote templates\n * Useful for customers who regularly order the same items\n */\nclass RecurringOrderManager {\n constructor() {\n this.activeOrders = [];\n \n events.on('quote-management/quote-template-generated', this.handleGeneration.bind(this));\n events.on('quote-management/quote-sent-for-review', this.handleSubmission.bind(this));\n }\n \n /**\n * Set up a recurring order schedule\n */\n async scheduleRecurringOrder(templateUid, schedule) {\n const recurringOrder = {\n templateUid,\n schedule, // e.g., { frequency: 'monthly', dayOfMonth: 1 }\n status: 'active',\n lastGenerated: null,\n nextGeneration: this.calculateNextDate(schedule)\n };\n \n // Save to user preferences\n await this.saveRecurringOrder(recurringOrder);\n \n // Set up next execution\n this.scheduleNextGeneration(recurringOrder);\n \n return recurringOrder;\n }\n \n /**\n * Generate quote from template on schedule\n */\n async generateScheduledQuote(templateUid, autoSubmit = true) {\n try {\n console.log(`Generating scheduled quote from template ${templateUid}`);\n \n // Generate the quote\n await generateQuoteFromTemplate(templateUid);\n \n // Store auto-submit preference\n if (autoSubmit) {\n this.pendingAutoSubmits.add(templateUid);\n }\n \n } catch (error) {\n console.error('Failed to generate scheduled quote:', error);\n \n // Notify user of failure\n this.notifyGenerationFailure(templateUid, error);\n }\n }\n \n /**\n * Handle successful quote generation\n */\n async handleGeneration(payload) {\n const { templateId, quoteId } = payload.data;\n \n console.log(`Quote ${quoteId} generated from template ${templateId}`);\n \n // Check if this was an automated generation\n if (this.pendingAutoSubmits.has(templateId)) {\n // Automatically submit for review\n try {\n await submitNegotiableQuote(quoteId);\n console.log(`Auto-submitted quote ${quoteId} for review`);\n \n this.pendingAutoSubmits.delete(templateId);\n \n } catch (error) {\n console.error('Failed to auto-submit quote:', error);\n \n // Notify user to manually submit\n this.notifyManualSubmissionNeeded(quoteId);\n }\n }\n \n // Update recurring order record\n await this.updateRecurringOrderHistory(templateId, quoteId);\n }\n \n /**\n * Handle quote submission\n */\n handleSubmission(payload) {\n const { quoteId } = payload.data;\n \n // Send confirmation email\n this.sendSubmissionConfirmation(quoteId);\n \n // Update dashboard\n this.updateDashboard();\n }\n \n calculateNextDate(schedule) {\n const now = new Date();\n switch (schedule.frequency) {\n case 'weekly':\n return new Date(now.setDate(now.getDate() + 7));\n case 'monthly':\n return new Date(now.setMonth(now.getMonth() + 1, schedule.dayOfMonth));\n case 'quarterly':\n return new Date(now.setMonth(now.getMonth() + 3, schedule.dayOfMonth));\n default:\n return null;\n }\n }\n \n scheduleNextGeneration(recurringOrder) {\n const delay = recurringOrder.nextGeneration - new Date();\n setTimeout(() => {\n this.generateScheduledQuote(recurringOrder.templateUid, true);\n }, delay);\n }\n \n // Helper methods\n pendingAutoSubmits = new Set();\n \n async saveRecurringOrder(order) { /* Save to backend */ }\n async updateRecurringOrderHistory(templateId, quoteId) { /* Update history */ }\n notifyGenerationFailure(templateId, error) { /* Send notification */ }\n notifyManualSubmissionNeeded(quoteId) { /* Send notification */ }\n sendSubmissionConfirmation(quoteId) { /* Send email */ }\n updateDashboard() { /* Refresh UI */ }\n}\n\n// Initialize recurring order system\nconst recurringOrders = new RecurringOrderManager();\n\n// Example: Set up monthly recurring order\nrecurringOrders.scheduleRecurringOrder('template-uid-123', {\n frequency: 'monthly',\n dayOfMonth: 1\n});\n```" + } + ], + "usageScenarios": "- One-click quote generation from commonly used templates.\n- Streamline repeat ordering workflows for regular customers.\n- Implement recurring order systems based on templates.\n- Quick quote creation for standard product bundles.\n- Template-based ordering for seasonal or periodic purchases.\n- Automated quote generation for subscription-like B2B orders.\n\n---" + }, + "quote-management/quote-templates-data": { + "whenTriggered": [ + "After loading templates list", + "After template creation/deletion", + "After template status changes" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nevents.on('quote-management/quote-templates-data', (payload) => {\n console.log(`${payload.data.totalCount} templates loaded`);\n updateTemplatesList(payload.data.templates);\n});\n```\n\n---" + } + ] + }, + "quote-management/shipping-address-set": { + "whenTriggered": [ + "After calling `setShippingAddress()`", + "When shipping address is updated" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nevents.on('quote-management/shipping-address-set', (payload) => {\n console.log('Shipping address set:', payload.data.address);\n refreshShippingMethods();\n recalculateQuoteTotals();\n});\n```\n\n---\n\n## Listening to events\n\nAll Quote Management events are emitted through the centralized event bus:\n\n```js\nimport { events } from '@dropins/tools/event-bus.js';\n\n// Listen to quote lifecycle events\nevents.on('quote-management/negotiable-quote-requested', handleQuoteRequest);\nevents.on('quote-management/quote-sent-for-review', handleQuoteReview);\nevents.on('quote-management/quote-duplicated', handleQuoteDuplicate);\n\n// Listen to quote data changes\nevents.on('quote-management/quote-data', handleQuoteUpdate);\nevents.on('quote-management/quantities-updated', handleQuantityChange);\n\n// Listen to template events\nevents.on('quote-management/quote-template-generated', handleTemplateGeneration);\nevents.on('quote-management/quote-templates-data', handleTemplatesLoad);\n\n// Clean up listeners\nevents.off('quote-management/quote-data', handleQuoteUpdate);\n```\n\n\n\n\n\n## Event flow examples" + } + ] + } +} diff --git a/_dropin-enrichments/quote-management/functions.json b/_dropin-enrichments/quote-management/functions.json new file mode 100644 index 000000000..1182aa3a1 --- /dev/null +++ b/_dropin-enrichments/quote-management/functions.json @@ -0,0 +1,186 @@ +{ + "overview": "The Quote Management drop-in provides **17 API functions** for managing negotiable quotes and quote templates, including creating quotes, adding items, managing shipping addresses, and processing quote workflows.", + "data_models": { + "description": "The quote management drop-in uses several TypeScript interfaces to define data structures:", + "models": [ + { + "name": "NegotiableQuoteModel", + "description": "Represents a negotiable quote with all its properties and relationships.", + "code": "```typescript\ninterface NegotiableQuoteModel {\n uid: string;\n name: string;\n createdAt: string;\n salesRepName: string;\n expirationDate: string;\n updatedAt: string;\n status: NegotiableQuoteStatus;\n buyer: {\n firstname: string;\n lastname: string;\n };\n templateName?: string;\n comments?: QuoteComment[];\n prices: QuotePrices;\n items: NegotiableQuoteCartItem[];\n canCheckout: boolean;\n canSendForReview: boolean;\n}\n```" + }, + { + "name": "NegotiableQuoteStatus", + "description": "Enumeration of possible quote statuses.", + "code": "```typescript\nenum NegotiableQuoteStatus {\n SUBMITTED = 'SUBMITTED',\n PENDING = 'PENDING',\n UPDATED = 'UPDATED',\n OPEN = 'OPEN',\n ORDERED = 'ORDERED',\n CLOSED = 'CLOSED',\n DECLINED = 'DECLINED',\n EXPIRED = 'EXPIRED',\n DRAFT = 'DRAFT',\n}\n```" + }, + { + "name": "CustomerModel", + "description": "Represents customer data and permissions.", + "code": "```typescript\ninterface CustomerModel {\n permissions: CustomerPermissions;\n}\n\ninterface CustomerPermissions {\n canRequestQuote: boolean;\n canEditQuote: boolean;\n canDeleteQuote: boolean;\n canCheckoutQuote: boolean;\n}\n```" + } + ] + }, + "acceptQuoteTemplate": { + "parameters": { + "params": { + "description": "An object of type `AcceptQuoteTemplateParams` containing the template UID and acceptance details. See the type definition for available fields." + } + } + }, + "addQuoteTemplateLineItemNote": { + "parameters": { + "params": { + "description": "An object of type `AddQuoteTemplateLineItemNoteParams` containing the template UID, item UID, and note text to add to a specific line item." + } + } + }, + "addQuoteTemplateShippingAddress": { + "parameters": { + "params": { + "description": "An object of type `AddQuoteTemplateShippingAddressParams` containing the template UID and shipping address details (street, city, region, postal code, country)." + } + } + }, + "cancelQuoteTemplate": { + "parameters": { + "params": { + "description": "An object of type `CancelQuoteTemplateParams` containing the template UID to cancel. This moves the quote template to canceled status." + } + } + }, + "closeNegotiableQuotes": { + "parameters": { + "quoteId": { + "description": "The unique identifier for the negotiable quote to close. This finalizes the quote and prevents further modifications or negotiations." + } + } + }, + "deleteNegotiableQuotes": { + "parameters": { + "quoteUids": { + "description": "One or more negotiable quote unique identifiers to delete. Can be a single UID string or an array of UIDs for batch deletion." + } + } + }, + "deleteQuoteTemplate": { + "parameters": { + "params": { + "description": "An object of type `DeleteQuoteTemplateParams` containing the template UID to delete. This permanently removes the quote template." + } + } + }, + "generateCartFromNegotiableQuote": { + "description": "Converts a negotiable quote into an active shopping cart, allowing the customer to proceed to checkout with the quoted items and pricing. This is typically used after a quote has been approved by both parties.", + "returns": "Returns a Promise that resolves to a cart ID string representing the newly created cart." + }, + "generateQuoteFromTemplate": { + "parameters": { + "params": { + "description": "An object of type `GenerateQuoteFromTemplateParams` containing the template UID and any customization parameters. Creates a new negotiable quote based on the template structure." + } + } + }, + "getNegotiableQuote": { + "parameters": { + "quoteId": { + "description": "The unique identifier for the negotiable quote to retrieve. Returns complete quote details including items, prices, history, comments, and negotiation status." + } + } + }, + "getQuoteTemplate": { + "parameters": { + "templateId": { + "description": "The unique identifier for the quote template to retrieve. Returns template details including structure, items, and configuration." + } + } + }, + "getQuoteTemplates": { + "parameters": { + "params": { + "description": "An optional object of type `GetQuoteTemplatesParams` containing pagination and filter criteria (currentPage, pageSize, filter). Omit to retrieve all templates with default pagination." + } + } + }, + "negotiableQuotes": { + "parameters": { + "params": { + "description": "An optional object of type `NegotiableQuotesParams` containing pagination and filter criteria (currentPage, pageSize, filter). Omit to retrieve all negotiable quotes with default pagination." + } + } + }, + "openQuoteTemplate": { + "parameters": { + "params": { + "description": "An object of type `OpenQuoteTemplateParams` containing the template UID to open or activate. This makes the template available for generating quotes." + } + } + }, + "removeQuoteTemplateItems": { + "parameters": { + "params": { + "description": "An object of type `RemoveQuoteTemplateItemsParams` containing the template UID and an array of item UIDs to remove from the template." + } + } + }, + "requestNegotiableQuote": { + "description": "Creates a new negotiable quote request from the current cart. This initiates the quote negotiation workflow, converting cart items into a quote that can be reviewed and negotiated by the seller.", + "returns": "Returns a Promise that resolves to a `NegotiableQuoteModel` object containing the new quote details." + }, + "sendQuoteTemplateForReview": { + "parameters": { + "params": { + "description": "An object of type `SendQuoteTemplateForReviewParams` containing the template UID and optional review notes. Submits the template for review by the seller or approver." + } + } + }, + "updateQuoteTemplateItemQuantities": { + "parameters": { + "params": { + "description": "An object of type `UpdateQuoteTemplateItemQuantitiesParams` containing the template UID and an array of item quantity updates (item UID and new quantity for each item)." + } + } + }, + "uploadFileToQuote": { + "parameters": { + "file": { + "description": "The File object to upload and attach to the quote. This can be a specification document, purchase order, or any supporting file that provides context for the quote request." + } + } + }, + "createQuoteTemplate": { + "parameters": { + "quoteId": { + "description": "The unique identifier for the negotiable quote to convert into a reusable template. Creates a template that can be used to generate similar quotes in the future." + } + } + }, + "deleteQuote": { + "parameters": { + "quoteUids": { + "description": "One or more negotiable quote unique identifiers to delete. Can be a single UID string or an array of UIDs for batch deletion. This permanently removes the quotes." + } + } + }, + "getQuoteData": { + "parameters": { + "quoteId": { + "description": "The unique identifier for the negotiable quote to retrieve. Returns complete quote details including items, prices, history, comments, and negotiation status." + } + } + }, + "getQuoteTemplateData": { + "parameters": { + "templateId": { + "description": "The unique identifier for the quote template to retrieve. Returns template details including structure, items, and configuration settings." + } + } + }, + "uploadFile": { + "parameters": { + "file": { + "description": "The File object to upload and attach to a quote. Supports specification documents, purchase orders, or any supporting files that provide context for quote requests." + } + } + } +} + diff --git a/_dropin-enrichments/quote-management/initialization.json b/_dropin-enrichments/quote-management/initialization.json new file mode 100644 index 000000000..9503f2b9c --- /dev/null +++ b/_dropin-enrichments/quote-management/initialization.json @@ -0,0 +1,19 @@ +{ + "intro": "The **Quote Management initializer** configures the drop-in for managing negotiable quotes, quote templates, and quote workflows. Use initialization to set quote identifiers, customize data models, and enable internationalization for multi-language B2B storefronts.", + "config": { + "quoteId": { + "description": "Quote identifier used to load and display a specific negotiable quote. Pass this to initialize the drop-in with quote details on page load." + }, + "quoteTemplateId": { + "description": "Quote template identifier used to load and display a specific quote template. Pass this to initialize the drop-in with template details on page load." + } + }, + "customModelExample": "const models = {\n NegotiableQuoteModel: {\n transformer: (data) => ({\n // Add urgency badge for expiring quotes (within 7 days)\n isExpiringSoon: data?.expirationDate && \n new Date(data.expirationDate) - Date.now() < 7 * 24 * 60 * 60 * 1000,\n // Custom status display for better UX\n statusDisplay: data?.status === 'SUBMITTED' ? 'Pending Review' : data?.status,\n // Add formatted expiration date\n expirationFormatted: data?.expirationDate ? \n new Date(data.expirationDate).toLocaleDateString() : null,\n }),\n },\n};\n\nawait initializers.mountImmediately(initialize, { models });", + "models": { + "NegotiableQuoteModel": { + "description": "Transforms negotiable quote data from GraphQL including quote details, status, items, totals, comments, and history. Use this to add custom fields or modify existing quote data structures.", + "definition": "interface NegotiableQuoteModel {\n uid: string;\n name: string;\n createdAt: string;\n salesRepName: string;\n expirationDate: string;\n updatedAt: string;\n status: NegotiableQuoteStatus;\n isVirtual: boolean;\n buyer: {\n firstname: string;\n lastname: string;\n };\n templateName?: string;\n totalQuantity: number;\n comments?: {\n uid: string;\n createdAt: string;\n author: {\n firstname: string;\n lastname: string;\n };\n text: string;\n attachments?: {\n name: string;\n url: string;\n }[];\n }[];\n history?: NegotiableQuoteHistoryEntry[];\n prices: {\n appliedDiscounts?: Discount[];\n appliedTaxes?: Tax[];\n discount?: Currency;\n grandTotal?: Currency;\n grandTotalExcludingTax?: Currency;\n shippingExcludingTax?: Currency;\n shippingIncludingTax?: Currency;\n subtotalExcludingTax?: Currency;\n subtotalIncludingTax?: Currency;\n subtotalWithDiscountExcludingTax?: Currency;\n totalTax?: Currency;\n };\n items: NegotiableQuoteCartItem[];\n shippingAddresses?: ShippingAddress[];\n canCheckout: boolean;\n canSendForReview: boolean;\n lockedForEditing?: boolean;\n canDelete: boolean;\n canClose: boolean;\n canUpdateQuote: boolean;\n readOnly: boolean;\n}" + } + } +} + diff --git a/_dropin-enrichments/quote-management/overview.json b/_dropin-enrichments/quote-management/overview.json new file mode 100644 index 000000000..be2e25cc5 --- /dev/null +++ b/_dropin-enrichments/quote-management/overview.json @@ -0,0 +1,106 @@ +{ + "introduction": "The Quote Management drop-in enables requesting negotiable quotes and quote management and tracking for Adobe Commerce storefronts. It also supports quote status updates and quote comments and attachments.", + "supported_features": [ + { + "feature": "Negotiable quotes", + "status": "Supported" + }, + { + "feature": "Quote requests with file attachments", + "status": "Supported" + }, + { + "feature": "Quote lifecycle management", + "status": "Supported" + }, + { + "feature": "Quote comments and history tracking", + "status": "Supported" + }, + { + "feature": "Quote templates for repeat ordering", + "status": "Supported" + }, + { + "feature": "Quote item management", + "status": "Supported" + }, + { + "feature": "Quote status tracking", + "status": "Supported" + }, + { + "feature": "Shipping address selection", + "status": "Supported" + }, + { + "feature": "Quote duplication", + "status": "Supported" + }, + { + "feature": "Convert quotes to orders", + "status": "Supported" + }, + { + "feature": "Quote list views with filtering", + "status": "Supported" + }, + { + "feature": "Customer authentication required", + "status": "Supported" + }, + { + "feature": "Multi-language support", + "status": "Supported" + }, + { + "feature": "GraphQL API integration", + "status": "Supported" + } + ], + "section_topics": { + "intro": "The topics in this section will help you understand how to customize and use the Quote Management effectively within your storefront.", + "sections": [ + { + "title": "Quick Start", + "description": "Provides quick reference information and getting started guide for the Quote Management drop-in. This topic covers package details, import paths, and basic usage examples to help you integrate Quote Management functionality into your site.", + "link": "/dropins-b2b/quote-management/quick-start/" + }, + { + "title": "Initialization", + "description": "**[Drop-in developer]:** Add 1-2 sentences describing what configuration options are available and what needs to be set up before using this drop-in.", + "link": "/dropins-b2b/quote-management/initialization/" + }, + { + "title": "Containers", + "description": "**[Drop-in developer]:** Add 1-2 sentences listing the main UI containers and what they're used for.", + "link": "/dropins-b2b/quote-management/containers/" + }, + { + "title": "Functions", + "description": "**[Drop-in developer]:** Add 1-2 sentences describing the main API functions and what operations they enable.", + "link": "/dropins-b2b/quote-management/functions/" + }, + { + "title": "Events", + "description": "**[Drop-in developer]:** Add 1-2 sentences describing what events are emitted and when they trigger.", + "link": "/dropins-b2b/quote-management/events/" + }, + { + "title": "Slots", + "description": "**[Drop-in developer]:** Add 1-2 sentences describing what parts of the UI can be customized with slots.", + "link": "/dropins-b2b/quote-management/slots/" + }, + { + "title": "Dictionary", + "description": "**[Drop-in developer]:** Add 1-2 sentences describing the i18n keys and what they're used for.", + "link": "/dropins-b2b/quote-management/dictionary/" + }, + { + "title": "Styles", + "description": "**[Drop-in developer]:** Add 1-2 sentences describing what visual elements can be styled.", + "link": "/dropins-b2b/quote-management/styles/" + } + ] + } +} diff --git a/_dropin-enrichments/quote-management/quick-start.json b/_dropin-enrichments/quote-management/quick-start.json new file mode 100644 index 000000000..ff8125d3d --- /dev/null +++ b/_dropin-enrichments/quote-management/quick-start.json @@ -0,0 +1,4 @@ +{ + "intro": "Get started with the Quote Management drop-in to enable B2B quote negotiation and management in your storefront." +} + diff --git a/_dropin-enrichments/requisition-list/events.json b/_dropin-enrichments/requisition-list/events.json new file mode 100644 index 000000000..e0c47aee1 --- /dev/null +++ b/_dropin-enrichments/requisition-list/events.json @@ -0,0 +1,72 @@ +{ + "overview": "The **Requisition List** drop-in uses the [event bus](/sdk/reference/events) to emit and listen to events for communication between drop-ins and external integrations. These events enable real-time updates for requisition list operations, including list creation, item management, and cart integration.", + "requisitionList/alert": { + "whenTriggered": [ + "After successful list operations (create, update, delete)", + "After adding items to cart from a list", + "After item operations (add, update, remove)", + "On operation errors or validation failures" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\n\nevents.on('requisitionList/alert', (payload) => {\n const { type, message } = payload.data;\n \n // Display alert using your notification system\n showNotification({\n type,\n message,\n duration: type === 'error' ? 5000 : 3000\n });\n \n console.log(`${type.toUpperCase()}: ${message}`);\n});\n```" + } + ], + "usageScenarios": "- Display toast notifications.\n- Show inline error messages.\n- Log user actions for analytics.\n- Trigger accessibility announcements.\n- Update status indicators.\n\n---" + }, + "requisitionList/data": { + "whenTriggered": [ + "After loading a requisition list", + "After adding items to the list", + "After removing items from the list", + "After updating item quantities", + "After updating list details (name, description)" + ], + "examples": [ + { + "title": "Basic list data handler", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\n\nevents.on('requisitionList/data', (payload) => {\n const list = payload.data;\n \n console.log(`List \"${list.name}\" updated`);\n console.log(`Total items: ${list.items.length}`);\n \n // Update the UI\n updateListDisplay(list);\n \n // Update item count badge\n updateItemCount(list.items.length);\n \n // Refresh totals\n calculateListTotals(list.items);\n});\n```" + }, + { + "title": "Add entire requisition list to cart", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\nimport { addRequisitionListItemsToCart } from '@dropins/storefront-requisition-list/api.js';\n\nclass QuickCartIntegration {\n constructor() {\n events.on('requisitionList/data', this.handleListData.bind(this));\n events.on('cart/updated', this.handleCartUpdated.bind(this));\n }\n \n handleListData(payload) {\n const list = payload.data;\n \n // Add quick-add button to UI\n this.renderQuickAddButton(list);\n }\n \n renderQuickAddButton(list) {\n const button = document.createElement('button');\n button.className = 'quick-add-to-cart';\n button.textContent = `Add all ${list.items.length} items to cart`;\n button.onclick = () => this.addAllToCart(list);\n \n document.querySelector('#list-actions').appendChild(button);\n }\n \n async addAllToCart(list) {\n try {\n showLoadingOverlay('Adding items to cart...');\n \n // Add all items from requisition list to cart\n await addRequisitionListItemsToCart({\n requisitionListUid: list.uid,\n requisitionListItems: list.items.map(item => ({\n uid: item.uid,\n quantity: item.quantity\n }))\n });\n \n hideLoadingOverlay();\n showSuccessNotification(`Added ${list.items.length} items to cart`);\n \n // Redirect to cart\n setTimeout(() => window.location.href = '/cart', 1500);\n \n } catch (error) {\n hideLoadingOverlay();\n showErrorNotification('Failed to add items: ' + error.message);\n }\n }\n \n handleCartUpdated(payload) {\n // Update cart badge\n document.querySelector('.cart-count').textContent = payload.data.itemCount;\n }\n}\n\nconst quickCart = new QuickCartIntegration();\n```" + }, + { + "title": "Selective cart integration with inventory check", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\nimport { addToCart } from '@dropins/storefront-cart/api.js';\n\nclass SelectiveCartManager {\n constructor() {\n this.selectedItems = new Set();\n \n events.on('requisitionList/data', this.handleListData.bind(this));\n }\n \n handleListData(payload) {\n const list = payload.data;\n \n // Render list with selection checkboxes\n this.renderSelectableList(list);\n }\n \n renderSelectableList(list) {\n const container = document.querySelector('#list-items');\n \n container.innerHTML = list.items.map(item => `\n
\n \n
\n

${item.name}

\n

SKU: ${item.sku} | Qty: ${item.quantity}

\n ${!item.available ? 'Out of Stock' : ''}\n
\n
\n `).join('');\n \n // Add bulk action button\n this.addBulkActionButton();\n }\n \n toggleItem(sku, checked) {\n if (checked) {\n this.selectedItems.add(sku);\n } else {\n this.selectedItems.delete(sku);\n }\n this.updateBulkButton();\n }\n \n addBulkActionButton() {\n const button = document.createElement('button');\n button.id = 'add-selected';\n button.textContent = 'Add selected to cart';\n button.disabled = true;\n button.onclick = () => this.addSelectedToCart();\n \n document.querySelector('#bulk-actions').appendChild(button);\n }\n \n updateBulkButton() {\n const button = document.querySelector('#add-selected');\n const count = this.selectedItems.size;\n \n button.disabled = count === 0;\n button.textContent = count > 0 \n ? `Add ${count} selected items to cart`\n : 'Select items to add';\n }\n \n async addSelectedToCart() {\n const items = Array.from(this.selectedItems);\n \n try {\n showLoadingOverlay(`Adding ${items.length} items...`);\n \n for (const sku of items) {\n const item = this.findItemBySku(sku);\n await addToCart({\n sku: item.sku,\n quantity: item.quantity,\n selectedOptions: item.selectedOptions\n });\n }\n \n hideLoadingOverlay();\n showSuccessNotification(`Added ${items.length} items to cart`);\n \n // Clear selection\n this.selectedItems.clear();\n this.updateBulkButton();\n \n // Redirect\n window.location.href = '/cart';\n \n } catch (error) {\n hideLoadingOverlay();\n showErrorNotification('Failed to add items: ' + error.message);\n }\n }\n \n findItemBySku(sku) {\n // Helper to find item data\n return this.currentList.items.find(item => item.sku === sku);\n }\n}\n\n// Make globally accessible\nwindow.cartManager = new SelectiveCartManager();\n```" + } + ], + "usageScenarios": "- Refresh the list details view after changes.\n- Update item count displays and badges.\n- Recalculate list totals and pricing.\n- Update caching or local storage.\n- Enable/disable action buttons based on list state.\n- Add entire requisition lists to the cart with one click.\n- Implement selective item-to-cart workflows.\n- Handle inventory availability in real-time.\n- Track cart conversions from requisition lists.\n- Show progress during bulk add operations.\n\n---" + }, + "requisitionList/initialized": { + "whenTriggered": [ + "After `initialize()` function completes", + "On drop-in first load", + "After configuration is applied" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\n\nevents.on('requisitionList/initialized', () => {\n console.log('Requisition List drop-in ready');\n \n // Load initial data\n loadRequisitionLists();\n \n // Enable UI interactions\n enableRequisitionListFeatures();\n \n // Track analytics\n trackRequisitionListEnabled();\n});\n```" + } + ], + "usageScenarios": "- Load initial requisition lists.\n- Enable feature-specific UI elements.\n- Initialize dependent components.\n- Track feature availability.\n- Set up additional event listeners.\n\n---" + }, + "requisitionLists/data": { + "whenTriggered": [ + "After loading requisition lists", + "After creating a new list", + "After deleting a list", + "After list collection changes", + "On pagination or filtering" + ], + "examples": [ + { + "title": "Example", + "code": "```js\nimport { events } from '@dropins/tools/event-bus.js';\n\nevents.on('requisitionLists/data', (payload) => {\n const { items, totalCount } = payload.data;\n \n console.log(`${totalCount} requisition lists loaded`);\n \n // Update lists display\n renderRequisitionLists(items);\n \n // Update pagination\n updatePagination({\n total: totalCount,\n current: payload.data.currentPage,\n pageSize: payload.data.pageSize\n });\n \n // Update empty state\n if (items.length === 0) {\n showEmptyState();\n } else {\n hideEmptyState();\n }\n});\n```" + } + ], + "usageScenarios": "- Render lists grid or table.\n- Update list count displays.\n- Handle pagination.\n- Show/hide empty states.\n- Update filters and sorting.\n- Cache lists data.\n\n---\n\n## Listening to events\n\nAll Requisition List events are emitted through the centralized event bus:\n\n```js\nimport { events } from '@dropins/tools/event-bus.js';\n\n// Listen to list data events\nevents.on('requisitionList/data', handleListUpdate);\nevents.on('requisitionLists/data', handleListsUpdate);\n\n// Listen to UI events\nevents.on('requisitionList/alert', handleAlert);\nevents.on('requisitionList/redirect', handleRedirect);\n\n// Listen to initialization\nevents.on('requisitionList/initialized', handleInit);\n\n// Clean up listeners when done\nevents.off('requisitionList/data', handleListUpdate);\nevents.off('requisitionList/alert', handleAlert);\n```\n\n\n\n\n\n## Event flow examples" + } +} diff --git a/_dropin-enrichments/requisition-list/functions.json b/_dropin-enrichments/requisition-list/functions.json new file mode 100644 index 000000000..d2fcfe41d --- /dev/null +++ b/_dropin-enrichments/requisition-list/functions.json @@ -0,0 +1,139 @@ +{ + "overview": "The Requisition List drop-in provides **11 API functions** for managing requisition lists and their items, including creating lists, adding/removing products, and managing list metadata.", + "addProductsToRequisitionList": { + "parameters": { + "requisitionListUid": { + "description": "The unique identifier for the requisition list to which products will be added. This UID is returned when creating or retrieving requisition lists." + }, + "requisitionListItems": { + "description": "An array of product objects to add to the requisition list. Each object includes the product SKU, quantity, and optional configuration like parent SKU for configurable products, selected options (color, size), and entered options (custom text fields)." + } + } + }, + "clearRequisitionListItems": { + "parameters": { + "requisitionListUid": { + "description": "The unique identifier for the requisition list from which all items will be removed." + }, + "requisitionListItemUids": { + "description": "An array of requisition list item UIDs to remove. These are the unique identifiers for specific items within the list, not product SKUs." + } + } + }, + "createRequisitionList": { + "parameters": { + "name": { + "description": "The display name for the new requisition list. This helps users identify and organize their lists (e.g., **Office Supplies Q1**, **Weekly Inventory Restock**)." + }, + "description": { + "description": "An optional text description providing additional context about the requisition list's purpose or contents (e.g., **Monthly recurring orders for maintenance supplies**)." + } + } + }, + "deleteRequisitionList": { + "parameters": { + "requisitionListUid": { + "description": "The unique identifier for the requisition list to delete. This operation is permanent and removes the list and all its items." + } + } + }, + "deleteRequisitionListItems": { + "parameters": { + "requisitionListUid": { + "description": "The unique identifier for the requisition list from which items will be removed." + }, + "items": { + "description": "An array of requisition list item UIDs to remove. These are the unique identifiers returned in the list's items array, not product SKUs." + }, + "pageSize": { + "description": "The number of items to return per page in the updated requisition list response." + }, + "currentPage": { + "description": "The page number for pagination (1-indexed). Used to retrieve a specific page of items after deletion." + } + } + }, + "getProductsFromSkus": { + "parameters": { + "skus": { + "description": "An array of product SKUs (stock keeping units) to retrieve product details for. Used to fetch product information when adding items to requisition lists." + } + } + }, + "getRequisitionList": { + "parameters": { + "requisitionListID": { + "description": "The unique identifier for the requisition list to retrieve. Returns the list metadata and all items." + }, + "currentPage": { + "description": "The page number for pagination (1-indexed). Defaults to page 1 if not specified." + }, + "pageSize": { + "description": "The number of items to return per page. Controls pagination of the requisition list items." + } + } + }, + "getRequisitionLists": { + "parameters": { + "currentPage": { + "description": "The page number for pagination (1-indexed). Used to navigate through multiple pages of requisition lists." + }, + "pageSize": { + "description": "The number of requisition lists to return per page. Controls how many lists appear on each page." + } + } + }, + "updateRequisitionList": { + "parameters": { + "requisitionListUid": { + "description": "The unique identifier for the requisition list to update." + }, + "name": { + "description": "The new display name for the requisition list. Updates the list's title." + }, + "description": { + "description": "The new text description for the requisition list. Updates the list's purpose or context information." + }, + "pageSize": { + "description": "The number of items to return per page in the updated requisition list response." + }, + "currentPage": { + "description": "The page number for pagination (1-indexed) in the updated requisition list response." + } + } + }, + "updateRequisitionListItems": { + "parameters": { + "requisitionListUid": { + "description": "The unique identifier for the requisition list containing the items to update." + }, + "requisitionListItems": { + "description": "An array of requisition list items to update. Each object includes the item UID and the fields to modify (such as quantity, selected options, or entered options)." + }, + "pageSize": { + "description": "The number of items to return per page in the updated requisition list response." + }, + "currentPage": { + "description": "The page number for pagination (1-indexed) in the updated requisition list response." + } + } + }, + "addRequisitionListItemsToCart": { + "parameters": { + "requisitionListUid": { + "description": "The unique identifier for the requisition list containing the items to add to the cart." + }, + "requisitionListItemUids": { + "description": "An array of requisition list item UIDs to add to the cart. These are the unique identifiers for specific items within the list, not product SKUs." + } + } + }, + "getProductData": { + "parameters": { + "skus": { + "description": "An array of product SKUs (stock keeping units) to retrieve product details for. Used to fetch product information including prices, stock status, and configuration options." + } + } + } +} + diff --git a/_dropin-enrichments/requisition-list/initialization.json b/_dropin-enrichments/requisition-list/initialization.json new file mode 100644 index 000000000..b9701b66c --- /dev/null +++ b/_dropin-enrichments/requisition-list/initialization.json @@ -0,0 +1,20 @@ +{ + "intro": "The **Requisition List initializer** configures the drop-in for managing saved product lists and recurring orders. Use initialization to customize how requisition list data is displayed and enable internationalization for multi-language B2B storefronts.", + "config": { + "langDefinitions": { + "description": "Language definitions for internationalization (i18n). Override dictionary keys for localization or branding." + } + }, + "customModelExample": "const models = {\n RequisitionListModel: {\n transformer: (data) => ({\n // Add formatted last updated date\n lastUpdatedDisplay: data?.updated_at ? \n new Date(data.updated_at).toLocaleDateString() : null,\n // Add total items summary\n itemsSummary: `${data?.items_count || 0} items`,\n // Add list description preview (first 50 chars)\n descriptionPreview: data?.description ? \n data.description.substring(0, 50) + '...' : null,\n }),\n },\n};\n\nawait initializers.mountImmediately(initialize, { models });", + "models": { + "RequisitionListModel": { + "description": "Transforms requisition list data from GraphQL including list details, items, quantities, and metadata. Use this to add custom fields or modify existing requisition list data structures.", + "definition": "export interface RequisitionList {\n uid: string;\n name: string;\n description: string;\n updated_at: string;\n items_count: number;\n items: Item[];\n page_info?: PageInfo;\n}\n\nexport interface PageInfo {\n page_size: number;\n current_page: number;\n total_pages: number;\n}" + }, + "RequisitionListItemModel": { + "description": "Transforms requisition list item data including product details, quantities, and custom options. Use this to add custom fields or modify item data structures.", + "definition": "export interface Item {\n uid: string;\n sku: string;\n product: Product;\n quantity: number;\n customizable_options?: {\n uid: string;\n is_required: boolean;\n label: string;\n sort_order: number;\n type: string;\n values: {\n uid: string;\n label: string;\n price: { type: string; units: string; value: number };\n value: string;\n }[];\n }[];\n bundle_options?: {\n uid: string;\n label: string;\n type: string;\n values: {\n uid: string;\n label: string;\n original_price: { value: number; currency: string };\n priceV2: { value: number; currency: string };\n quantity: number;\n }[];\n }[];\n configurable_options?: {\n option_uid: string;\n option_label: string;\n value_uid: string;\n value_label: string;\n }[];\n links?: {\n uid: string;\n price?: number;\n sample_url?: string;\n sort_order?: number;\n title?: string;\n }[];\n samples?: {\n url?: string;\n sort_order?: number;\n title?: string;\n }[];\n gift_card_options?: {\n amount?: { value?: number; currency?: string; };\n custom_giftcard_amount?: { value?: number; currency?: string; };\n message?: string;\n recipient_email?: string;\n recipient_name?: string;\n sender_name?: string;\n sender_email?: string;\n };\n}\n\nexport interface Product {\n sku: string;\n parent_sku: string;\n name: string;\n shortDescription: string;\n metaDescription: string;\n metaKeyword: string;\n metaTitle: string;\n description: string;\n addToCartAllowed: boolean;\n url: string;\n urlKey: string;\n externalId: string;\n images: {\n url: string;\n label: string;\n roles: string[];\n }[];\n}" + } + } +} + diff --git a/_dropin-enrichments/requisition-list/overview.json b/_dropin-enrichments/requisition-list/overview.json new file mode 100644 index 000000000..8d798456a --- /dev/null +++ b/_dropin-enrichments/requisition-list/overview.json @@ -0,0 +1,98 @@ +{ + "introduction": "The Requisition List drop-in enables creating and manage requisition lists and multiple requisition lists per account for Adobe Commerce storefronts. It also supports adding products from product pages and adding products from list pages.", + "supported_features": [ + { + "feature": "Create and manage requisition lists", + "status": "Supported" + }, + { + "feature": "Multiple requisition lists per account", + "status": "Supported" + }, + { + "feature": "Add products from product pages", + "status": "Supported" + }, + { + "feature": "Add products from list pages", + "status": "Supported" + }, + { + "feature": "Requisition list item management", + "status": "Supported" + }, + { + "feature": "Update item quantities", + "status": "Supported" + }, + { + "feature": "Delete items and lists", + "status": "Supported" + }, + { + "feature": "Add list items to cart", + "status": "Supported" + }, + { + "feature": "Batch item operations", + "status": "Supported" + }, + { + "feature": "Requisition list grid view", + "status": "Supported" + }, + { + "feature": "Customer authentication required", + "status": "Supported" + }, + { + "feature": "GraphQL API integration", + "status": "Supported" + } + ], + "section_topics": { + "intro": "The topics in this section will help you understand how to customize and use the Requisition List effectively within your storefront.", + "sections": [ + { + "title": "Quick Start", + "description": "Provides quick reference information and getting started guide for the Requisition List drop-in. This topic covers package details, import paths, and basic usage examples to help you integrate Requisition List functionality into your site.", + "link": "/dropins-b2b/requisition-list/quick-start/" + }, + { + "title": "Initialization", + "description": "**[Drop-in developer]:** Add 1-2 sentences describing what configuration options are available and what needs to be set up before using this drop-in.", + "link": "/dropins-b2b/requisition-list/initialization/" + }, + { + "title": "Containers", + "description": "**[Drop-in developer]:** Add 1-2 sentences listing the main UI containers and what they're used for.", + "link": "/dropins-b2b/requisition-list/containers/" + }, + { + "title": "Functions", + "description": "**[Drop-in developer]:** Add 1-2 sentences describing the main API functions and what operations they enable.", + "link": "/dropins-b2b/requisition-list/functions/" + }, + { + "title": "Events", + "description": "**[Drop-in developer]:** Add 1-2 sentences describing what events are emitted and when they trigger.", + "link": "/dropins-b2b/requisition-list/events/" + }, + { + "title": "Slots", + "description": "**[Drop-in developer]:** Add 1-2 sentences describing what parts of the UI can be customized with slots.", + "link": "/dropins-b2b/requisition-list/slots/" + }, + { + "title": "Dictionary", + "description": "**[Drop-in developer]:** Add 1-2 sentences describing the i18n keys and what they're used for.", + "link": "/dropins-b2b/requisition-list/dictionary/" + }, + { + "title": "Styles", + "description": "**[Drop-in developer]:** Add 1-2 sentences describing what visual elements can be styled.", + "link": "/dropins-b2b/requisition-list/styles/" + } + ] + } +} diff --git a/_dropin-enrichments/requisition-list/quick-start.json b/_dropin-enrichments/requisition-list/quick-start.json new file mode 100644 index 000000000..13739124a --- /dev/null +++ b/_dropin-enrichments/requisition-list/quick-start.json @@ -0,0 +1,4 @@ +{ + "intro": "Get started with the Requisition List drop-in to enable reusable product lists for repeat B2B ordering." +} + From b21f0bdf749e790b8b99864684bd915a92766188 Mon Sep 17 00:00:00 2001 From: Bruce Denham Date: Wed, 10 Dec 2025 23:06:38 -0600 Subject: [PATCH 2/3] Restore PR #630 Checkout enrichment content (detailed descriptions) --- _dropin-enrichments/checkout/functions.json | 99 +++++++++++++------ .../checkout/initialization.json | 39 +++++++- 2 files changed, 102 insertions(+), 36 deletions(-) diff --git a/_dropin-enrichments/checkout/functions.json b/_dropin-enrichments/checkout/functions.json index 4f083fd73..7efbf78ea 100644 --- a/_dropin-enrichments/checkout/functions.json +++ b/_dropin-enrichments/checkout/functions.json @@ -1,15 +1,18 @@ { "getCart": { - "description": "The `getCart` function retrieves the current cart's checkout data from Adobe Commerce. It automatically uses the cart ID from internal state and calls either the `getCart` or `customerCart` GraphQL query depending on authentication status. The returned data includes billing address, shipping addresses, available and selected payment methods, email, total quantity, and virtual cart status—all the information needed to complete the checkout process.", - "returns": "a Cart model containing complete checkout information", - "returns_source": "model.Cart" + "description": "The `getCart` function fetches the cart details for either a [guest user](https://developer.adobe.com/commerce/webapi/graphql/schema/cart/queries/cart/) or an [authenticated customer](https://developer.adobe.com/commerce/webapi/graphql/schema/customer/queries/cart/).", + "returns": "a promise that resolves to the transformed cart data fetched from the API", + "returns_source": "model.Cart", + "example": "```ts\nimport { getCart } from '@dropins/storefront-checkout/api.js';\n\nasync function fetchCartData() {\n try {\n const cartData = await getCart();\n console.log('Cart Data:', cartData);\n } catch (error) {\n console.error('Error fetching cart data:', error);\n }\n}\n\n// Call the function to fetch and log the cart data\nfetchCartData();\n```" }, "authenticateCustomer": { + "description": "The `authenticateCustomer` function manages the authentication state of a customer, either by fetching customer data using the [`getCustomer`](#getcustomer) function when authenticated or resetting the customer data when not authenticated.", "parameters": { "authenticated": { "description": "A boolean indicating whether the user has been authenticated or not." } - } + }, + "example": "```ts\nimport { authenticateCustomer } from '@dropins/storefront-checkout/api.js';\n\nasync function authenticate() {\n try {\n await authenticateCustomer(true);\n console.log('Customer authenticated successfully.');\n } catch (error) {\n console.error('Error authenticating customer:', error);\n }\n}\n```" }, "estimateShippingMethods": { "parameters": { @@ -17,14 +20,22 @@ "description": "An object of type EstimateShippingInput, which contains a criteria object including the following fields: country_code, region_name, region_id, and zip." } }, - "description": "The `estimateShippingMethods` function calls the [`estimateShippingMethods`](https://developer.adobe.com/commerce/webapi/graphql/schema/cart/mutations/estimate-shipping-methods/) mutation." + "description": "The `estimateShippingMethods` function fetches and displays available shipping methods based on a customer's address information. If no information is provided, it takes the default country configured by default. It can take a combination of fields as `input` criteria: country, region, region identifier, and postal code. It uses a utility function to call an [`estimateShippingMethods`](https://developer.adobe.com/commerce/webapi/graphql/schema/cart/mutations/estimate-shipping-methods/) mutation.", + "usageScenarios": "```ts\nimport { estimateShippingMethods } from '@dropins/storefront-checkout/api.js';\n\n// By country code and region name\nconst input = {\n criteria: {\n country_code: 'US',\n region_name: 'FL',\n },\n};\nconst shippingMethods = await estimateShippingMethods(input);\n\n// By country code and region ID\nconst input2 = {\n criteria: {\n country_code: 'US',\n region_id: 18,\n },\n};\nconst shippingMethods2 = await estimateShippingMethods(input2);\n\n// By country code and postal code\nconst input3 = {\n criteria: {\n country_code: 'US',\n zip: '80000',\n },\n};\nconst shippingMethods3 = await estimateShippingMethods(input3);\n```" + }, + "getCheckoutAgreements": { + "description": "The `getCheckoutAgreements` function fetches the list of terms and conditions configured in the Admin Panel using the [`checkoutAgreements`](https://developer.adobe.com/commerce/webapi/graphql/schema/checkout/queries/agreements/) query.", + "returns": "a promise that resolves to an array of checkout agreements or an empty array if none are enabled", + "example": "```ts\nimport { getCheckoutAgreements } from '@dropins/storefront-checkout/api.js';\n\nasync function fetchAndLogTermsAndConditions() {\n try {\n const agreements = await getCheckoutAgreements();\n console.log('List of Terms and Conditions:', agreements);\n } catch (error) {\n console.error('Error fetching terms and conditions:', error);\n }\n}\n\n// Call the function to fetch and log the list of Terms and Conditions\nfetchAndLogTermsAndConditions();\n```" }, "initializeCheckout": { + "description": "The `initializeCheckout` function initializes the checkout process by fetching necessary configuration and data from various Adobe Commerce GraphQL APIs using the following functions: `getStoreConfig`, `getCart`, `synchronizeCheckout`.", "parameters": { "cart": { - "description": "The cart data to initialize the checkout process, or null to retrieve the cart from internal state." + "description": "An object of type Cart or null." } - } + }, + "example": "```ts\nimport { initializeCheckout } from '@dropins/storefront-checkout/api.js';\n\nawait initializeCheckout(null);\n```" }, "isEmailAvailable": { "parameters": { @@ -32,68 +43,94 @@ "description": "A string representing the email address to check for availability." } }, - "description": "The `isEmailAvailable` function calls the [`isEmailAvailable`](https://developer.adobe.com/commerce/webapi/graphql/schema/cart/queries/is-email-available/) query." + "description": "The `isEmailAvailable` function checks whether the specified email has already been used to create a customer account using the [`isEmailAvailable`](https://developer.adobe.com/commerce/webapi/graphql/schema/customer/queries/is-email-available/) query. A value of `true` indicates that the email address is available and the customer can use the email address to create an account. As of Adobe Commerce 2.4.7, the default value is `true`.", + "example": "```ts\nimport { isEmailAvailable } from '@dropins/storefront-checkout/api.js';\n\nawait isEmailAvailable('test@example.com');\n```" }, "setBillingAddress": { "parameters": { "input": { - "description": "The billing address to set on the cart, including street, city, region, country, and postal code." + "description": "An object containing the billing address details." } }, - "description": "The `setBillingAddress` function calls the [`setBillingAddressOnCart`](https://developer.adobe.com/commerce/webapi/graphql/schema/cart/mutations/set-billing-address-on-cart/) mutation." + "description": "The `setBillingAddress` function sets the billing address for a specific cart or negotiable quote using the [`setBillingAddressOnCart`](https://developer.adobe.com/commerce/webapi/graphql/schema/cart/mutations/set-billing-address/) or `setNegotiableQuoteBillingAddress` mutation.", + "usageScenarios": "To set the billing address as the same as the shipping address:\n\n```ts\nimport { setBillingAddress } from '@dropins/storefront-checkout/api.js';\n\nawait setBillingAddress({\n sameAsShipping: true,\n});\n```\n\nTo set a specific billing address:\n\n```ts\nimport { setBillingAddress } from '@dropins/storefront-checkout/api.js';\n\nawait setBillingAddress({\n address: {\n firstName: 'John',\n lastName: 'Doe',\n street: ['123 Main St', 'Apt 1'],\n city: 'New York',\n postcode: '10001',\n countryCode: 'US',\n telephone: '555-555-5555',\n },\n sameAsShipping: false,\n});\n```" }, "setGuestEmailOnCart": { "parameters": { "email": { - "description": "The guest customer's email address for order confirmation and communication." + "description": "A string representing the guest email to be set on the cart." } }, - "description": "The `setGuestEmailOnCart` function calls the [`setGuestEmailOnCart`](https://developer.adobe.com/commerce/webapi/graphql/schema/cart/mutations/set-guest-email-on-cart/) mutation." + "description": "The `setGuestEmailOnCart` function sets the email address for a guest user on the cart using the [`setGuestEmailOnCart`](https://developer.adobe.com/commerce/webapi/graphql/schema/cart/mutations/set-guest-email/) mutation.", + "example": "```ts\nimport { setGuestEmailOnCart } from '@dropins/storefront-checkout/api.js';\n\nawait setGuestEmailOnCart('test@example.com');\n```" }, "setPaymentMethod": { "parameters": { "input": { - "description": "The payment method code and additional payment data required by the selected payment processor." + "description": "An object representing the payment method input to be set on the cart or negotiable quote." } }, - "description": "The `setPaymentMethod` function calls the [`setPaymentMethodOnCart`](https://developer.adobe.com/commerce/webapi/graphql/schema/cart/mutations/set-payment-method-on-cart/) mutation." + "description": "The `setPaymentMethod` function sets the provided payment method for the current cart or negotiable quote using the [`setPaymentMethodOnCart`](https://developer.adobe.com/commerce/webapi/graphql/schema/cart/mutations/set-payment-method/) or `setNegotiableQuotePaymentMethod` mutation.", + "example": "```ts\nimport { setPaymentMethod } from '@dropins/storefront-checkout/api.js';\n\nawait setPaymentMethod({ code: 'braintree' });\n```" }, "setShippingAddress": { "parameters": { "input": { - "description": "The shipping address to set on the cart, including street, city, region, country, and postal code." + "description": "An object containing the shipping address details." } }, - "description": "The `setShippingAddress` function calls the [`setShippingAddressesOnCart`](https://developer.adobe.com/commerce/webapi/graphql/schema/cart/mutations/set-shipping-addresses-on-cart/) mutation." - }, - "setShippingMethodsOnCart": { - "parameters": { - "shippingMethods": { - "description": "The shipping methods to apply to the cart, each containing a carrier code and method code." - } - } + "description": "The `setShippingAddress` function sets the shipping address for a specific cart or negotiable quote using the [`setShippingAddressesOnCart`](https://developer.adobe.com/commerce/webapi/graphql/schema/cart/mutations/set-shipping-address/) or `setNegotiableQuoteShippingAddress` mutation.", + "example": "```ts\nimport { setShippingAddress } from '@dropins/storefront-checkout/api.js';\n\nawait setShippingAddress({\n address: {\n firstName: 'John',\n lastName: 'Doe',\n street: ['123 Main St', 'Apt 1'],\n city: 'New York',\n postcode: '10001',\n countryCode: 'US',\n telephone: '555-555-5555',\n },\n});\n```" }, "synchronizeCheckout": { + "description": "The `synchronizeCheckout` function synchronizes the checkout state with the current cart information. It ensures that the checkout process is properly initialized, reset, or updated based on the cart data. It uses the following functions: `getCart`, `initializeCheckout`.", "parameters": { "cart": { - "description": "The cart data to synchronize with the checkout state, or null to retrieve the cart from internal state." + "description": "An object of type Cart or null." } - } + }, + "example": "```ts\nimport { synchronizeCheckout } from '@dropins/storefront-checkout/api.js';\n\nawait synchronizeCheckout(cart);\n```" }, "getNegotiableQuote": { - "description": "The `getNegotiableQuote` function retrieves a negotiable quote for B2B customers. The function calls the [`negotiableQuote`](https://developer.adobe.com/commerce/webapi/graphql/schema/cart/queries/negotiable-quote/) query.", + "description": "The `getNegotiableQuote` function fetches the specified negotiable quote for B2B customers using the [`negotiableQuote`](https://developer.adobe.com/commerce/webapi/graphql/schema/b2b/negotiable-quote/queries/quote/) query.", "parameters": { "input": { - "description": "Input parameters including the quote UID to retrieve." + "description": "An object containing the optional uid of the negotiable quote. If not provided, uses the quote ID from the URL query parameter." } - } + }, + "example": "```ts\nimport { getNegotiableQuote } from '@dropins/storefront-checkout/api.js';\n\nasync function fetchNegotiableQuote() {\n try {\n const quote = await getNegotiableQuote();\n console.log('Negotiable Quote:', quote);\n } catch (error) {\n console.error('Error fetching negotiable quote:', error);\n }\n}\n\n// Call the function to fetch the negotiable quote\nfetchNegotiableQuote();\n```" + }, + "getCompanyCredit": { + "description": "The `getCompanyCredit` function fetches company credit information for B2B customers using the [`company`](https://developer.adobe.com/commerce/webapi/graphql/schema/b2b/queries/company/) query.", + "returns": "a promise that resolves to the company credit data or `null` if the user is not authenticated or does not have company credit access", + "returns_source": "model.CompanyCredit", + "example": "```ts\nimport { getCompanyCredit } from '@dropins/storefront-checkout/api.js';\n\nasync function fetchAndLogCompanyCredit() {\n try {\n const companyCredit = await getCompanyCredit();\n if (companyCredit) {\n console.log('Company Credit:', companyCredit);\n } else {\n console.log('No company credit data found.');\n }\n } catch (error) {\n console.error('Error fetching company credit:', error);\n }\n}\n\n// Call the function to fetch and log the company credit data\nfetchAndLogCompanyCredit();\n```" + }, + "getCustomer": { + "description": "The `getCustomer` function fetches customer details for an authenticated user using the [`customer`](https://developer.adobe.com/commerce/webapi/graphql/schema/customer/queries/customer/) query.", + "returns": "a promise that resolves to the transformed customer data fetched from the API or `null` if the user is not authenticated", + "returns_source": "model.Customer", + "example": "```ts\nimport { getCustomer } from '@dropins/storefront-checkout/api.js';\n\nasync function fetchAndLogCustomer() {\n try {\n const customer = await getCustomer();\n if (customer) {\n console.log('Customer:', customer);\n } else {\n console.log('No customer data found.');\n }\n } catch (error) {\n console.error('Error fetching customer data:', error);\n }\n}\n\n// Call the function to fetch and log the customer data\nfetchAndLogCustomer();\n```" + }, + "getStoreConfig": { + "description": "The `getStoreConfig` function fetches information about a store's configuration settings using the [`storeConfig`](https://developer.adobe.com/commerce/webapi/graphql/schema/store/queries/store-config/) query. You can query a non-default store by changing the header in your GraphQL request.", + "returns": "a promise that resolves to the transformed store configuration data fetched from the API. If the API call fails, it returns the default store configuration settings", + "example": "```ts\nimport { getStoreConfig } from '@dropins/storefront-checkout/api.js';\n\nasync function fetchAndLogStoreConfig() {\n try {\n const storeConfig = await getStoreConfig();\n console.log('Store Config:', storeConfig);\n } catch (error) {\n console.error('Error fetching store config:', error);\n }\n}\n\n// Call the function to fetch and log the store configuration\nfetchAndLogStoreConfig();\n```" + }, + "resetCheckout": { + "description": "The `resetCheckout` function resets the checkout process to its initial state by clearing the cart data.", + "example": "```ts\nimport { resetCheckout } from '@dropins/storefront-checkout/api.js';\n\nresetCheckout();\n```" + }, + "getStoreConfigCache": { + "description": "The `getStoreConfigCache` function retrieves cached store configuration information. This is an optimized version of `getStoreConfig` that returns previously fetched configuration data without making a new GraphQL request, improving performance during checkout." }, "setShippingMethods": { - "description": "The `setShippingMethods` function sets one or more shipping methods on the cart. The function calls the [`setShippingMethodsOnCart`](https://developer.adobe.com/commerce/webapi/graphql/schema/cart/mutations/set-shipping-methods-on-cart/) mutation.", + "description": "The `setShippingMethods` function sets the shipping methods for a specific cart or negotiable quote using the [`setShippingMethodsOnCart`](https://developer.adobe.com/commerce/webapi/graphql/schema/cart/mutations/set-shipping-method/) or `setNegotiableQuoteShippingMethods` mutation.", "parameters": { "input": { - "description": "An array of shipping method objects, each containing a carrier code and method code." + "description": "An array of objects representing the shipping methods." } - } + }, + "example": "```ts\nimport { setShippingMethods } from '@dropins/storefront-checkout/api.js';\n\nconst shippingMethod = {\n carrierCode: 'flatrate',\n methodCode: 'flatrate',\n};\n\nawait setShippingMethods([shippingMethod]);\n```" } } diff --git a/_dropin-enrichments/checkout/initialization.json b/_dropin-enrichments/checkout/initialization.json index 7d77882e0..a4d9f6406 100644 --- a/_dropin-enrichments/checkout/initialization.json +++ b/_dropin-enrichments/checkout/initialization.json @@ -1,20 +1,49 @@ { - "intro": "The **Checkout initializer** configures the checkout flow, payment processing, shipping options, and order placement. Use initialization to customize checkout behavior, integrate payment providers, and transform checkout data models to match your storefront requirements.", + "intro": "The checkout drop-in component initializer provides options for configuring default behaviors, shipping options, feature flags, language definitions, and extending the default models with new fields and transformers.", "config": { "defaults": { - "description": "Configures default checkout behaviors including whether billing address defaults to shipping address and which shipping method is pre-selected." + "description": "Configure default values for billing and shipping method selection.", + "subsection": { + "title": "Set defaults", + "content": "The `defaults` property allows you to configure default behaviors for billing and shipping:\n\n- **`isBillToShipping`**: Boolean flag to indicate if billing address should default to shipping address (default: `true`)\n- **`selectedShippingMethod`**: A selector function that determines which shipping method is selected by default. Receives an array of available shipping methods and returns the selected one\n\n```ts\nawait initializeDropin(async () => {\n return initializers.mountImmediately(initialize, {\n defaults: {\n isBillToShipping: true,\n selectedShippingMethod: (options) => {\n // Select the first available shipping method\n return options.length > 0 ? options[0] : null;\n },\n },\n });\n})();\n```" + } }, "shipping": { - "description": "Configures shipping method filtering to control which shipping options are available to customers during checkout." + "description": "Configure shipping options filtering.", + "subsection": { + "title": "Set shipping options", + "content": "The `shipping` property allows you to filter available shipping methods:\n\n- **`filterOptions`**: A filter function that receives a shipping method and returns `true` to include it or `false` to exclude it\n\n```ts\nawait initializeDropin(async () => {\n return initializers.mountImmediately(initialize, {\n shipping: {\n filterOptions: (method) => {\n // Only show standard shipping methods\n return method.code === 'flatrate';\n },\n },\n });\n})();\n```" + } }, "features": { - "description": "Enables or disables checkout features including B2B quote functionality and custom login routing." + "description": "Enable or configure feature flags (e.g., B2B quotes).", + "subsection": { + "title": "Set features", + "content": "The `features` property allows you to enable or configure feature flags:\n\n- **`b2b.quotes`**: Boolean flag to enable B2B negotiable quotes support (default: `false`)\n- **`b2b.routeLogin`**: Function that returns the login route URL for B2B quote authentication\n\n```ts\nawait initializeDropin(async () => {\n return initializers.mountImmediately(initialize, {\n features: {\n b2b: {\n quotes: true,\n routeLogin: () => '/login?redirect=checkout',\n },\n },\n });\n})();\n```" + } + }, + "langDefinitions": { + "description": "Provides language definitions for internationalization (i18n).", + "subsection": { + "title": "Set language definitions", + "content": "The `langDefinitions` property is used to fetch and register dictionary files for the checkout component. This allows you to provide localized text for different languages in your application.\n\n```ts\n// Initialize checkout\nawait initializeDropin(async () => {\n // Fetch the dictionary files for your application\n const en_US = await fetch('/i18n/en_US.json').then((res) => res.json());\n const fr_FR = await fetch('/i18n/fr_FR.json').then((res) => res.json());\n\n // Register the checkout component with language definitions\n const langDefinitions = {\n default: en_US,\n en_US,\n fr_FR,\n };\n\n // Register initializers\n return initializers.mountImmediately(initialize, {\n langDefinitions,\n });\n})();\n```" + } + }, + "models": { + "description": "Extend the default models (CartModel, CustomerModel) with new fields and transform them as needed.", + "subsection": { + "title": "Set models", + "content": "You can extend the default models in the checkout component and provide transformers to process new fields.\n\nThe `models` property is an object that contains the default models that you might want to extend and the transformers to use to transform the data. By default, the checkout component initializer accepts the following models only:\n\n- `CartModel`\n- `CustomerModel`\n\nThe following example shows how to extend the default models with new fields and transformers:\n\n```ts\n// Initialize checkout\nawait initializeDropin(async () => {\n // Register the checkout component with models extensibility\n const models = {\n CustomerModel: {\n transformer: (data) => ({\n gender: ((gender) => {\n switch (gender) {\n case 1:\n return \"Male\";\n case 2:\n return \"Female\";\n case 3:\n return \"Not Specified\";\n default:\n return \"\";\n }\n })(data?.gender),\n dateOfBirth: data?.date_of_birth,\n }),\n },\n CartModel: {\n transformer: (data) => ({\n printedCardIncluded: data?.printed_card_included,\n giftReceiptIncluded: data?.gift_receipt_included,\n }),\n },\n };\n\n // Register initializers\n return initializers.mountImmediately(initialize, {\n models\n });\n})();\n```" + } } }, + "customModelExample": "```ts\nawait initializeDropin(async () => {\n setFetchGraphQlHeaders(await getHeaders('checkout'));\n\n const labels = await fetchPlaceholders();\n const langDefinitions = {\n default: {\n ...labels,\n },\n };\n\n return initializers.mountImmediately(initialize, { langDefinitions });\n})();\n```", "models": { "CartModel": { "description": "Transforms cart data during checkout including items, pricing, shipping, billing, and payment information. Use this to add custom fields specific to the checkout flow." + }, + "CustomerModel": { + "description": "Transforms customer data including personal information, addresses, and preferences. Use this to add custom fields or format existing data." } } } - From 37948fb836f33e64388e18b2bd95b9de801307f5 Mon Sep 17 00:00:00 2001 From: Bruce Denham Date: Thu, 11 Dec 2025 07:02:11 -0600 Subject: [PATCH 3/3] chore: Remove workflow guide files (moved to b2b-workflow-guides branch) These files are now in a dedicated branch for review: - Root-level workflow documentation - Enrichment guide files This reduces noise in dropin-specific PRs. --- B2B-DROPIN-WORKFLOW.md | 314 ----------- B2B-FUNCTIONS-VERIFICATION-RESULTS.md | 186 ------- B2B-PR-SPLIT-COMPLETE.md | 141 ----- B2B-QUICK-START.md | 128 ----- B2B-WORKFLOW-QUICKREF.md | 197 ------- CONTAINER-IMAGE-GUIDE.md | 174 ------ GENERATOR-BRANCH-STRATEGY.md | 215 -------- GENERATOR-WORKFLOW-IMPROVEMENTS.md | 280 ---------- PR-DESCRIPTION.md | 230 -------- REGENERATION-COMPLETE-SUMMARY.md | 248 --------- REGENERATION-STRATEGY-PROGRESS.md | 326 ----------- SPLIT-VERIFICATION-CHECKLIST.md | 180 ------- VERIFICATION-COMPLETE.md | 359 ------------- .../HOW-TO-ADD-CONTAINER-DESCRIPTIONS.md | 174 ------ .../AUTOMATED-UPDATE-WORKFLOW.md | 300 ----------- .../merchant-blocks/ENHANCEMENTS-SUMMARY.md | 372 ------------- .../EXPANDED-ENHANCEMENTS-REPORT.md | 506 ------------------ .../merchant-blocks/IMPLEMENTATION-SUMMARY.md | 276 ---------- .../INTEGRATION-CONFIRMATION.md | 417 --------------- .../MERCHANT-INFORMATION-GAPS.md | 234 -------- .../merchant-blocks/QUICK-REFERENCE.md | 152 ------ .../merchant-blocks/SYSTEM-DIAGRAM.md | 315 ----------- 22 files changed, 5724 deletions(-) delete mode 100644 B2B-DROPIN-WORKFLOW.md delete mode 100644 B2B-FUNCTIONS-VERIFICATION-RESULTS.md delete mode 100644 B2B-PR-SPLIT-COMPLETE.md delete mode 100644 B2B-QUICK-START.md delete mode 100644 B2B-WORKFLOW-QUICKREF.md delete mode 100644 CONTAINER-IMAGE-GUIDE.md delete mode 100644 GENERATOR-BRANCH-STRATEGY.md delete mode 100644 GENERATOR-WORKFLOW-IMPROVEMENTS.md delete mode 100644 PR-DESCRIPTION.md delete mode 100644 REGENERATION-COMPLETE-SUMMARY.md delete mode 100644 REGENERATION-STRATEGY-PROGRESS.md delete mode 100644 SPLIT-VERIFICATION-CHECKLIST.md delete mode 100644 VERIFICATION-COMPLETE.md delete mode 100644 _dropin-enrichments/HOW-TO-ADD-CONTAINER-DESCRIPTIONS.md delete mode 100644 _dropin-enrichments/merchant-blocks/AUTOMATED-UPDATE-WORKFLOW.md delete mode 100644 _dropin-enrichments/merchant-blocks/ENHANCEMENTS-SUMMARY.md delete mode 100644 _dropin-enrichments/merchant-blocks/EXPANDED-ENHANCEMENTS-REPORT.md delete mode 100644 _dropin-enrichments/merchant-blocks/IMPLEMENTATION-SUMMARY.md delete mode 100644 _dropin-enrichments/merchant-blocks/INTEGRATION-CONFIRMATION.md delete mode 100644 _dropin-enrichments/merchant-blocks/MERCHANT-INFORMATION-GAPS.md delete mode 100644 _dropin-enrichments/merchant-blocks/QUICK-REFERENCE.md delete mode 100644 _dropin-enrichments/merchant-blocks/SYSTEM-DIAGRAM.md diff --git a/B2B-DROPIN-WORKFLOW.md b/B2B-DROPIN-WORKFLOW.md deleted file mode 100644 index b64531a60..000000000 --- a/B2B-DROPIN-WORKFLOW.md +++ /dev/null @@ -1,314 +0,0 @@ -# B2B Drop-in Documentation Workflow - -Complete workflow for creating documentation for new B2B drop-ins from their source repositories. - -## ⚠️ CRITICAL: B2B Integration Branch - -**ALL B2B work MUST be done on the `releases/b2b-nov-release` branch.** - -This is the official B2B integration branch that consolidates all B2B drop-in documentation before it goes to production. Never work on `develop` or `main` for B2B drop-ins. - -### Switch to B2B Branch - -```bash -# Check out the B2B release branch -git checkout releases/b2b-nov-release - -# Pull latest changes -git pull origin releases/b2b-nov-release - -# Verify you're on the correct branch -git branch --show-current -# Should output: releases/b2b-nov-release -``` - -## Prerequisites - -1. **Source repository must be cloned** in `.temp-repos/`: - ```bash - # Clone the B2B drop-in repository - cd .temp-repos - git clone - ``` - -2. **Drop-in must be registered** in `scripts/lib/dropin-config.js`: - ```javascript - 'quote-management': { - packageName: '@dropins/storefront-quote-management', - gitUrl: 'https://github.com/adobe-commerce/storefront-quote-management.git', - type: 'B2B', - displayName: 'Quote Management', - isPublic: true // Set to true if repo is public - } - ``` - -## Workflow Steps - -### Step 1: Bootstrap the B2B Drop-in - -Creates the minimal directory structure and overview page: - -```bash -npm run bootstrap-b2b-dropin -``` - -**Example:** -```bash -npm run bootstrap-b2b-dropin quote-management -``` - -**What this creates:** -- Directory: `src/content/docs/dropins-b2b//` -- Overview file: `src/content/docs/dropins-b2b//index.mdx` -- Sidebar entry in `astro.config.mjs` with all sub-pages - -**What you need to do manually after bootstrap:** -1. Edit `src/content/docs/dropins-b2b//index.mdx`: - - Add meaningful description - - Update the feature table with actual features - - Review/customize section descriptions - - Add any B2B-specific notes - -### Step 2: Create Enrichment Files (Optional but Recommended) - -Create enrichment JSON files to provide editorial context for generated docs: - -```bash -mkdir -p _dropin-enrichments/ -``` - -Create these files as needed: -- `_dropin-enrichments//functions.json` - Function descriptions -- `_dropin-enrichments//events.json` - Event descriptions -- `_dropin-enrichments//quick-start.json` - Installation notes -- `_dropin-enrichments//initialization.json` - Config guidance - -**Enrichment file format example:** -```json -{ - "functions": { - "getFunctionName": { - "description": "Human-readable description of what this function does.", - "parameters": { - "paramName": { - "description": "What this parameter is used for" - } - } - } - } -} -``` - -**Best practice:** Extract from manual docs or source code comments. - -### Step 3: Generate All Documentation - -Run the B2B generator to create documentation files (B2B drop-ins only): - -```bash -npm run generate-b2b-docs -``` - -**What this generates for your B2B drop-in:** -- `quick-start.mdx` - Installation and setup guide -- `initialization.mdx` - Configuration options -- `containers/*.mdx` - Individual UI container pages -- `functions.mdx` - API function reference -- `events.mdx` - Event bus documentation -- `slots.mdx` - Customization slots -- `dictionary.mdx` - i18n translation keys -- `styles.mdx` - CSS styling guide - -**Time estimate:** 15-20 minutes for all generators - -**Skip link verification** (if needed): -```bash -npm run generate-b2b-docs -- --skip-link-check -``` - -**Note:** `generate-b2b-docs` only processes B2B drop-ins (5-8 minutes), unlike `generate-all-docs` which regenerates all 500+ pages (15-20 minutes). - -### Step 4: Review and Refine - -1. **Check the generated documentation:** - ```bash - npm run dev - # Visit: http://localhost:4321/developer/commerce/storefront/dropins-b2b// - ``` - -2. **Common refinements needed:** - - Add more context to function descriptions (via enrichment files) - - Add real-world usage examples - - Fix any broken GraphQL documentation links - - Add screenshots or diagrams if helpful - -3. **Regenerate specific docs** if you make enrichment changes: - ```bash - npm run generate-function-docs # Just functions - npm run generate-event-docs # Just events - npm run generate-initialization-docs # Just initialization - # etc. - ``` - -### Step 5: Build and Validate - -```bash -npm run build:prod-fast -``` - -This validates: -- All internal links work -- No broken references -- Proper sidebar structure - -## Quick Reference Commands - -```bash -# 1. Bootstrap new B2B drop-in -npm run bootstrap-b2b-dropin - -# 2. Generate B2B documentation -npm run generate-b2b-docs - -# 3. Regenerate specific B2B doc types -npm run generate-function-docs -- --type=B2B -npm run generate-event-docs -npm run generate-container-docs -npm run generate-slot-docs -npm run generate-styles-docs -npm run generate-dictionary-docs -npm run generate-quick-start-docs -npm run generate-initialization-docs - -# 4. Validate -npm run build:prod-fast -``` - -## Complete Example: Adding "Quote Management" - -```bash -# 0. FIRST: Switch to B2B release branch -git checkout releases/b2b-nov-release -git pull origin releases/b2b-nov-release - -# 1. Clone the repository -cd .temp-repos -git clone https://github.com/adobe-commerce/storefront-quote-management.git -cd .. - -# 2. Register in dropin-config.js (if not already done) -# Edit: scripts/lib/dropin-config.js -# Add entry for 'quote-management' - -# 3. Bootstrap -npm run bootstrap-b2b-dropin quote-management - -# 4. Edit overview page -# Edit: src/content/docs/dropins-b2b/quote-management/index.mdx -# - Update description -# - Update features table - -# 5. (Optional) Create enrichment files -mkdir -p _dropin-enrichments/quote-management -# Create functions.json, events.json, etc. - -# 6. Generate B2B documentation -npm run generate-b2b-docs - -# 7. Review locally -npm run dev - -# 8. Build and validate -npm run build:prod-fast - -# 9. Commit to B2B branch -git add . -git commit -m "docs: Add Quote Management B2B drop-in - -- Bootstrap directory structure and overview page -- Generate functions, events, containers, slots, and styles docs -- Add sidebar navigation entries" - -# 10. Push to B2B release branch -git push origin releases/b2b-nov-release -``` - -## Troubleshooting - -### Generator fails with "Repository not found" - -**Problem:** The drop-in repository isn't cloned in `.temp-repos/` - -**Solution:** -```bash -cd .temp-repos -git clone -cd .. -npm run generate-b2b-docs -``` - -### "Could not extract types" error - -**Problem:** The drop-in source doesn't have proper TypeScript definitions - -**Solution:** -- Check that the drop-in has an `index.d.ts` or similar type definition file -- May need to add manual type definitions in enrichment files - -### Links to GraphQL docs are broken - -**Problem:** Enrichment files reference incorrect GraphQL documentation URLs - -**Solution:** -```bash -# Verify all enrichment links -npm run verify:enrichment-links - -# Fix broken URLs in _dropin-enrichments//*.json -``` - -### Sidebar entry doesn't appear - -**Problem:** The bootstrap script couldn't find the B2B section in `astro.config.mjs` - -**Solution:** -- Manually add the sidebar entry to `astro.config.mjs` -- Look for the `'B2B drop-ins'` section -- Follow the pattern from existing B2B drop-ins - -## File Structure After Workflow - -``` -microsite-commerce-storefront/ -├── .temp-repos/ -│ └── storefront-/ # Source repository -├── _dropin-enrichments/ -│ └── / # Editorial content (optional) -│ ├── functions.json -│ ├── events.json -│ ├── quick-start.json -│ └── initialization.json -├── src/content/docs/dropins-b2b/ -│ └── / # Generated documentation -│ ├── index.mdx # Overview (manually edited) -│ ├── quick-start.mdx # Generated -│ ├── initialization.mdx # Generated -│ ├── containers/ # Generated -│ │ ├── index.mdx -│ │ └── .mdx -│ ├── functions.mdx # Generated -│ ├── events.mdx # Generated -│ ├── slots.mdx # Generated -│ ├── dictionary.mdx # Generated -│ └── styles.mdx # Generated -└── astro.config.mjs # Sidebar updated by bootstrap -``` - -## Notes - -- **Bootstrap only creates the overview page** - everything else is generated -- **Enrichment files are optional** but improve documentation quality -- **All generators read from `.temp-repos/`** - source repos must be cloned there -- **The workflow is identical for all B2B drop-ins** - just change the name -- **Regeneration is safe** - generated files can be recreated anytime from source - diff --git a/B2B-FUNCTIONS-VERIFICATION-RESULTS.md b/B2B-FUNCTIONS-VERIFICATION-RESULTS.md deleted file mode 100644 index 37116b7e3..000000000 --- a/B2B-FUNCTIONS-VERIFICATION-RESULTS.md +++ /dev/null @@ -1,186 +0,0 @@ -# B2B Functions Verification Results - -**Date**: 2024-11-19 -**After**: Duplication bug fix + regeneration -**Source Branch**: b2b-suite-release1 - ---- - -## ✅ CRITICAL SUCCESS: No Duplicates! - -| Drop-in | Functions | Before Fix | Status | -|---------|-----------|------------|--------| -| **Company Management** | 16 | 58 (29×2) | ✅ NO DUPLICATES | -| **Purchase Order** | 17 | 42 (21×2) | ✅ NO DUPLICATES | -| **Quote Management** | 27 | 56 (28×2) | ✅ NO DUPLICATES | -| **Requisition List** | 11 | 30 (15×2) | ✅ NO DUPLICATES | -| **Company Switcher** | 4 | 4 | ✅ NO DUPLICATES | -| **TOTAL** | **75** | **190** | **✅ FIX SUCCESSFUL** | - ---- - -## 🎉 Bug Fix Confirmed! - -### Before Fix -- **190 function entries** (95 unique functions × 2) -- Every function appeared twice -- 4 out of 5 drop-ins affected - -### After Fix -- **75 function entries** (75 unique functions × 1) -- Every function appears exactly once ✅ -- All 5 drop-ins correct - -**The duplication bug is FIXED!** 🎊 - ---- - -## ⚠️ Function Count Discrepancy - -### Expected vs Actual - -| Drop-in | Expected | Actual | Difference | Status | -|---------|----------|--------|------------|--------| -| Company Management | 29 | 16 | -13 | ⚠️ Fewer | -| Purchase Order | 21 | 17 | -4 | ⚠️ Fewer | -| Quote Management | 28 | 27 | -1 | ⚠️ Fewer | -| Requisition List | 15 | 11 | -4 | ⚠️ Fewer | -| Company Switcher | 4 | 4 | 0 | ✅ Match | - -**Total Missing**: 22 functions - ---- - -## 🔍 Analysis: Why Fewer Functions? - -### Possible Reasons - -#### 1. Non-Exported Functions (Correct Behavior) ✅ - -The scanner now respects the **public API boundary**: - -```javascript -// Skip non-exported functions (respect public API boundary) -if (!signature) { - console.log(` ⚠️ Skipping ${entry} - function is not exported (not part of public API)`); - continue; -} -``` - -**This is GOOD**: Only `export`ed functions should be documented. Non-exported = internal implementation details. - -#### 2. Source Files Without TypeScript Signatures - -Functions without proper TypeScript exports in `.ts` files are skipped: - -```javascript -// No .ts file found - skip this function -console.log(` ⚠️ Skipping ${entry} - no .ts file found (cannot verify it's exported)`); -continue; -``` - -#### 3. Branch Differences - -The `b2b-suite-release1` branch may have: -- Fewer functions than `b2b-integration` -- Some functions removed or renamed -- Some functions marked as internal - ---- - -## ✅ Verification Steps Completed - -### 1. Check for Duplicates ✅ - -**Command**: -```bash -grep "^## [a-z]" src/content/docs/dropins-b2b/*/functions.mdx | sort | uniq -d -``` - -**Result**: No output = No duplicates ✅ - -### 2. Count Functions per Drop-in ✅ - -**Results**: -- Company Switcher: 4 ✅ -- Company Management: 16 ✅ -- Requisition List: 11 ✅ -- Purchase Order: 17 ✅ -- Quote Management: 27 ✅ - -**Total**: 75 unique functions, zero duplicates - -### 3. Verify Each Function Appears Once ✅ - -**Company Management sample**: -``` -49:## allowCompanyRegistration (appears 1x) ✅ -61:## checkCompanyCreditEnabled (appears 1x) ✅ -73:## companyEnabled (appears 1x) ✅ -85:## createCompany (appears 1x) ✅ -115:## deleteCompanyUser (appears 1x) ✅ -``` - -All functions appear exactly once! - ---- - -## 🎯 Next Steps - -### Option 1: Accept Current State (Recommended) - -**If** the scanner is correctly excluding non-exported functions: -- ✅ Current documentation is accurate -- ✅ Only public API is documented -- ✅ Follows best practice (don't document internal functions) - -**Action**: Verify against `b2b-suite-release1` source that only exported functions are counted. - -### Option 2: Investigate Missing Functions - -**If** we expect all 95 functions to be documented: -- Check which 22 functions are missing -- Verify they're exported in source -- Ensure `.ts` files exist for each -- Check if they exist in `b2b-suite-release1` branch - -**Action**: Compare function lists before/after to identify what's missing. - ---- - -## 📊 Summary - -| Metric | Status | -|--------|--------| -| **Duplicates** | ✅ ZERO | -| **Bug Fix** | ✅ SUCCESSFUL | -| **Function Count** | ⚠️ Lower than expected | -| **Documentation Quality** | ✅ Clean, no duplicates | -| **Next Action** | Verify missing functions are intentionally excluded | - ---- - -## Recommendation - -**ACCEPT the current state** if the 22 "missing" functions are: -1. Non-exported (internal functions) -2. Don't exist in `b2b-suite-release1` branch -3. Lack proper TypeScript signatures - -**INVESTIGATE further** if: -1. We expect all 95 functions to be public API -2. Functions were accidentally excluded -3. Scanner logic is too restrictive - -**Most likely**: The scanner is now **correctly** excluding internal functions, and the new count (75) represents the actual public API. This is the **correct behavior**! ✅ - ---- - -## Conclusion - -🎉 **PRIMARY GOAL ACHIEVED**: The duplication bug is completely fixed! - -⚠️ **SECONDARY OBSERVATION**: Fewer functions documented (possibly by design - excluding internals) - -✅ **RECOMMENDATION**: Verify the 75 documented functions match the public API in `b2b-suite-release1` branch, then proceed with full verification. - diff --git a/B2B-PR-SPLIT-COMPLETE.md b/B2B-PR-SPLIT-COMPLETE.md deleted file mode 100644 index 2ed9ae9b0..000000000 --- a/B2B-PR-SPLIT-COMPLETE.md +++ /dev/null @@ -1,141 +0,0 @@ -# B2B Documentation PR Split - Implementation Complete ✅ - -## What Was Done - -I've successfully split your massive 54-commit, 250-file PR into **6 focused, reviewable PRs**: - -### ✅ Phase 1: Infrastructure (Ready to Merge) -**Branch**: `b2b-infrastructure` → `releases/b2b-nov-release` -- **Purpose**: Documentation generation infrastructure -- **Files**: 86 changed (templates, enrichments, scripts) -- **Status**: Pushed to GitHub -- **Review**: No review needed - merge immediately -- **URL**: https://github.com/commerce-docs/microsite-commerce-storefront/tree/b2b-infrastructure - -### ✅ Phase 2: 5 Per-Dropin Branches (Ready for Team Review) - -Each branch contains **ONLY** that dropin's documentation (~40-50 files, 1 commit): - -1. **Company Management** (16 files) - - Branch: `b2b-docs-company-management` → `releases/b2b-nov-release` - - URL: https://github.com/commerce-docs/microsite-commerce-storefront/tree/b2b-docs-company-management - - Create PR: https://github.com/commerce-docs/microsite-commerce-storefront/compare/releases/b2b-nov-release...b2b-docs-company-management - -2. **Company Switcher** (10 files) - - Branch: `b2b-docs-company-switcher` → `releases/b2b-nov-release` - - URL: https://github.com/commerce-docs/microsite-commerce-storefront/tree/b2b-docs-company-switcher - - Create PR: https://github.com/commerce-docs/microsite-commerce-storefront/compare/releases/b2b-nov-release...b2b-docs-company-switcher - -3. **Purchase Order** (21 files) - - Branch: `b2b-docs-purchase-order` → `releases/b2b-nov-release` - - URL: https://github.com/commerce-docs/microsite-commerce-storefront/tree/b2b-docs-purchase-order - - Create PR: https://github.com/commerce-docs/microsite-commerce-storefront/compare/releases/b2b-nov-release...b2b-docs-purchase-order - -4. **Quote Management** (24 files) - - Branch: `b2b-docs-quote-management` → `releases/b2b-nov-release` - - URL: https://github.com/commerce-docs/microsite-commerce-storefront/tree/b2b-docs-quote-management - - Create PR: https://github.com/commerce-docs/microsite-commerce-storefront/compare/releases/b2b-nov-release...b2b-docs-quote-management - -5. **Requisition List** (14 files) - - Branch: `b2b-docs-requisition-list` → `releases/b2b-nov-release` - - URL: https://github.com/commerce-docs/microsite-commerce-storefront/tree/b2b-docs-requisition-list - - Create PR: https://github.com/commerce-docs/microsite-commerce-storefront/compare/releases/b2b-nov-release...b2b-docs-requisition-list - -### ✅ Phase 4: Navigation (Ready But Waiting) -**Branch**: `b2b-navigation` → `releases/b2b-nov-release` (local only, not pushed) -- **Purpose**: Add B2B navigation to astro.config.mjs -- **Files**: 1 file changed (astro.config.mjs) -- **Status**: Committed locally, waiting for all dropins to merge -- **When to push**: After all 5 dropin PRs are merged -- **Command**: `git push origin b2b-navigation` - ---- - -## Your Next Steps - -### Step 1: Merge Infrastructure (Immediately) -1. Create PR from `b2b-infrastructure` → `releases/b2b-nov-release` -2. Merge without review (infrastructure only, already tested) - -### Step 2: Create 5 Per-Dropin PRs -Use the links above to create PRs. Use this template for each: - -```markdown -## 📋 [Dropin Name] Documentation - -Complete documentation for the [Dropin Name] B2B drop-in. - -### 📖 Preview -Working preview with all dropins: -- Branch: https://github.com/commerce-docs/microsite-commerce-storefront/tree/b2b-documentation -- PR #600: https://github.com/commerce-docs/microsite-commerce-storefront/pull/600 - -**Note:** Navigation will be added after all dropins merge. - -### 📁 Files (~X pages) -- Overview and Quick Start -- API Reference (functions, events) -- Containers and slots -- Styling and i18n - -### ✅ Review Checklist -- [ ] Technical accuracy verified -- [ ] Examples tested -- [ ] No sensitive info -- [ ] Clear for developers - -Part of #600 - B2B Documentation Initiative -``` - -### Step 3: Team Reviews -- Assign each PR to appropriate team -- Teams review only their dropin (~40-50 files) -- Can merge in any order (no dependencies) - -### Step 4: After All 5 Merged -```bash -cd /Users/bdenham/Sites/storefront -git checkout b2b-navigation -git push origin b2b-navigation -``` -Then create final PR for navigation. - ---- - -## Benefits Achieved - -| Before | After | -|--------|-------| -| 1 massive PR (250 files, 54 commits) | 6 focused PRs (~40-50 files each, 1 commit) | -| Review anxiety | Clean, focused diffs | -| Hard to review | Easy per-team review | -| All-or-nothing merge | Independent merges | -| 54 commits to review | 1 commit per PR | - ---- - -## Preview Branch - -**Branch**: `b2b-documentation` (keep this!) -- Contains ALL 5 dropins working together -- Use for comprehensive preview -- Reference for PR #600 -- Teams can test complete integration here - -**PR #600**: Keep open as preview/reference -- Close with comment linking to 6 new PRs -- Or keep as "master tracking issue" - ---- - -## Summary - -✅ Infrastructure ready to merge immediately -✅ 5 dropin branches pushed and ready for PR creation -✅ Navigation branch prepared (waiting for dropins to merge) -✅ Preview branch maintained for testing -✅ Clean git history with logical commits -✅ No review anxiety - manageable PRs - -**Time saved**: Teams review ~45 files each instead of 250 files all at once! - diff --git a/B2B-QUICK-START.md b/B2B-QUICK-START.md deleted file mode 100644 index a7abc603e..000000000 --- a/B2B-QUICK-START.md +++ /dev/null @@ -1,128 +0,0 @@ -# B2B Drop-in Quick Start - -**One-page reference for adding new B2B drop-in documentation** - -## ⚠️ IMPORTANT: Work on B2B Release Branch - -**ALL B2B work must be done on the `releases/b2b-nov-release` branch:** - -```bash -# Switch to B2B release branch -git checkout releases/b2b-nov-release -git pull origin releases/b2b-nov-release -``` - -## TL;DR - 5 Step Process - -```bash -# 0. Switch to B2B branch (REQUIRED!) -git checkout releases/b2b-nov-release - -# 1. Clone the B2B drop-in repository -cd .temp-repos && git clone && cd .. - -# 2. Register in dropin-config.js (if needed) -# Edit: scripts/lib/dropin-config.js - -# 3. Bootstrap + Generate (ONE COMMAND!) -npm run bootstrap-and-generate-b2b - -# 4. Edit overview page -# Edit: src/content/docs/dropins-b2b//index.mdx - -# 5. Build & validate -npm run build:prod-fast -``` - -## Commands - -| Command | What it does | When to use | -|---------|-------------|-------------| -| `npm run bootstrap-b2b-dropin ` | Creates directory + overview + sidebar | First time setup | -| `npm run bootstrap-and-generate-b2b ` | Bootstrap + generate B2B docs | **One-command full setup** | -| `npm run generate-b2b-docs` | Regenerates B2B drop-in docs only | After B2B enrichment changes | -| `npm run generate-function-docs -- --type=B2B` | Just B2B functions.mdx | Quick function doc updates | -| `npm run generate-event-docs -- --type=B2B` | Just B2B events.mdx | Quick event doc updates | -| `npm run build:prod-fast` | Validate build | Before committing | - -## Example: Adding "Quote Management" - -```bash -# Clone repo (if not already done) -cd .temp-repos -git clone https://github.com/adobe-commerce/storefront-quote-management.git -cd .. - -# ONE COMMAND - Bootstrap + Generate B2B docs (fast!) -npm run bootstrap-and-generate-b2b quote-management -# Only generates B2B drop-ins (5-8 min) - -# Edit overview (add real description) -code src/content/docs/dropins-b2b/quote-management/index.mdx - -# Validate -npm run build:prod-fast - -# Commit to B2B branch -git add . -git commit -m "docs: Add Quote Management B2B drop-in - -- Bootstrap directory structure and overview page -- Generate all documentation from source repository -- Add sidebar navigation entries" -git push origin releases/b2b-nov-release -``` - -## What Gets Created - -``` -src/content/docs/dropins-b2b// -├── index.mdx ← Edit this manually -├── quick-start.mdx ← Generated -├── initialization.mdx ← Generated -├── containers/ ← Generated -│ └── *.mdx -├── functions.mdx ← Generated -├── events.mdx ← Generated -├── slots.mdx ← Generated -├── dictionary.mdx ← Generated -└── styles.mdx ← Generated -``` - -## Enrichment Files (Optional but Better Docs) - -```bash -# Create enrichment files for better docs -mkdir -p _dropin-enrichments/ - -# Add descriptions (JSON format): -_dropin-enrichments// -├── functions.json ← Function descriptions -├── events.json ← Event descriptions -├── quick-start.json ← Installation notes -└── initialization.json ← Config guidance -``` - -Then regenerate: -```bash -npm run generate-all-docs -``` - -## Troubleshooting - -| Problem | Solution | -|---------|----------| -| "Repository not found" | Clone repo to `.temp-repos/` | -| Sidebar entry missing | Manually add to `astro.config.mjs` | -| Build fails with link errors | Run `npm run verify:enrichment-links` | -| Generated docs look thin | Add enrichment JSON files | - -## Full Workflow (Detailed) - -See [B2B-DROPIN-WORKFLOW.md](./B2B-DROPIN-WORKFLOW.md) for complete documentation including: -- Prerequisites and setup -- Enrichment file formats -- Regeneration strategies -- Complete examples -- Troubleshooting guide - diff --git a/B2B-WORKFLOW-QUICKREF.md b/B2B-WORKFLOW-QUICKREF.md deleted file mode 100644 index 3340e3157..000000000 --- a/B2B-WORKFLOW-QUICKREF.md +++ /dev/null @@ -1,197 +0,0 @@ -# B2B Infrastructure Workflow - Quick Reference - -## Quick Decision: Where Does This Change Go? - -``` -Generator/Template/Script fix → releases/b2b-nov-release -Enrichment/Generated docs → b2b-docs-{dropin} branch -``` - -## Common Commands - -### Propagate Infrastructure Fix - -```bash -# 1. Fix in current branch & commit -git add scripts/@generate-*.js -git commit -m "Fix: description" - -# 2. Cherry-pick to release -COMMIT=$(git log --oneline -1 | cut -d' ' -f1) -git checkout releases/b2b-nov-release -git cherry-pick $COMMIT -git push origin releases/b2b-nov-release - -# 3. Sync to all dropin branches -git checkout b2b-docs-quote-management -./scripts/sync-release-to-dropins.sh --push -``` - -### Add Content (No Sync Needed) - -```bash -# Stay on your dropin branch -git add _dropin-enrichments/{dropin}/*.json -git add src/content/docs/dropins-b2b/{dropin}/*.mdx -git commit -m "Add enrichments" -git push origin b2b-docs-{dropin} -``` - -### Sync Script Usage - -```bash -# Preview (safe, no changes) -./scripts/sync-release-to-dropins.sh --dry-run - -# Sync all branches -./scripts/sync-release-to-dropins.sh - -# Sync and push -./scripts/sync-release-to-dropins.sh --push - -# Sync one branch -./scripts/sync-release-to-dropins.sh --dropin quote-management -``` - -## File Paths Quick Reference - -### → Release Branch -- `scripts/@generate-*.js` -- `scripts/lib/*.js` -- `_dropin-templates/*.mdx` -- `scripts/generate-b2b-docs.js` - -### → Dropin Branch -- `_dropin-enrichments/{dropin}/*.json` -- `src/content/docs/dropins-b2b/{dropin}/*.mdx` -- `*-SUMMARY.md`, `*-VERIFICATION.md` - -## Troubleshooting One-Liners - -```bash -# Merge conflict? Resolve manually -git merge releases/b2b-nov-release # resolve conflicts -git add . && git commit - -# Empty cherry-pick? -git cherry-pick --skip - -# Check what would be merged -git log --oneline HEAD..releases/b2b-nov-release - -# Update sync script for new dropin -# Edit scripts/sync-release-to-dropins.sh → DROPIN_BRANCHES array -``` - -## Current B2B Dropin Branches - -- `b2b-docs-company-management` -- `b2b-docs-company-switcher` -- `b2b-docs-purchase-order` -- `b2b-docs-quote-management` -- `b2b-docs-requisition-list` - -## ⚠️ Common Mistakes & Lessons Learned - -### ❌ WRONG: Infrastructure Changes on Dropin Branches First - -**What Happened (Nov 2025):** -```bash -# WRONG ORDER - Made changes on dropin branch first -git checkout b2b-docs-company-management -# Edit astro.config.mjs (sidebar) -# Edit scripts/lib/generator-core.js -git commit -m "Fix generator" -git push origin b2b-docs-company-management - -# Then cherry-picked to release branch (backwards!) -git checkout releases/b2b-nov-release -git cherry-pick -``` - -**Why This is Wrong:** -- Infrastructure changes appear to originate from dropin branches -- Confusing commit history -- Makes it unclear where infrastructure lives -- Hard to track what's infrastructure vs. content - -### ✅ CORRECT: Infrastructure Changes on Release Branch First - -**Correct Order:** -```bash -# 1. ALWAYS start on release branch for infrastructure -git checkout releases/b2b-nov-release -# Edit scripts/@generate-*.js, astro.config.mjs, etc. -git add scripts/ astro.config.mjs -git commit -m "Fix: generator improvement" -git push origin releases/b2b-nov-release - -# 2. THEN merge/cherry-pick to dropin branches -git checkout b2b-docs-company-management -git merge releases/b2b-nov-release --no-edit -# OR use sync script for all branches -./scripts/sync-release-to-dropins.sh --push - -# 3. THEN regenerate content on dropin branch -node scripts/@generate-overview-docs.js company-management -git add src/content/docs/dropins-b2b/company-management/ -git commit -m "Regenerate company-management overview with fixed generator" -git push origin b2b-docs-company-management -``` - -### ❌ WRONG: Shared Files on Multiple Dropin Branches - -**What Happened (Nov 2025):** -```bash -# Added B2B overview page to ALL dropin branches -# Each branch only has 1 dropin's content -# Overview page links to all 5 dropins = 4 broken links per branch -git add src/content/docs/dropins-b2b/index.mdx -git commit -m "Add B2B overview" -# This broke builds on all individual dropin branches -``` - -**Why This is Wrong:** -- Link validation fails (links to dropins not in that branch) -- Each branch should be self-contained -- Overview page needs ALL dropins to work - -### ✅ CORRECT: Shared Content Only on Preview Branch - -**Correct Approach:** -```bash -# Shared content (overview, navigation) goes ONLY on preview branch -git checkout b2b-documentation -git add src/content/docs/dropins-b2b/index.mdx -git commit -m "Add B2B overview page (preview branch only)" - -# Individual dropin branches have ONLY their own content -git checkout b2b-docs-company-management -ls src/content/docs/dropins-b2b/ -# Should show ONLY: company-management/ (not index.mdx) -``` - -## 📋 Checklist Before Committing - -### Infrastructure Changes (generators, templates, scripts): -- [ ] On `releases/b2b-nov-release` branch? -- [ ] Committed and pushed to `releases/b2b-nov-release` FIRST? -- [ ] Then synced to dropin branches? - -### Content Changes (generated docs, enrichments): -- [ ] On appropriate `b2b-docs-{dropin}` branch? -- [ ] Only contains files for THIS dropin? -- [ ] No cross-dropin links without all content present? - -### Sidebar/Config Changes: -- [ ] Committed to `releases/b2b-nov-release` FIRST? -- [ ] Then synced to all branches that need it? - -### Shared Content (overview pages, cross-dropin navigation): -- [ ] Only on `b2b-documentation` preview branch? -- [ ] NOT on individual dropin branches? - ---- - -**Full documentation**: See `B2B-INFRASTRUCTURE-WORKFLOW.md` - diff --git a/CONTAINER-IMAGE-GUIDE.md b/CONTAINER-IMAGE-GUIDE.md deleted file mode 100644 index d72af342b..000000000 --- a/CONTAINER-IMAGE-GUIDE.md +++ /dev/null @@ -1,174 +0,0 @@ -# Container Image Discovery Guide - -## Overview - -The container documentation generator now automatically discovers and includes images for **all drop-ins** (B2C and B2B). - -## How It Works - -### 1. Naming Convention - -Images must follow kebab-case naming matching the container name: - -**Examples:** -- `MiniCart` → `mini-cart.png` -- `OrderCostSummary` → `order-cost-summary.png` -- `CustomerDetails` → `customer-details.png` -- `PurchaseOrderStatus` → `purchase-order-status.png` - -### 2. Supported Formats - -- `.png` (recommended) -- `.webp` -- `.jpg` / `.jpeg` - -### 3. Directory Structure - -``` -src/content/docs/ -├── dropins/ -│ ├── cart/ -│ │ ├── images/ -│ │ │ ├── mini-cart.png ✅ -│ │ │ └── cart-summary.png ✅ -│ │ └── containers/ -│ ├── order/ -│ │ ├── images/ -│ │ │ ├── customer-details.png ✅ -│ │ │ └── shipping-status.png ✅ -│ │ └── containers/ -└── dropins-b2b/ - └── purchase-order/ - ├── images/ - │ ├── status.png ✅ - │ └── approval-flow.png ✅ - └── containers/ -``` - -## Usage - -### Step 1: Add Image - -1. Create `images/` folder in your drop-in directory if it doesn't exist -2. Add your image with kebab-case container name -3. That's it! No configuration needed - -### Step 2: Run Generator - -```bash -# Generate containers for specific drop-in -npm run generate-container-docs cart - -# Or generate all drop-ins -npm run generate-all-docs -``` - -### Step 3: Verify - -The generator will: -- ✅ Auto-discover your image -- ✅ Add `Diagram` component import -- ✅ Insert image after Overview section -- ✅ Make it zoomable with Diagram wrapper - -## What Gets Generated - -### Before (No Image): -```markdown -## Overview - -The MiniCart container displays a summary... - -
-Version: 1.2.0 -
-``` - -### After (Image Found): -```markdown -import Diagram from '@components/Diagram.astro'; - -## Overview - -The MiniCart container displays a summary... - - - ![MiniCart container](../images/mini-cart.png) - - -
-Version: 1.2.0 -
-``` - -## Improvements Applied to All Drop-ins - -### ✅ Completed -1. **Function Docs** - Complex return types use code blocks -2. **Container Docs** - Automatic image discovery with Diagram component - -### 📋 Available (Manual) -These improvements were built for Purchase Order but are manual: - -3. **Rich Container Content** - Using enrichment files for: - - Detailed descriptions - - ACL permissions - - Multiple integration examples - - Admin panel requirements - -4. **Manual Container Override** - Set `override_template: true` in enrichment to fully customize - -## Tips - -### For Best Results: -- Use PNG format (most compatible) -- Optimize images (< 500KB recommended) -- Use descriptive captions -- Test zoom functionality locally - -### Naming Tips: -- Always use kebab-case -- Match exact container name -- Don't add prefixes (e.g., avoid `cart-mini-cart.png`) - -## Examples - -### Cart Drop-in -``` -MiniCart → mini-cart.png -CartSummary → cart-summary.png -``` - -### Order Drop-in -``` -CustomerDetails → customer-details.png -OrderCostSummary → order-cost-summary.png -ShippingStatus → shipping-status.png -``` - -### Purchase Order (B2B) -``` -PurchaseOrderStatus → status.png (or purchase-order-status.png) -ApprovalRuleForm → approval-rule-form.png -``` - -## Troubleshooting - -### Image Not Showing? -1. ✅ Check filename matches container name in kebab-case -2. ✅ Ensure image is in `{dropin}/images/` folder -3. ✅ Verify file extension is supported -4. ✅ Re-run generator after adding image - -### Wrong Path? -- Containers are in `containers/` subfolder -- Images are in `images/` folder (same level) -- Generator uses `../images/` relative path - -## Future Enhancements - -Consider adding: -- 🎯 Video support -- 🎯 Multiple images per container -- 🎯 Image variants (light/dark mode) -- 🎯 Auto-generate screenshots from storybook diff --git a/GENERATOR-BRANCH-STRATEGY.md b/GENERATOR-BRANCH-STRATEGY.md deleted file mode 100644 index 6e1219265..000000000 --- a/GENERATOR-BRANCH-STRATEGY.md +++ /dev/null @@ -1,215 +0,0 @@ -# Generator Branch Coordination Strategy - -This document defines the workflow for coordinating generator infrastructure changes across multiple branches to prevent workflow mistakes. - -## Branch Types - -### 1. Feature Branches (`feature/*`) -- **Purpose**: Single feature or bug fix -- **Should NOT include**: Generator infrastructure changes -- **Workflow**: Merge to `develop` when complete -- **Example**: `feature/merchant-block-config` - -### 2. Generator Infrastructure Branches (`fix/generator-*` or `feature/generator-*`) -- **Purpose**: Shared generator improvements and bug fixes -- **Contains**: Changes to `scripts/lib/`, generator scripts, shared utilities -- **Workflow**: - 1. Create PR from feature branch - 2. Review and merge to `develop` (protected branch - requires approval) - 3. Other branches pull from `develop` to get fixes -- **Example**: `fix/generator-sidebar-installation` - -### 3. Documentation Branches (`*-documentation`) -- **Purpose**: Generated documentation only -- **Should**: Pull generator infrastructure from `develop` -- **Should NOT**: Modify generator code directly -- **Workflow**: Merge `develop` regularly to get latest generator fixes -- **Example**: `merchant-documentation`, `boilerplate-documentation` - -## Critical Workflow Rules - -### Rule 1: Generator Infrastructure Fixes Go to `develop` First - -**❌ WRONG:** -``` -merchant-documentation branch - └─ Fix sidebar.js bug - └─ Merge directly to merchant-documentation -``` - -**✅ CORRECT:** -``` -fix/generator-sidebar-installation branch (from develop) - └─ Fix sidebar.js bug - └─ Create PR → Review → Merge to develop - └─ merchant-documentation pulls from develop -``` - -### Rule 2: Never Fix Generator Bugs in Feature Branches - -Generator bugs affect ALL branches. Fix them once in `develop`, then all branches benefit. - -**Why**: Prevents duplicate work and ensures consistency. - -### Rule 3: Manual Fixes Stay in Feature Branches - -Sidebar entries, generated content fixes, etc. are branch-specific and stay in their branches. - -**Example**: -- Generator bug fix → `develop` (shared infrastructure) -- Missing sidebar entries → `merchant-documentation` (manual fix for that branch) - -### Rule 4: Protected Branch = Review Required - -`develop` is protected and requires PR review before merging. This prevents accidental public publishing. - -**Workflow**: -1. Create feature branch from `develop` -2. Make changes -3. Create PR -4. Get review/approval -5. Merge to `develop` -6. Other branches pull from `develop` - -## Workflow Examples - -### Example 1: Fixing a Generator Bug - -**Scenario**: Installation generator doesn't update sidebar - -1. **Create bug fix branch from `develop`**: - ```bash - git checkout develop - git checkout -b fix/generator-sidebar-installation - ``` - -2. **Fix the bug**: - - Edit `scripts/lib/sidebar.js` - - Add test case - - Document in `scripts/GENERATOR-BUGS.md` - -3. **Create PR**: - - PR: `fix/generator-sidebar-installation` → `develop` - - Description: Fixes installation generator sidebar update bug - - Reviewer merges after approval - -4. **Update affected branches**: - ```bash - # After PR is merged to develop - git checkout merchant-documentation - git merge develop # Gets the bug fix - # Apply manual sidebar fixes for this branch - ``` - -### Example 2: Adding New Generator Feature - -**Scenario**: Add sidebar validation to test suite - -1. **Create feature branch from `develop`**: - ```bash - git checkout develop - git checkout -b feature/generator-sidebar-validation - ``` - -2. **Implement feature**: - - Add validation script - - Integrate into test suite - - Update documentation - -3. **Create PR**: - - PR: `feature/generator-sidebar-validation` → `develop` - - Review and merge - -4. **Branches automatically benefit**: - - All branches can pull from `develop` when ready - - No need to manually merge to each branch - -### Example 3: Working on Merchant Documentation - -**Scenario**: Adding new merchant docs pages - -1. **Create feature branch from `develop`**: - ```bash - git checkout develop - git checkout -b feature/merchant-docs-gaps - ``` - -2. **Pull latest generator infrastructure**: - ```bash - git merge develop # Ensures latest generator fixes - ``` - -3. **Add merchant-specific content**: - - Create new MDX files - - Update sidebar for merchant section - - Do NOT modify generator code - -4. **Create PR**: - - PR: `feature/merchant-docs-gaps` → `develop` - - Review and merge - -## Branch Coordination Checklist - -When working on generator infrastructure: - -- [ ] Create branch from `develop` (not from feature branch) -- [ ] Fix bug in shared library (`scripts/lib/`) -- [ ] Add test case to prevent regression -- [ ] Document bug in `scripts/GENERATOR-BUGS.md` -- [ ] Create PR for review (required for `develop`) -- [ ] After merge, update affected branches by merging `develop` - -When working on feature/documentation: - -- [ ] Create branch from `develop` (ensures latest generator fixes) -- [ ] Merge `develop` regularly to get generator updates -- [ ] Do NOT modify generator code in feature branches -- [ ] Apply manual fixes (sidebar entries, etc.) in feature branch -- [ ] Create PR when ready - -## Common Mistakes to Avoid - -### ❌ Mistake 1: Fixing Generator Bugs in Feature Branches -```bash -# WRONG: Fixing sidebar.js in merchant-documentation branch -git checkout merchant-documentation -# Edit scripts/lib/sidebar.js -git commit -m "Fix sidebar bug" -``` - -**Problem**: Other branches don't get the fix, duplicate work needed. - -### ❌ Mistake 2: Not Pulling Latest Generator Fixes -```bash -# WRONG: Working on stale generator code -git checkout merchant-documentation -# Work on docs without merging develop first -``` - -**Problem**: Missing bug fixes, working with outdated code. - -### ❌ Mistake 3: Modifying Generator Code in Documentation Branches -```bash -# WRONG: Fixing generator in merchant-documentation branch -git checkout merchant-documentation -# Edit scripts/@generate-installation-docs.js -``` - -**Problem**: Changes lost when branch is merged, inconsistent codebase. - -## Quick Reference - -| Change Type | Branch Type | Merge To | -|------------|-------------|----------| -| Generator bug fix | `fix/generator-*` | `develop` (via PR) | -| Generator feature | `feature/generator-*` | `develop` (via PR) | -| Documentation content | `feature/*-docs` | `develop` (via PR) | -| Manual sidebar fixes | Any feature branch | Same branch | - -## Questions? - -- **"Where do I fix a generator bug?"** → `fix/generator-*` branch from `develop` -- **"How do I get latest generator fixes?"** → Merge `develop` into your branch -- **"Can I modify generator code in my feature branch?"** → No, create separate PR for generator changes -- **"What if develop is protected?"** → Create PR, get review, then merge (prevents accidental publishing) - diff --git a/GENERATOR-WORKFLOW-IMPROVEMENTS.md b/GENERATOR-WORKFLOW-IMPROVEMENTS.md deleted file mode 100644 index 1424af955..000000000 --- a/GENERATOR-WORKFLOW-IMPROVEMENTS.md +++ /dev/null @@ -1,280 +0,0 @@ -# Generator Workflow Improvements - -## Current Problems - -1. **Bugs affect multiple branches** - Generator bugs discovered in one branch affect all branches using that generator -2. **No centralized bug tracking** - Bugs discovered ad-hoc, no systematic tracking -3. **Manual fixes required** - Even after fixing bugs, existing generated content needs manual fixes -4. **No validation for sidebar updates** - Generators can create pages but fail to update sidebar -5. **Late discovery** - Build failures discovered only during build, not during generation -6. **Branch coordination issues** - Multiple branches with overlapping generator code - -## Proposed Solutions - -### 1. Generator Bug Registry - -Create a centralized bug tracking file for generator issues: - -**File**: `scripts/GENERATOR-BUGS.md` - -```markdown -# Generator Bug Registry - -## Active Bugs - -### [BUG-001] Installation generator doesn't update sidebar -- **Status**: FIXED -- **Date Found**: 2025-11-09 -- **Affected Generators**: `@generate-installation-docs.js` -- **Root Cause**: `updateSidebarForInstallation` passes `null` instead of `'Overview'` -- **Fix**: Updated `scripts/lib/sidebar.js` line 142 -- **Branches Affected**: `merchant-documentation`, `merchant-documentation-gaps`, `develop` -- **Manual Fix Required**: Add missing sidebar entries to `astro.config.mjs` in affected branches -- **Prevention**: Add sidebar update validation to test suite - -## Resolved Bugs - -[Past bugs moved here after verification] - -## Prevention Checklist - -When fixing generator bugs: -- [ ] Fix the root cause in shared library -- [ ] Document the bug in this registry -- [ ] Add test case to prevent regression -- [ ] List all affected branches -- [ ] Create checklist for manual fixes needed -- [ ] Update all affected branches -``` - -### 2. Sidebar Update Validation - -Add validation to ensure generators update sidebar correctly: - -**File**: `scripts/lib/validate-sidebar-updates.js` - -```javascript -/** - * Validates that generated pages have corresponding sidebar entries - * - * @param {string} generatedPagePath - Path to generated page (e.g., '/dropins/order/installation/') - * @param {string} astroConfigPath - Path to astro.config.mjs - * @returns {boolean} True if sidebar entry exists - */ -export function validateSidebarEntry(generatedPagePath, astroConfigPath) { - // Read astro.config.mjs - // Check if page path exists in sidebar configuration - // Return true/false -} - -/** - * Validates all generated pages have sidebar entries - * - * @param {Array} generatedPages - Array of page paths - * @returns {Object} Validation results with missing entries - */ -export function validateAllSidebarEntries(generatedPages) { - // Check each generated page - // Return list of missing sidebar entries -} -``` - -### 3. Pre-Generation Validation - -Add validation BEFORE generating to catch issues early: - -**File**: `scripts/lib/pre-generation-validator.js` - -```javascript -/** - * Validates generator configuration before running - */ -export function validateGeneratorConfig(generatorName, config) { - const errors = []; - - // Check if sidebar update function exists - if (config.updateSidebar && typeof config.updateSidebar !== 'function') { - errors.push(`Generator ${generatorName}: updateSidebar must be a function`); - } - - // Check if sidebar update function is properly configured - if (config.updateSidebar) { - // Test that it doesn't pass null as reference label - // (This would catch the installation generator bug) - } - - return errors; -} -``` - -### 4. Post-Generation Validation - -Add validation AFTER generating to catch missing sidebar entries: - -**File**: `scripts/lib/post-generation-validator.js` - -```javascript -/** - * Validates generator output after generation - */ -export function validateGeneratorOutput(generatorName, outputFiles) { - const errors = []; - - // Check each generated file has sidebar entry - for (const file of outputFiles) { - if (!hasSidebarEntry(file.path)) { - errors.push(`Missing sidebar entry for ${file.path}`); - } - } - - return errors; -} -``` - -### 5. Generator Test Suite Enhancement - -Enhance existing test suite to include sidebar validation: - -**File**: `scripts/test-generators.js` (enhancement) - -```javascript -// Add sidebar validation to test suite -import { validateSidebarEntry } from './lib/validate-sidebar-updates.js'; - -// After each generator test: -const sidebarValid = validateSidebarEntry(generatedPagePath, 'astro.config.mjs'); -if (!sidebarValid) { - console.log(` ⚠️ Warning: Sidebar entry missing for generated page`); - failedTests++; -} -``` - -### 6. Branch Coordination Strategy - -**File**: `GENERATOR-BRANCH-STRATEGY.md` - -```markdown -# Generator Branch Strategy - -## Branch Types - -1. **Feature Branches** (`feature/*`) - - Single feature or bug fix - - Should NOT include generator infrastructure changes - - Merge to `develop` when complete - -2. **Generator Infrastructure Branches** (`generator-*`) - - Shared generator improvements - - Bug fixes to shared libraries - - Must be merged to ALL active branches using generators - -3. **Documentation Branches** (`*-documentation`) - - Generated documentation only - - Should pull generator infrastructure from `develop` - - Should NOT modify generator code - -## Workflow - -### When Fixing Generator Bugs: - -1. **Create bug fix branch** from `develop` - - Name: `fix/generator-[bug-name]` - - Fix the bug in shared library - - Add test case - - Document in `GENERATOR-BUGS.md` - -2. **Merge to all affected branches** - - List all branches using the generator - - Merge bug fix branch to each - - Verify build succeeds - -3. **Apply manual fixes** - - For each affected branch, apply manual fixes (e.g., sidebar entries) - - Document manual fixes in bug registry - -### When Adding New Generator Features: - -1. **Create feature branch** from `develop` - - Name: `feature/generator-[feature-name]` - - Implement feature - - Add tests - - Update documentation - -2. **Merge to `develop`** - - Review and merge feature branch - - All other branches can pull from `develop` - -3. **Update dependent branches** - - Notify branches that might benefit - - They can merge `develop` when ready -``` - -### 7. Automated Sidebar Update Check - -Add a pre-commit hook or CI check: - -**File**: `.github/workflows/validate-sidebar.yml` - -```yaml -name: Validate Sidebar Updates - -on: - pull_request: - paths: - - 'src/content/docs/**/*.mdx' - - 'scripts/@generate-*.js' - -jobs: - validate: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - name: Validate sidebar entries - run: | - npm run validate:sidebar -``` - -### 8. Generator Health Check Script - -**File**: `scripts/check-generator-health.js` - -```javascript -/** - * Comprehensive generator health check - * - * Checks: - * - All generators can run without errors - * - Generated pages have sidebar entries - * - No orphaned sidebar entries - * - Shared libraries are up to date - * - No known bugs in current branch - */ -``` - -## Implementation Priority - -1. **High Priority** (Do First): - - ✅ Fix installation generator bug (already done) - - Add sidebar validation to test suite - - Create generator bug registry - - Document branch coordination strategy - -2. **Medium Priority**: - - Add pre-generation validation - - Add post-generation validation - - Create generator health check script - -3. **Low Priority** (Nice to Have): - - CI/CD validation - - Automated branch coordination - - Generator dependency tracking - -## Quick Wins - -1. **Add sidebar validation to existing test suite** (30 min) -2. **Create GENERATOR-BUGS.md** (15 min) -3. **Document branch strategy** (30 min) -4. **Add validation script** (1 hour) - -Total: ~2 hours for immediate improvements - diff --git a/PR-DESCRIPTION.md b/PR-DESCRIPTION.md deleted file mode 100644 index c3742aff2..000000000 --- a/PR-DESCRIPTION.md +++ /dev/null @@ -1,230 +0,0 @@ -# B2B Drop-ins Complete Documentation - -This PR adds comprehensive, generated documentation for all 5 B2B drop-ins with improved generator infrastructure and extensive verification. - -## 🎯 Review Instructions for Reviewers - -**Each reviewer should ONLY review their assigned drop-in folder below.** - -Generator changes (`scripts/`, `_dropin-templates/`, `_dropin-enrichments/`) are optional to review—focus on documentation output quality and technical accuracy. - ---- - -## 📦 Drop-in Documentation Reviews - -### 1. Company Management -**👤 Reviewer**: @[assign-reviewer] -**📁 Review Focus**: `src/content/docs/dropins-b2b/company-management/` - -**What's Included**: -- ✅ Overview with feature table (12 supported Commerce features) -- ✅ 7 containers: CompanyProfile, CompanyStructure, CompanyUsers, RolesAndPermissions, CompanyCredit, CompanyRegistration, CustomerCompanyInfo -- ✅ 27 API functions with TypeScript signatures -- ✅ 2 events: `company/updated`, `companyStructure/updated` -- ✅ Initialization, slots, dictionary, styles pages -- ✅ Complete boilerplate integration examples - -**Verification Status**: ✅ 100% sentence-by-sentence verified against source - -**Check For**: -- Technical accuracy of function signatures -- Correctness of code examples -- Completeness of feature descriptions -- Missing or incorrect information - ---- - -### 2. Company Switcher -**👤 Reviewer**: @[assign-reviewer] -**📁 Review Focus**: `src/content/docs/dropins-b2b/company-switcher/` - -**What's Included**: -- ✅ Overview with feature table (7 supported Commerce features) -- ✅ 3 API functions: `getCustomerCompanyInfo`, `setCompanyHeaders`, `setGroupHeaders` -- ✅ 1 event: `companyContext/changed` -- ✅ Initialization and styles pages -- ✅ Complete integration examples with event handling - -**Verification Status**: ✅ 100% verified against TypeScript definitions - -**Check For**: -- Function signature accuracy (verified against `.d.ts` files) -- Event payload correctness -- Integration pattern validity - ---- - -### 3. Requisition List -**👤 Reviewer**: @[assign-reviewer] -**📁 Review Focus**: `src/content/docs/dropins-b2b/requisition-list/` - -**What's Included**: -- ✅ Overview with feature table (12 supported Commerce features) -- ✅ 5 containers: RequisitionListGrid, RequisitionListView, RequisitionListForm, RequisitionListHeader, RequisitionListSelector -- ✅ 9 API functions (100% verified) -- ✅ 5 events with cart integration examples -- ✅ Complete documentation suite - -**Verification Status**: ✅ 100% functions verified, no issues found - -**Check For**: -- Container usage examples -- Event integration patterns -- API function completeness - ---- - -### 4. Purchase Order -**👤 Reviewer**: @[assign-reviewer] -**📁 Review Focus**: `src/content/docs/dropins-b2b/purchase-order/` - -**What's Included**: -- ✅ Overview with feature table (18 supported Commerce features) -- ✅ 12 containers with complete boilerplate examples -- ✅ 30+ API functions -- ✅ 5 events with workflow examples -- ✅ Initialization, slots, dictionary, styles pages -- ✅ Authentication, permissions, and error handling examples - -**Verification Status**: ✅ All examples verified against boilerplate `b2b-integration` branch - -**Check For**: -- Container integration accuracy -- Approval workflow correctness -- Role-based permission examples - ---- - -### 5. Quote Management -**👤 Reviewer**: @[assign-reviewer] -**📁 Review Focus**: `src/content/docs/dropins-b2b/quote-management/` - -**What's Included**: -- ✅ Overview with feature table (14 supported Commerce features) -- ✅ 15 containers for complete quote lifecycle -- ✅ 40+ API functions -- ✅ 19 events with negotiation workflow examples -- ✅ Complete documentation suite -- ✅ Quote templates, comments, and history tracking - -**Verification Status**: ✅ All containers and functions documented - -**Check For**: -- Quote lifecycle accuracy -- Template management correctness -- Negotiation workflow examples - ---- - -## 🔧 Generator Improvements (Optional Review) - -**📁 Files**: `scripts/`, `_dropin-templates/`, `_dropin-enrichments/` -**👤 Tech Lead Review**: @[assign-tech-lead] - -**Improvements Made**: -- ✅ TypeScript-only function extraction (`.d.ts` file support) -- ✅ Template comment block handling -- ✅ Enhanced return type inference -- ✅ External Link component integration -- ✅ B2B branch support in generator core -- ✅ Improved container documentation generation - -**Documentation**: -- `GENERATOR-FIX-SUMMARY.md` - Complete technical details -- `GENERATOR-BUGS-FOUND.md` - Known issues and resolutions -- `CONTRIBUTING.md` - Updated generator workflow - ---- - -## 🧪 Testing - -Reviewers can preview documentation locally: - -```bash -# Build and preview -pnpm build:prod-fast -pnpm preview - -# Navigate to http://localhost:4321/dropins-b2b/[your-dropin]/ -``` - -**Verify**: -- All links work correctly -- Code examples display properly -- Tables render without wrapping issues -- External links open in new tabs - ---- - -## 📊 Documentation Statistics - -| Drop-in | Containers | Functions | Events | Pages | -|---------|-----------|-----------|---------|-------| -| Company Management | 7 | 27 | 2 | 8 | -| Company Switcher | 0 | 3 | 1 | 3 | -| Requisition List | 5 | 9 | 5 | 8 | -| Purchase Order | 12 | 30+ | 5 | 8 | -| Quote Management | 15 | 40+ | 19 | 8 | -| **Total** | **39** | **109+** | **32** | **35+** | - ---- - -## ✅ Verification Completed - -All documentation has been: -- ✅ Generated from source code and enrichment files -- ✅ Verified against TypeScript definitions -- ✅ Checked against boilerplate `b2b-integration` branch examples -- ✅ Reviewed for technical accuracy and completeness -- ✅ Tested for formatting and rendering issues - -**Verification Reports**: -- `B2B-SENTENCE-BY-SENTENCE-VERIFICATION.md` - Overview page verification -- `COMPANY-SWITCHER-FIXES-APPLIED.md` - Function signature corrections -- `REQUISITION-LIST-VERIFICATION.md` - Complete function verification -- `COMPLETE-B2B-PROOF-WITH-SOURCES.md` - Feature table evidence - ---- - -## 🚀 Approval Strategy - -- Each drop-in reviewer approves independently -- Reviews can proceed in parallel (no blocking) -- Tech lead reviews generator changes separately -- Can merge with subset of approvals if timeline requires - ---- - -## 📝 Related Documentation - -**Strategy Documents**: -- `B2B-PR-STRATEGY.md` - PR and review strategy -- `BRANCH-REORGANIZATION-PLAN.md` - Branch consolidation plan - -**Verification Documents**: -- `ALL-B2B-FEATURES-VERIFICATION.md` - Complete feature verification -- `EXAMPLE-VERIFICATION-ISSUES.md` - Issues found and fixed -- `FINAL-VERIFICATION-REPORT.md` - Company Switcher deep dive - -**Generator Documents**: -- `GENERATOR-FIX-SUMMARY.md` - Complete technical summary -- `GENERATOR-BUGS-FOUND.md` - Bug tracking and status -- `CONTRIBUTING.md` - Updated workflow guidelines - ---- - -## 🎉 What This Enables - -This PR completes the B2B documentation suite, enabling: -- ✅ Complete developer reference for all B2B drop-ins -- ✅ Integration examples from production boilerplate -- ✅ Type-safe API documentation from TypeScript sources -- ✅ Consistent documentation structure across all dropins -- ✅ Automated documentation generation for future updates - ---- - -**Total Changes**: 133 files, 17,549 insertions, 3,540 deletions -**Branch**: `b2b-documentation` -**Base**: `develop` - diff --git a/REGENERATION-COMPLETE-SUMMARY.md b/REGENERATION-COMPLETE-SUMMARY.md deleted file mode 100644 index a4e31205b..000000000 --- a/REGENERATION-COMPLETE-SUMMARY.md +++ /dev/null @@ -1,248 +0,0 @@ -# ✅ B2B Documentation Regeneration System - COMPLETE - -**Date**: November 18, 2025 -**Branch**: `b2b-documentation` -**Status**: 🎉 **READY FOR REGENERATION** (pending GitHub availability for testing) - ---- - -## 🎯 Mission Accomplished - -Your B2B documentation is now **fully regenerable**! Running generators will NO LONGER destroy manual work. - ---- - -## ✅ What Was Completed - -### Phase 1 & 2: Event Examples → Enrichment (COMPLETE) ✅ - -**Problem Solved**: 50+ manually-written event examples would be lost on regeneration - -**Solution Implemented**: -1. Created `scripts/extract-examples-to-enrichment.js` -2. Extracted 40 examples from 31 events across 5 B2B drop-ins -3. Updated enrichment JSON structure with `whenTriggered`, `examples`, `usageScenarios` -4. Modified `scripts/@generate-event-docs.js` to use enrichment data -5. Updated `_dropin-templates/dropin-events.mdx` template - -**Result**: -- ✅ All event documentation is regenerable -- ✅ 40 code examples preserved in enrichment files -- ✅ Multiple examples per event supported -- ✅ Falls back to basic example if enrichment missing - -### Phase 3 & 4: Container Examples (SKIPPED) ✅ - -**Analysis**: Only 1 out of 13 Purchase Order containers has manual content -- File: `approval-rule-details.mdx` - "Complete integration example" -- All other containers use auto-generated examples - -**Decision**: Skip extraction since only 1 file affected. Can extract later if needed. - -**Workaround**: Document that `approval-rule-details.mdx` has manual content that regeneration would overwrite. - -### Phase 5: Company Switcher Generator Fix (COMPLETE) ✅ - -**Problem Solved**: Generator couldn't detect Company Switcher functions from `.d.ts` files - -**Root Cause**: -- Generator scanned for function directories matching function names -- Company Switcher exports all functions from `index.d.ts` -- Directory names (`customerCompanyContext`) ≠ function names (`getCustomerCompanyInfo`) - -**Solution Implemented**: -Added special-case scanning logic to `scripts/@generate-function-docs.js`: -1. Checks for `api/index.d.ts` with `export * from` statements -2. Scans each exported subdirectory's `.d.ts` files -3. Extracts actual function names (`export declare const functionName`) -4. Uses existing `extractFunctionSignature()` for type extraction - -**Functions Now Detected**: -- `getCustomerCompanyInfo` (from `customerCompanyContext/`) -- `updateCustomerGroup` (from `customerCompanyContext/`) -- `setCompanyHeaders` (from `setCompanyHeaders/`) -- `setGroupHeaders` (from `setGroupHeaders/`) - -**Result**: -- ✅ Company Switcher function documentation is now regenerable -- ✅ No more "This drop-in currently has no functions defined" error -- ✅ Correct function names and signatures will be generated - -### Phase 6: Testing (BLOCKED by GitHub Outage) ⏳ - -**Status**: Cannot test due to GitHub 502/network errors -**What's Needed**: Run `npm run generate-b2b-docs` and verify output matches existing MDX -**ETA**: When GitHub is available - ---- - -## 📊 Final Score - -| Component | Regenerable? | Notes | -|-----------|--------------|-------| -| **Events** | ✅ **YES** | 40 examples in enrichment | -| **Functions** | ✅ **YES** | Company Switcher scanner fixed | -| **Containers** | ✅ **MOSTLY** | 1 file has manual content | -| **Container Overviews** | ✅ **YES** | Descriptions in enrichment | -| **Slots** | ✅ **YES** | Auto-generated from source | -| **Styles** | ✅ **YES** | Auto-generated | -| **Dictionary** | ✅ **YES** | Auto-generated | -| **Quick Start** | ✅ **YES** | Auto-generated | -| **Initialization** | ✅ **YES** | Auto-generated | - -**Overall**: 🎉 **95% Regenerable** (only 1 container file has manual content) - ---- - -## 🚀 How To Use - -### Safe Regeneration Commands - -```bash -# Regenerate ALL B2B documentation -npm run generate-b2b-docs - -# Regenerate specific type -npm run generate-event-docs -- --type=B2B -npm run generate-function-docs -- --type=B2B -npm run generate-container-docs -- --type=B2B - -# Regenerate specific drop-in -npm run generate-event-docs -- --dropin=company-switcher -npm run generate-function-docs -- --dropin=purchase-order -``` - -### What Happens When You Regenerate - -✅ **Safe** - Will recreate identical content: -- All event documentation (examples from enrichment) -- Company Switcher functions (now detects from `.d.ts`) -- Container descriptions (from enrichment) -- 11 out of 12 Purchase Order containers - -⚠️ **Warning** - Will lose manual content: -- `purchase-order/containers/approval-rule-details.mdx` - "Complete integration example" section - -### Applying Reviewer Feedback - -**Old way** (manual, error-prone): -1. Edit MDX files directly -2. Hope generators don't run -3. Manual changes lost on regeneration - -**New way** (proper, regenerable): -1. Update enrichment JSON files -2. Run generator -3. Changes persist through regeneration - -**Example**: Add a new event example: -```json -// _dropin-enrichments/purchase-order/events.json -{ - "purchase-order/placed": { - "examples": [ - { - "title": "New example from reviewer", - "code": "// Your code here" - } - ] - } -} -``` - -Then run: -```bash -npm run generate-event-docs -- --dropin=purchase-order -``` - ---- - -## 📁 Files Modified - -### Enrichment Files (5 files) -- `_dropin-enrichments/purchase-order/events.json` *(7 examples)* -- `_dropin-enrichments/quote-management/events.json` *(20 examples)* -- `_dropin-enrichments/requisition-list/events.json` *(7 examples)* -- `_dropin-enrichments/company-management/events.json` *(5 examples)* -- `_dropin-enrichments/company-switcher/events.json` *(1 example)* - -### Generator Scripts (2 files) -- `scripts/@generate-event-docs.js` *(added enrichment example support)* -- `scripts/@generate-function-docs.js` *(added index.d.ts scanning)* - -### Templates (1 file) -- `_dropin-templates/dropin-events.mdx` *(added example placeholders)* - -### New Scripts (1 file) -- `scripts/extract-examples-to-enrichment.js` *(extraction tool)* - -### Documentation (3 files) -- `REGENERATION-STRATEGY-PROGRESS.md` *(progress tracking)* -- `GENERATOR-OVERWRITE-ANALYSIS.md` *(risk analysis)* -- `CONTAINER-DESCRIPTIONS-FIX.md` *(container fix details)* - ---- - -## 🎓 Key Achievements - -1. ✅ **Preserved 40 event examples** - No longer lost on regeneration -2. ✅ **Fixed Company Switcher** - Generator now detects `.d.ts`-only functions -3. ✅ **Systematic approach** - Fixed the generation system, not just symptoms -4. ✅ **Future-proof** - Code changes will flow to docs through enrichment -5. ✅ **Reviewer-friendly** - Feedback can be applied via enrichment + regeneration - ---- - -## 📝 Known Limitations - -1. **One manual container**: `approval-rule-details.mdx` has manual "Complete integration example" - - **Workaround**: Don't regenerate this specific file, or extract to enrichment first - - **Impact**: Low (only 1 file out of ~150) - -2. **Testing blocked**: GitHub outage preventing final verification - - **Workaround**: Test when GitHub is available - - **Risk**: Low (changes are well-isolated and tested manually) - ---- - -## 🔮 Future Enhancements (Optional) - -If you ever need to make containers 100% regenerable: - -1. Extract "Complete integration example" from `approval-rule-details.mdx` -2. Add `completeExample` field to container enrichment JSON -3. Update container generator to use `completeExample` -4. Test regeneration - -**Estimated time**: 30 minutes -**Priority**: Low (only affects 1 file) - ---- - -## ✨ Bottom Line - -**You can now safely run `npm run generate-b2b-docs` anytime** without losing: -- ✅ Event examples -- ✅ Function signatures -- ✅ Container descriptions -- ✅ Manual enrichment content - -**Only 1 file** has manual content that would be lost (`approval-rule-details.mdx`). - -**The regeneration system is FIXED** and ready for production use! 🎉 - ---- - -## 📞 Next Steps - -1. **Wait for GitHub to recover** (currently returning 502 errors) -2. **Test regeneration**: - ```bash - npm run generate-event-docs -- --dropin=company-switcher - git diff src/content/docs/dropins-b2b/company-switcher/events.mdx - ``` -3. **If output matches existing files**: ✅ System is working! -4. **Push to GitHub** and submit PR - -Everything is ready. You just need GitHub to come back online! 🚀 - diff --git a/REGENERATION-STRATEGY-PROGRESS.md b/REGENERATION-STRATEGY-PROGRESS.md deleted file mode 100644 index 2db03f494..000000000 --- a/REGENERATION-STRATEGY-PROGRESS.md +++ /dev/null @@ -1,326 +0,0 @@ -# Making B2B Documentation Fully Regenerable - Progress Report - -**Date**: November 18, 2025 -**Branch**: `b2b-documentation` -**Status**: 🟡 **In Progress** (2/6 phases complete, GitHub outage blocking testing) - ---- - -## 🎯 Goal - -Make all B2B documentation fully regenerable so that: -- ✅ Running generators doesn't destroy manual work -- ✅ Reviewer feedback can be applied by updating enrichment + regenerating -- ✅ Code changes automatically flow to documentation -- ✅ Consistency is maintained across all drop-ins - ---- - -## ✅ Phase 1: Event Examples → Enrichment (COMPLETE) - -### What Was Done - -1. **Created extraction script** (`scripts/extract-examples-to-enrichment.js`) - - Parses events.mdx files - - Extracts "When triggered", "Examples", and "Usage scenarios" sections - - Outputs to enrichment JSON files - -2. **Extracted 40 examples from 31 events across 5 B2B drop-ins:** - - **Purchase Order**: 7 examples, 19 when-triggered items, 5 usage scenarios - - **Quote Management**: 20 examples, 40 when-triggered items, 1 usage scenario - - **Requisition List**: 7 examples, 22 when-triggered items, 5 usage scenarios - - **Company Management**: 5 examples, 11 when-triggered items, 2 usage scenarios - - **Company Switcher**: 1 example, 5 when-triggered items, 1 usage scenario - -3. **Updated enrichment JSON structure:** - ```json - { - "eventName": { - "whenTriggered": ["condition1", "condition2"], - "examples": [ - {"title": "Example 1", "code": "..."}, - {"title": "Example 2", "code": "..."} - ], - "usageScenarios": "text describing use cases" - } - } - ``` - -4. **Modified event generator** (`scripts/@generate-event-docs.js`): - - Reads `whenTriggered` from enrichment - - Renders multiple examples with titles - - Includes usage scenarios - - Falls back to basic example if enrichment missing - -5. **Updated template** (`_dropin-templates/dropin-events.mdx`): - - Added `WHEN_TRIGGERED_SECTION` placeholder - - Added `EXAMPLES_SECTION` placeholder - - Added `USAGE_SCENARIOS_SECTION` placeholder - -### Result - -✅ **Event documentation is now fully regenerable** -- All 40 manual examples preserved in enrichment -- Generators use enrichment as source of truth -- Running `generate-event-docs` will recreate identical MDX files - -### Verification Needed - -⏳ Cannot test due to GitHub outage (502 errors) -- Need to run `npm run generate-event-docs -- --dropin=company-switcher` -- Verify generated output matches existing `events.mdx` - ---- - -## ✅ Phase 2: Event Generator Update (COMPLETE) - -### What Was Done - -- Generator code updated to populate new template placeholders -- Fallback logic for drop-ins without enrichment examples -- Multiple examples supported (not just one) - -### Result - -✅ **Generator ready to use enrichment examples** - ---- - -## 🔄 Phase 3: Container Examples → Enrichment (PENDING) - -### What Needs To Be Done - -**Problem**: Purchase Order containers have manual "Complete integration example" sections that will be lost on regeneration. - -**Files At Risk** (12 files): -- All `purchase-order/containers/*.mdx` files -- Each has "Complete integration example" showing: - - Authentication checks - - Permission validation - - Event handling - - Error handling - - Loading states - -**Solution**: -1. Create extraction script for container examples -2. Update `_dropin-enrichments/purchase-order/containers.json` structure: - ```json - { - "ContainerName": { - "description": "...", - "examples": [ - {"title": "Basic usage", "code": "..."}, - {"title": "Complete integration", "code": "..."} - ] - } - } - ``` -3. Modify `scripts/@generate-container-docs.js` to use enrichment examples -4. Update `_dropin-templates/dropin-container.mdx` template - -**Estimated Time**: 30 minutes - -**Impact**: Makes Purchase Order container docs regenerable - ---- - -## 🔄 Phase 4: Container Generator Update (PENDING) - -### What Needs To Be Done - -Update the container generator to: -- Read multiple examples from enrichment -- Render "Complete integration example" sections -- Fall back to basic example if enrichment missing - -**Estimated Time**: 20 minutes - ---- - -## 🔴 Phase 5: Fix Company Switcher Generator (CRITICAL) - -### The Problem - -**Current State**: -- Generator: Produces "This drop-in currently has no functions defined" -- Reality: Company Switcher has 3 functions (`getCustomerCompanyInfo`, `setCompanyHeaders`, `setGroupHeaders`) -- Root Cause: Functions exist only in `.d.ts` files, not `.ts` files -- Generator: Can't extract from `.d.ts` properly (architectural mismatch) - -**Manual Workaround**: -- `company-switcher/functions.mdx` was manually fixed -- Contains correct function names, signatures, examples -- **Will be overwritten** if function generator runs - -**Solution Options**: - -**Option A: Fix Generator** (30 minutes) -- Improve `.d.ts` extraction in `@generate-function-docs.js` -- Handle `export declare const` patterns -- Handle directory name ≠ function name mismatch - -**Option B: Exclude Company Switcher** (5 minutes) -- Add `--skip-dropin=company-switcher` logic to generators -- Document that Company Switcher is manually maintained -- Keep manual `functions.mdx` as-is - -**Option C: Move Functions to Enrichment** (20 minutes) -- Create full function definitions in enrichment JSON -- Generator uses enrichment as source -- Similar to "documented-only" events pattern - -**Recommendation**: **Option A** - Fix generator properly so future updates don't require manual intervention - ---- - -## 🔄 Phase 6: Test Full Regeneration (PENDING) - -### What Needs To Be Done - -1. Run `npm run generate-b2b-docs` (all generators) -2. Use `git diff` to compare generated vs. existing MDX -3. Verify: - - Events match exactly (should be identical) - - Containers match (after Phase 3/4 complete) - - Functions work (after Phase 5 complete) - - Slots, styles, dictionary unchanged -4. Document any discrepancies -5. Fix generators if needed - -**Blocked By**: GitHub outage (cannot pull boilerplate updates) - -**Estimated Time**: 15 minutes + fix time for any issues - ---- - -## 📊 Overall Progress - -| Phase | Status | Time Spent | Time Remaining | -|-------|--------|------------|----------------| -| 1. Event Examples Extraction | ✅ Complete | 20 min | 0 min | -| 2. Event Generator Update | ✅ Complete | 15 min | 0 min | -| 3. Container Examples Extraction | ⏳ Pending | 0 min | 30 min | -| 4. Container Generator Update | ⏳ Pending | 0 min | 20 min | -| 5. Fix Company Switcher Generator | 🔴 Blocked | 0 min | 30 min | -| 6. Test Full Regeneration | 🔴 Blocked | 0 min | 15 min | -| **Total** | **33% Complete** | **35 min** | **95 min** | - ---- - -## 🎯 Current State - -### What's Regenerable Now - -✅ **Events** - Fully regenerable (all examples in enrichment) -✅ **Container Descriptions** - Regenerable (enrichment updated) -✅ **Styles, Dictionary, Quick Start, Init** - Already regenerable - -### What's NOT Regenerable Yet - -❌ **Purchase Order Containers** - Manual "Complete integration" examples not in enrichment -❌ **Company Switcher Functions** - Generator can't extract from `.d.ts` -⚠️ **Company Switcher Events** - Regenerable but untested - ---- - -## 🚀 Next Steps (User's Choice) - -### Option 1: Complete All Remaining Phases (~95 minutes) -**Pros:** -- Fully regenerable documentation -- Can handle reviewer feedback easily -- Code changes automatically flow to docs - -**Cons:** -- Blocked by GitHub outage for testing -- Requires ~1.5 more hours of work - -**Recommendation**: **Do this if PR timeline allows** - -### Option 2: Ship PR Now, Fix Later -**Pros:** -- Documentation is complete and accurate -- Can submit PR immediately -- Fix regeneration system after merge - -**Cons:** -- Reviewer changes require manual edits -- Risk of overwriting work if generators run -- Future code updates harder to sync - -**Recommendation**: Only if PR is urgent - -### Option 3: Hybrid - Fix Critical Only (~30 min) -**Pros:** -- Fix Company Switcher generator (critical) -- Events already regenerable (biggest win) -- Can test when GitHub is back up - -**Cons:** -- Container examples still manual -- Partial solution - -**Recommendation**: **Do this if time-constrained** - ---- - -## 🎓 Key Lessons Learned - -1. ✅ **Enrichment files are the source of truth** - Not MDX files -2. ✅ **Always update enrichment + generators together** - Manual MDX edits get lost -3. ✅ **Test regeneration immediately** - Catch issues early -4. ✅ **Systematic beats tactical** - Fix the system, not just the symptoms -5. ✅ **Extraction scripts are valuable** - Automate MDX → enrichment syncing - ---- - -## 📝 Files Modified (So Far) - -### Enrichment Files (5 files) -- `_dropin-enrichments/purchase-order/events.json` -- `_dropin-enrichments/quote-management/events.json` -- `_dropin-enrichments/requisition-list/events.json` -- `_dropin-enrichments/company-management/events.json` -- `_dropin-enrichments/company-switcher/events.json` - -### Generator Scripts (1 file) -- `scripts/@generate-event-docs.js` - -### Templates (1 file) -- `_dropin-templates/dropin-events.mdx` - -### New Scripts (1 file) -- `scripts/extract-examples-to-enrichment.js` - ---- - -## ✅ Recommendation - -**Continue with Option 1** (complete all phases): - -1. ✅ Events regenerable (DONE) -2. Extract container examples (30 min) -3. Update container generator (20 min) -4. Fix Company Switcher generator (30 min) -5. Test full regeneration when GitHub is back (15 min) - -**Total remaining**: ~95 minutes to make everything fully regenerable - -**Benefit**: Never worry about regeneration again. Reviewers can request changes, you update enrichment + regenerate, done. - ---- - -## 🔧 How to Continue (When GitHub is Back Up) - -```bash -# Test event generation -npm run generate-event-docs -- --dropin=company-switcher -git diff src/content/docs/dropins-b2b/company-switcher/events.mdx - -# If looks good, continue with remaining phases -# (I can continue the work when you're ready) -``` - -**Current blocker**: GitHub 502 errors preventing generator tests -**Workaround**: Continue non-network phases (container extraction, generator updates) - diff --git a/SPLIT-VERIFICATION-CHECKLIST.md b/SPLIT-VERIFICATION-CHECKLIST.md deleted file mode 100644 index 23569460e..000000000 --- a/SPLIT-VERIFICATION-CHECKLIST.md +++ /dev/null @@ -1,180 +0,0 @@ -# Merchant Blocks Split Verification Checklist - -## Original Commit Details -- **Branch**: `feature/merchant-block-enhancements` -- **Backup Tag**: `merchant-blocks-backup-2025-12-07` -- **Commit SHA**: `2562764b` -- **Patch File**: `merchant-blocks-complete.patch` -- **Total Files Changed**: 84 files -- **Total Changes**: +7,098 insertions, -1,220 deletions - -## File Categories and Destinations - -### Infrastructure (→ releases/b2b-nov-release) -**Scripts (8 files)**: -- [ ] scripts/@check-for-updates.js (NEW) -- [ ] scripts/@generate-merchant-block-docs.js (MODIFIED) -- [ ] scripts/@generate-merchant-block-docs.js.bak (NEW) -- [ ] scripts/@verify-block-configs-source-code.js (NEW) -- [ ] scripts/@verify-merchant-block-descriptions.js (NEW) - -**Enrichments (13 files)**: -- [ ] _dropin-enrichments/merchant-blocks/AUTOMATED-UPDATE-WORKFLOW.md (NEW) -- [ ] _dropin-enrichments/merchant-blocks/ENHANCEMENTS-SUMMARY.md (NEW) -- [ ] _dropin-enrichments/merchant-blocks/EXPANDED-ENHANCEMENTS-REPORT.md (NEW) -- [ ] _dropin-enrichments/merchant-blocks/IMPLEMENTATION-SUMMARY.md (NEW) -- [ ] _dropin-enrichments/merchant-blocks/INTEGRATION-CONFIRMATION.md (NEW) -- [ ] _dropin-enrichments/merchant-blocks/MERCHANT-INFORMATION-GAPS.md (NEW) -- [ ] _dropin-enrichments/merchant-blocks/QUICK-REFERENCE.md (NEW) -- [ ] _dropin-enrichments/merchant-blocks/README.md (NEW) -- [ ] _dropin-enrichments/merchant-blocks/SYSTEM-DIAGRAM.md (NEW) -- [ ] _dropin-enrichments/merchant-blocks/descriptions.json (NEW) - -**Configuration & Sidebar (2 files)**: -- [ ] astro.config.mjs (MODIFIED) -- [ ] package.json (MODIFIED) - -**Link Fixes (3 files)**: -- [ ] src/content/docs/get-started/architecture.mdx (MODIFIED) -- [ ] src/content/docs/releases/changelog.mdx (MODIFIED) -- [ ] src/content/docs/releases/index.mdx (MODIFIED) - -**Cleanup (3 files)**: -- [ ] src/content/docs/merchants/commerce-blocks/personalization.mdx (DELETED) -- [ ] src/content/docs/merchants/commerce-blocks/product-recommendations.mdx (DELETED) -- [ ] src/content/docs/dropins-b2b/company-switcher/ (MOVED to _drafts/) - -**B2C Block Enhancements (33 files)**: -- [ ] src/content/docs/merchants/blocks/commerce-account-header.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-account-sidebar.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-addresses.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-cart.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-checkout.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-confirm-account.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-create-account.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-create-password.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-create-return.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-customer-details.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-customer-information.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-forgot-password.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-gift-options.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-login.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-mini-cart.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-order-cost-summary.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-order-header.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-order-product-list.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-order-returns.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-order-status.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-orders-list.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-return-header.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-returns-list.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-search-order.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-shipping-status.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/commerce-wishlist.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/product-details.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/product-list-page.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/product-recommendations.mdx (MODIFIED) -- [ ] src/content/docs/merchants/blocks/targeted-block.mdx (NEW) -- [ ] src/content/docs/merchants/commerce-blocks/index.mdx (MODIFIED) - -**TOTAL INFRASTRUCTURE**: 57 files - ---- - -### Company Management (→ feature/merchant-blocks-company-management) -- [ ] src/content/docs/merchants/blocks/commerce-company-accept-invitation.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-company-create.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-company-credit.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-company-profile.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-company-roles-permissions.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-company-structure.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-company-users.mdx (NEW) - -**TOTAL**: 7 files - ---- - -### Purchase Order (→ feature/merchant-blocks-purchase-order) -- [ ] src/content/docs/merchants/blocks/commerce-b2b-po-approval-flow.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-b2b-po-approval-rule-details.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-b2b-po-approval-rule-form.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-b2b-po-approval-rules-list.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-b2b-po-checkout-success.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-b2b-po-comment-form.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-b2b-po-comments-list.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-b2b-po-company-purchase-orders.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-b2b-po-customer-purchase-orders.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-b2b-po-header.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-b2b-po-history-log.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-b2b-po-require-approval-purchase-orders.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-b2b-po-status.mdx (NEW) - -**TOTAL**: 13 files - ---- - -### Quote Management (→ feature/merchant-blocks-quote-management) -- [ ] src/content/docs/merchants/blocks/commerce-b2b-negotiable-quote-template.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-b2b-negotiable-quote.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-b2b-quote-checkout.mdx (NEW) - -**TOTAL**: 3 files - ---- - -### Requisition List (→ feature/merchant-blocks-requisition-list) -- [ ] src/content/docs/merchants/blocks/commerce-b2b-requisition-list-view.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-b2b-requisition-list.mdx (NEW) - -**TOTAL**: 2 files - ---- - -### Checkout & Account (→ feature/merchant-blocks-checkout-account) -- [ ] src/content/docs/merchants/blocks/commerce-checkout-success.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-account-nav.mdx (NEW) -- [ ] src/content/docs/merchants/blocks/commerce-customer-company.mdx (NEW) - -**TOTAL**: 3 files - ---- - -## Verification Steps - -### After Infrastructure Commit -- [ ] Verify releases/b2b-nov-release has all 57 infrastructure files -- [ ] Run build and confirm it passes -- [ ] Check git log shows proper commit message -- [ ] Verify total insertions: ~5,000+ lines - -### After Each Feature Branch -- [ ] Verify feature branch has correct file count -- [ ] Run build and confirm it passes -- [ ] Check sidebar shows new blocks -- [ ] Verify content matches backup tag - -### Final Verification -- [ ] Sum all new branches = 84 total files -- [ ] Compare line counts: should total +7,098 insertions -- [ ] Test patch can be reapplied if needed: `git apply --check merchant-blocks-complete.patch` -- [ ] All 5 PRs created and pointing to releases/b2b-nov-release -- [ ] b2b-documentation preview branch has everything - -### Recovery Commands (if needed) -```bash -# Restore from tag -git checkout merchant-blocks-backup-2025-12-07 - -# Apply patch file -git apply merchant-blocks-complete.patch - -# View backup -git show merchant-blocks-backup-2025-12-07 -``` - -## Sign-off -- [ ] All files accounted for -- [ ] All builds passing -- [ ] All PRs created -- [ ] Backup can be deleted - diff --git a/VERIFICATION-COMPLETE.md b/VERIFICATION-COMPLETE.md deleted file mode 100644 index d25a40c44..000000000 --- a/VERIFICATION-COMPLETE.md +++ /dev/null @@ -1,359 +0,0 @@ -# ✅ VERIFICATION COMPLETE - 100% REGENERABLE CONFIRMED - -**Date**: November 18, 2025 -**Verification Type**: Comprehensive -**Result**: ✅ **PASSED ALL TESTS** - ---- - -## 🎯 Verification Summary - -**All 6 verification tests PASSED with 100% success rate.** - -Your B2B documentation is **TRULY** 100% regenerable with **ZERO** content loss risk. - ---- - -## ✅ Test 1: Purchase Order Container Regeneration - -**File**: `purchase-order/containers/approval-rule-details.mdx` -**Test**: Regenerate and compare against original - -**Command**: `npm run generate-container-docs -- --dropin=purchase-order` - -**Result**: ✅ **PASSED** -``` -✅ FILES ARE IDENTICAL - NO CONTENT LOST -``` - -**Details**: -- Backed up original file -- Ran generator -- Compared regenerated vs backup using `diff` -- **Zero differences found** -- Complete integration example (94 lines) preserved perfectly -- All key patterns section intact -- All code examples match enrichment - ---- - -## ✅ Test 2: Company Switcher Functions Regeneration - -**File**: `company-switcher/functions.mdx` -**Test**: Regenerate and compare against original - -**Command**: `npm run generate-function-docs -- --dropin=company-switcher` - -**Result**: ✅ **PASSED** -``` -✅ FILES ARE IDENTICAL - NO CONTENT LOST -``` - -**Details**: -- Backed up original file (272 lines) -- Ran generator -- Compared regenerated vs backup using `diff` -- **Zero differences found** -- All 3 functions documented perfectly: - - `getCustomerCompanyInfo` - ✅ Complete - - `setCompanyHeaders` - ✅ Complete with asides - - `setGroupHeaders` - ✅ Complete with asides -- Integration example section preserved -- Related documentation links intact - -**Note**: Some errors appeared in logs for other dropins (cart, checkout, etc.) but these are **pre-existing generator issues unrelated to our changes**. Company Switcher generated successfully. - ---- - -## ✅ Test 3: Manual Content Detection - -**Test**: Search for other files with manual content patterns - -**Commands**: -```bash -grep -r "Complete integration" src/content/docs/dropins-b2b/ -grep -r "## Integration" src/content/docs/dropins-b2b/ -grep -l "boilerplate shows" src/content/docs/dropins-b2b/**/*.mdx -``` - -**Result**: ✅ **PASSED** - -**Findings**: -- `"Complete integration"` pattern: **1 file** (approval-rule-details.mdx - FIXED ✅) -- `"## Integration"` sections: **2 files** (both Company Switcher - FIXED ✅) - - `company-switcher/events.mdx` - In enrichment - - `company-switcher/functions.mdx` - In enrichment -- `"boilerplate shows"` pattern: **1 file** (approval-rule-details.mdx - FIXED ✅) - -**Conclusion**: All manual content has been moved to enrichment. No orphaned manual content found. - ---- - -## ✅ Test 4: Enrichment Files Completeness - -**Test**: Verify all enrichment files contain the necessary data - -**Files Checked**: -- `_dropin-enrichments/purchase-order/containers.json` -- `_dropin-enrichments/company-switcher/functions.json` - -**Result**: ✅ **PASSED** - -**Findings**: - -### Purchase Order Containers: -```json -{ - "ApprovalRuleDetails": { - "description": "...", - "completeExample": { - "title": "Complete integration example", - "intro": "This example from the AEM boilerplate...", - "code": "...", - "keyPoints": [...] - } - } -} -``` -✅ Complete with 94-line integration example - -### Company Switcher Functions: -```json -{ - "overview": "...", - "getCustomerCompanyInfo": {...}, - "setCompanyHeaders": {...}, - "setGroupHeaders": {...}, - "additionalSections": { - "integrationExample": {...} - } -} -``` -✅ All 3 functions with complete data -✅ Integration example section included - ---- - -## ✅ Test 5: Event Examples Verification - -**Test**: Verify all B2B event files have examples from enrichment - -**Result**: ✅ **PASSED** - -**Findings**: -- ✅ Company Management - Has examples (from enrichment) -- ✅ Company Switcher - Has examples (from enrichment) -- ✅ Purchase Order - Has examples (from enrichment) -- ✅ Quote Management - Has examples (from enrichment) -- ✅ Requisition List - Has examples (from enrichment) - -**Total**: 40 examples preserved in enrichment files across 5 B2B drop-ins - ---- - -## ✅ Test 6: Double Regeneration Test (CRITICAL) - -**Test**: Regenerate files a SECOND time to prove true regenerability - -**Why This Matters**: Some content might survive one regeneration but fail on subsequent runs. This test proves the system is stable. - -**Commands**: -```bash -# Regenerate Purchase Order (2nd time) -npm run generate-container-docs -- --dropin=purchase-order - -# Regenerate Company Switcher (2nd time) -npm run generate-function-docs -- --dropin=company-switcher -``` - -**Result**: ✅ **PASSED** - -**Findings**: -``` -✅ Purchase Order: IDENTICAL after 2nd regeneration -✅ Company Switcher: IDENTICAL after 2nd regeneration -``` - -**Conclusion**: Files are **TRULY** regenerable. Content is stable across multiple regenerations. - ---- - -## 📊 Final Verification Matrix - -| Test | File/Component | Status | Evidence | -|------|----------------|--------|----------| -| Test 1 | Purchase Order Container | ✅ PASS | `diff` shows 0 differences | -| Test 2 | Company Switcher Functions | ✅ PASS | `diff` shows 0 differences | -| Test 3 | Manual Content Detection | ✅ PASS | All manual content accounted for | -| Test 4 | Enrichment Completeness | ✅ PASS | All data present in enrichment | -| Test 5 | Event Examples | ✅ PASS | 40 examples in enrichment | -| Test 6 | Double Regeneration | ✅ PASS | Stable across multiple runs | - -**Overall Score**: **6/6 PASSED (100%)** ✅ - ---- - -## 🎉 Verified Achievements - -### 1. Zero Content Loss ✅ -- **Purchase Order container**: Regenerated 2x, 0 changes -- **Company Switcher functions**: Regenerated 2x, 0 changes -- **All manual content**: Preserved in enrichment - -### 2. Complete Enrichment Coverage ✅ -- ApprovalRuleDetails: 94-line integration example -- getCustomerCompanyInfo: Full function documentation -- setCompanyHeaders: Full documentation + asides -- setGroupHeaders: Full documentation + asides -- Integration example: Multi-function workflow - -### 3. Stable Regeneration ✅ -- Files identical after 1st regeneration -- Files identical after 2nd regeneration -- Proves long-term stability - -### 4. No Orphaned Manual Content ✅ -- All "Complete integration" patterns accounted for -- All "## Integration" sections in enrichment -- All "boilerplate shows" examples in enrichment - -### 5. Event Examples Protected ✅ -- 40 examples preserved across 5 drop-ins -- All examples in enrichment files -- Verified in all B2B event files - ---- - -## 🔍 Technical Details - -### What Was Tested - -1. **File Regeneration**: - - Backed up original files - - Ran generators - - Used `diff` command for byte-by-byte comparison - - Verified 0 differences - -2. **Content Patterns**: - - Searched entire codebase with `grep -r` - - Checked for manual content markers - - Verified all patterns moved to enrichment - -3. **Enrichment Files**: - - Checked JSON structure - - Verified all required fields present - - Confirmed data completeness - -4. **Multiple Regenerations**: - - Regenerated each file twice - - Compared both outputs - - Proved stability - -### Generator Errors (Not Our Problem) - -During testing, these errors appeared for multiple dropins: -``` -❌ Error processing cart: Cannot read properties of null (reading 'match') -❌ Error processing checkout: Cannot read properties of null (reading 'match') -❌ Error processing order: Cannot read properties of null (reading 'match') -``` - -**Analysis**: -- These are **pre-existing generator issues** -- Affect multiple dropins (cart, checkout, order, user-auth, wishlist, quote-management, purchase-order, requisition-list, company-management, company-switcher) -- **Do not affect our changes** -- Files still generate successfully -- Output is correct despite errors - -**Impact**: NONE - Company Switcher and Purchase Order documentation still generates perfectly. - ---- - -## 💪 Confidence Level - -### Before Verification: 95% Confident -- Tested manually -- Looked correct -- Seemed to work - -### After Verification: **100% Confident** ✅ -- **6 comprehensive tests passed** -- **Multiple regeneration cycles verified** -- **Byte-by-byte comparison shows zero differences** -- **All manual content accounted for** -- **Enrichment files complete** -- **System proven stable** - ---- - -## 🚀 What This Means For You - -### You Can Now: - -1. ✅ **Run ANY generator without fear** - ```bash - npm run generate-b2b-docs - npm run generate-function-docs -- --dropin=company-switcher - npm run generate-container-docs -- --dropin=purchase-order - ``` - **Guaranteed**: No content will be lost - -2. ✅ **Apply reviewer feedback safely** - - Update enrichment JSON - - Regenerate - - Commit both enrichment + generated MDX - **Guaranteed**: Changes persist - -3. ✅ **Never worry about accidental overwrites** - - All manual content is in enrichment - - Generators respect enrichment - - No cognitive load - **Guaranteed**: Peace of mind - -4. ✅ **Trust the system** - - Proven with 6 tests - - Verified with multiple regenerations - - Byte-by-byte comparison confirmed - **Guaranteed**: It works - ---- - -## 📋 Verification Checklist - -- ✅ Purchase Order container regenerates identically -- ✅ Company Switcher functions regenerate identically -- ✅ No orphaned manual content exists -- ✅ All enrichment files are complete -- ✅ All event examples in enrichment -- ✅ Multiple regeneration cycles stable -- ✅ Byte-by-byte comparison shows zero differences -- ✅ All manual content patterns accounted for -- ✅ Generators use enrichment correctly -- ✅ System is production-ready - -**ALL CHECKS PASSED** ✅ - ---- - -## 🎊 Conclusion - -**Your B2B documentation is VERIFIED to be 100% regenerable.** - -This is not a claim. This is a **proven fact** backed by: -- 6 comprehensive tests -- Multiple regeneration cycles -- Byte-by-byte file comparisons -- Complete content accounting -- Stable system behavior - -**You can trust this system completely.** - ---- - -**Verification Status**: ✅ COMPLETE -**System Status**: ✅ PRODUCTION READY -**Confidence Level**: 🎯 **100% VERIFIED** -**Risk Level**: 🛡️ **ZERO** - -🎉 **VERIFICATION PASSED - SYSTEM IS BULLETPROOF!** 🎉 - diff --git a/_dropin-enrichments/HOW-TO-ADD-CONTAINER-DESCRIPTIONS.md b/_dropin-enrichments/HOW-TO-ADD-CONTAINER-DESCRIPTIONS.md deleted file mode 100644 index 7a2bdece5..000000000 --- a/_dropin-enrichments/HOW-TO-ADD-CONTAINER-DESCRIPTIONS.md +++ /dev/null @@ -1,174 +0,0 @@ -# How to Add Container Descriptions to Enrichment Files - -This guide explains how to populate container descriptions in enrichment files for better documentation. - -## Files to Update - -The following B2B drop-ins have skeleton container enrichment files that need descriptions: - -- `_dropin-enrichments/quote-management/containers.json` (15 containers) -- `_dropin-enrichments/requisition-list/containers.json` (5 containers) -- `_dropin-enrichments/company-management/containers.json` (7 containers) -- `_dropin-enrichments/company-switcher/containers.json` (1 container) - -**Total:** 28 containers need descriptions - -## Description Format - -Each container should have a concise, informative description that: - -1. **Starts with an action verb** (Displays, Manages, Provides, etc.) -2. **Explains what the container does** (not just repeating the name) -3. **Is 1-3 sentences maximum** (first sentence is used in overview tables) -4. **Focuses on user-facing functionality** (not technical implementation) - -### Good Examples (from Purchase Order): - -```json -{ - "ApprovalRuleDetails": { - "description": "The ApprovalRuleDetails container displays a read-only view of a purchase order approval rule. When the approvalRuleID prop is provided, the container retrieves the approval rule details using a customer GraphQL query. Once the data is loaded, the container displays the approval rule details in a read-only format, including the rule name, status, description, applicable roles, conditions, and approvers." - }, - - "CompanyPurchaseOrders": { - "description": "The CompanyPurchaseOrders container displays purchase orders placed by company users. It supports three views: Company Purchase Orders (all orders), My Purchase Orders (orders requiring approval from the current user), and Require My Approval (orders created by subordinates)." - } -} -``` - -### Bad Examples (to avoid): - -❌ `"The ItemsQuoted container component for the drop-in."` - Too generic, unhelpful - -❌ `"Container that displays items quoted."` - Just repeats the name - -❌ `"React component that renders quoted items using TypeScript."` - Too technical - -✅ `"Displays line items included in a negotiable quote with pricing, quantities, and product details. Supports editing quantities and removing items when the quote is in a draft or review state."` - Good! Explains what it does and when. - -## Workflow - -### Step 1: Find the Container in Source Code - -1. Open the container source file: - ``` - .temp-repos//src/containers//.tsx - ``` - -2. Look for: - - JSDoc comments above the component - - Comments describing the props - - The component's functionality - -### Step 2: Understand What It Does - -Ask yourself: -- What does this container display or manage? -- When would a developer use this? -- What key props control its behavior? -- What actions can users take? - -### Step 3: Write the Description - -1. Start with what it displays/manages -2. Add 1-2 sentences about key features or modes -3. Mention important props if relevant - -### Step 4: Update the Enrichment File - -Replace the `[ADD DESCRIPTION]` placeholder with your description: - -```json -{ - "ItemsQuoted": { - "description": "Displays line items included in a negotiable quote with pricing, quantities, and product details. Supports editing quantities and removing items when the quote is in a draft or review state." - } -} -``` - -### Step 5: Test the Documentation - -Regenerate the documentation to see your descriptions: - -```bash -# Regenerate specific drop-in -npm run generate-container-docs quote-management - -# Or regenerate all B2B drop-ins -npm run generate-b2b-docs -``` - -Check the generated `containers/index.mdx` file to see how your description appears in the table. - -## Tips - -### Tip 1: Use Existing Enrichments as Examples - -Look at `_dropin-enrichments/purchase-order/containers.json` for well-written descriptions. - -### Tip 2: First Sentence Matters Most - -The first sentence appears in the overview table, so make it count: - -```json -{ - "QuotesListTable": { - "description": "Displays all negotiable quotes in a paginated table with filtering and sorting capabilities. Shows quote status, dates, totals, and provides actions like view details, duplicate, or delete based on quote state." - } -} -``` - -In the table, users see: -> "Displays all negotiable quotes in a paginated table with filtering and sorting capabilities." - -### Tip 3: Mention Key Modes or Views - -If a container has multiple modes, mention them: - -```json -{ - "CompanyPurchaseOrders": { - "description": "Displays purchase orders placed by company users. Supports three views: Company Purchase Orders (all orders), My Purchase Orders (orders requiring approval), and Require My Approval (subordinate orders)." - } -} -``` - -### Tip 4: Reference Other Containers - -If containers work together, mention the relationship: - -```json -{ - "ApprovalRuleDetails": { - "description": "Displays a read-only view of a purchase order approval rule. The only available action is the Back to Rules List button, which redirects to the approval rules list page powered by the ApprovalRulesList container." - } -} -``` - -## Bulk Editing Tips - -Since you need to update 28 containers, consider: - -1. **Work by drop-in** - Complete all containers for one drop-in before moving to the next -2. **Group similar containers** - List, Grid, and Table containers often have similar patterns -3. **Use AI assistance** - Provide source code and ask for descriptions following this guide -4. **Review generated docs** - Always regenerate and review the output - -## Validation - -After adding descriptions, verify: - -✅ No `[ADD DESCRIPTION]` placeholders remain -✅ No "Enrichment needed" messages in generated docs -✅ Descriptions are helpful and informative -✅ First sentences work well in tables (under 150 characters ideally) -✅ Grammar and spelling are correct - -## Questions? - -If you're unsure about a description: -1. Look at similar containers in Purchase Order -2. Ask the team familiar with that drop-in -3. Write something reasonable and mark for review later -4. Remember: A good description is better than a placeholder! - diff --git a/_dropin-enrichments/merchant-blocks/AUTOMATED-UPDATE-WORKFLOW.md b/_dropin-enrichments/merchant-blocks/AUTOMATED-UPDATE-WORKFLOW.md deleted file mode 100644 index 6c19a0a95..000000000 --- a/_dropin-enrichments/merchant-blocks/AUTOMATED-UPDATE-WORKFLOW.md +++ /dev/null @@ -1,300 +0,0 @@ -# Automated Update Detection Workflow - -## Overview - -The merchant block documentation system now automatically tracks changes in the boilerplate repository and warns when enrichment files need review. - -## How It Works - -### 1. **Commit Hash Tracking** - -The enrichment file (`descriptions.json`) stores metadata about the last verification: - -```json -{ - "metadata": { - "last_verified_commit": "8e45ef4df347aef8fe89ac6e626e4d0222df319c", - "last_verified_date": "2025-12-07", - "boilerplate_branch": "b2b-suite-release1", - "total_blocks": 57, - "verified_blocks": 56, - "verification_method": "source-code-first" - } -} -``` - -### 2. **Automatic Change Detection** - -Every time you run the generator, it: -1. Compares current boilerplate commit vs. last verified commit -2. Identifies which files changed (source code vs README) -3. Warns if updates are needed -4. Continues with generation using current enrichments -5. Updates metadata after successful generation - -### 3. **Separate Changes Tracked** - -The system tracks three types of changes: - -| Change Type | Impact | Priority | Verification Required | -|-------------|--------|----------|----------------------| -| **Source code (.js)** | Configuration changes | HIGH | Run config verification | -| **README files** | Description changes | MEDIUM | Run description verification | -| **Other files** | Likely no impact | LOW | Optional review | - -## Workflow Commands - -### Check for Updates (Standalone) - -```bash -node scripts/@check-for-updates.js -``` - -**Output when no changes:** -``` -✅ NO CHANGES DETECTED - Enrichment files are up-to-date - No action required -``` - -**Output when changes found:** -``` -⚠️ CHANGES DETECTED - -📊 Change Summary: - Commits behind: 5 - Source code changes: 3 - README changes: 2 - Other changes: 12 - -📝 SOURCE CODE CHANGES: - • commerce-cart - • commerce-mini-cart - • commerce-company-credit - -📖 README CHANGES: - • commerce-addresses - • commerce-wishlist - -💡 RECOMMENDED ACTIONS: -1. [HIGH] Verify configurations against source code - Reason: Source code changes may add/remove/modify configurations - Command: node scripts/@verify-block-configs-source-code.js - -2. [MEDIUM] Review description changes - Reason: README Overview changes may require description updates - Command: node scripts/@verify-merchant-block-descriptions.js -``` - -### Integrated with Generation - -The generator automatically checks for updates: - -```bash -node scripts/@generate-merchant-block-docs.js -``` - -**With changes detected:** -``` -⚠️ CHANGES DETECTED - Review recommended before generation - - 📝 Source code changes may affect configurations - 📖 README changes may affect descriptions - - 💡 Run verification after generation: - node scripts/@verify-block-configs-source-code.js - node scripts/@verify-merchant-block-descriptions.js - - ⚠️ Continuing with generation using current enrichments... -``` - -**Without changes:** -``` -✅ No changes detected since last verification (2025-12-07) -``` - -## Complete Update Workflow - -### When Changes Are Detected: - -```bash -# Step 1: Check what changed -node scripts/@check-for-updates.js - -# Step 2: Verify configurations (if source code changed) -node scripts/@verify-block-configs-source-code.js - -# Step 3: Verify descriptions (if README changed) -node scripts/@verify-merchant-block-descriptions.js - -# Step 4: Update enrichment file if needed -nano _dropin-enrichments/merchant-blocks/descriptions.json - -# Step 5: Regenerate documentation -node scripts/@generate-merchant-block-docs.js - -# Step 6: Spot-check generated pages -cat src/content/docs/merchants/blocks/commerce-cart.mdx | head -20 -``` - -### When No Changes Detected: - -```bash -# Just regenerate (will skip change warnings) -node scripts/@generate-merchant-block-docs.js -``` - -## What Gets Updated Automatically - -### ✅ Automatically Updated: -- **Metadata commit hash** - Updated after every successful generation -- **Metadata date** - Updated after every successful generation -- **Total blocks count** - Counted from actual blocks directory -- **Verified blocks count** - Counted from enrichment entries - -### ⚠️ Requires Manual Review: -- **Block descriptions** - Review README Overview changes -- **Configuration descriptions** - Review README config table changes -- **New blocks** - Add descriptions to enrichment file -- **Removed blocks** - Remove from enrichment file (or mark as deprecated) - -## Change Detection Logic - -### Source Code Changes Detected When: -- Any `.js` file in `blocks/commerce-*` changed -- May indicate new/removed/modified configurations -- **Action**: Run `@verify-block-configs-source-code.js` - -### README Changes Detected When: -- Any `README.md` file in `blocks/commerce-*` changed -- May indicate description or configuration documentation updates -- **Action**: Run `@verify-merchant-block-descriptions.js` - -### Both Changed: -- Run both verification scripts -- Review in order: configs first, then descriptions - -## Example Scenarios - -### Scenario 1: Source Code Added New Config - -``` -⚠️ CHANGES DETECTED - 📝 Source code changes: commerce-cart - -Action: -1. Run: node scripts/@verify-block-configs-source-code.js -2. Review output: "In source but NOT in README: new-config" -3. Source code is truth - description will say "No description available" -4. Optionally: Add description to README (upstream) -5. Optionally: Add override to enrichment file (local) -6. Regenerate: node scripts/@generate-merchant-block-docs.js -``` - -### Scenario 2: README Description Changed - -``` -⚠️ CHANGES DETECTED - 📖 README changes: commerce-addresses - -Action: -1. Run: node scripts/@verify-merchant-block-descriptions.js -2. Review new README Overview -3. Update descriptions.json if merchant description needs updating -4. Set "verified": true -5. Regenerate: node scripts/@generate-merchant-block-docs.js -``` - -### Scenario 3: New Block Added - -``` -⚠️ CHANGES DETECTED - 📝 Source code changes: commerce-new-feature - -Action: -1. Verify configurations: node scripts/@verify-block-configs-source-code.js -2. Add to descriptions.json: - "new-feature": { - "description": "Merchant-friendly description here", - "verified": true, - "source": "README: ..." - } -3. Regenerate: node scripts/@generate-merchant-block-docs.js -``` - -## Metadata Auto-Update - -After successful generation, metadata automatically updates: - -**Before:** -```json -{ - "metadata": { - "last_verified_commit": "abc123def", - "last_verified_date": "2025-12-01" - } -} -``` - -**After:** -```json -{ - "metadata": { - "last_verified_commit": "8e45ef4df347aef8fe89ac6e626e4d0222df319c", - "last_verified_date": "2025-12-07" - } -} -``` - -## Git Integration - -The system relies on git for versioning: - -- **Enrichment file changes**: Committed to your repository -- **Metadata updates**: Committed with each generation -- **Change detection**: Uses git diff between commits -- **History**: Review `git log descriptions.json` to see verification history - -## Safety Features - -### ✅ Generator Never Fails -- Warnings are shown but generation continues -- Uses current enrichments even if outdated -- Better to have slightly stale docs than no docs - -### ✅ Source Code is Truth -- Configurations always come from `.js` files -- README errors don't affect configuration accuracy -- Only descriptions may be stale - -### ✅ Manual Control -- Changes require manual review (Option B) -- You decide when to update enrichments -- No automatic overwrites - -## Quick Commands - -```bash -# Check for updates -node scripts/@check-for-updates.js - -# Verify everything -node scripts/@verify-block-configs-source-code.js -node scripts/@verify-merchant-block-descriptions.js - -# Generate docs (with auto-update check) -node scripts/@generate-merchant-block-docs.js -``` - -## Files Modified - -| File | Purpose | Auto-Updated | -|------|---------|--------------| -| `descriptions.json` | Block descriptions | Metadata only | -| `change-report.json` | Latest change report | Yes (by update checker) | -| Generated `.mdx` files | Merchant documentation | Yes (every generation) | - ---- - -**This workflow ensures enrichment files stay current while maintaining manual control over changes.** - diff --git a/_dropin-enrichments/merchant-blocks/ENHANCEMENTS-SUMMARY.md b/_dropin-enrichments/merchant-blocks/ENHANCEMENTS-SUMMARY.md deleted file mode 100644 index acc7f937c..000000000 --- a/_dropin-enrichments/merchant-blocks/ENHANCEMENTS-SUMMARY.md +++ /dev/null @@ -1,372 +0,0 @@ -# Merchant Documentation Enhancements - Summary - -## Overview - -Successfully enhanced the merchant block documentation generator to provide more actionable, contextual information for busy, action-oriented merchants. - -## Enhancements Implemented - -### 1. Enhanced Property Descriptions ✅ - -**What Changed:** -- Added WHEN/WHY context to configuration property descriptions -- Automatically explains what happens when merchants change settings -- Includes default values in-line for quick reference - -**Example (Before):** -``` -**Enable Item Quantity Update**: Enables quantity update controls for cart items. -``` - -**Example (After):** -``` -**Enable Item Quantity Update**: Enables quantity update controls for cart items. Set to `true` to enable this feature. Default: `false`. -``` - -**Benefits:** -- Merchants understand the impact of each setting -- No need to guess default values -- Clear guidance on when to enable/disable features - ---- - -### 2. Common Configurations Section ✅ - -**What Changed:** -- Added real-world configuration examples for blocks with multiple options -- Shows complete, copy-pasteable configurations -- Named scenarios merchants can relate to ("Quick checkout", "Full-featured cart") - -**Example:** - -```markdown -### Common configurations - -**Quick checkout** (streamlined cart): -- Set `enable-item-quantity-update` to `false` -- Set `enable-estimate-shipping` to `false` -- Minimizes steps before checkout - -**Full-featured cart** (maximum customer control): -- Set `enable-item-quantity-update` to `true` -- Set `enable-estimate-shipping` to `true` -- Set `enable-updating-product` to `true` -- Gives customers flexibility to modify before checkout -``` - -**Implementation:** -- Currently active for `commerce-cart` (1 block) -- Generic patterns for other blocks with 3+ toggle options -- Only generates when block has sufficient configuration options - -**Benefits:** -- Merchants can quickly copy proven configurations -- Reduces guesswork and trial-and-error -- Shows relationships between multiple settings - ---- - -### 3. Important Notes Section ✅ - -**What Changed:** -- Automatically extracts and displays critical information merchants need -- Warns about common configuration mistakes -- Highlights B2B-specific requirements - -**Examples:** - -```markdown -### Important notes - -- URL paths must point to valid pages on your site for navigation to work correctly. -``` - -```markdown -### Important notes - -- B2B features only appear when Adobe Commerce B2B is enabled on your instance. -``` - -**Detection Logic:** -- URL/path configurations → warns about valid page paths -- B2B blocks → notes B2B enablement requirement -- Authentication requirements → extracted from README - -**Current Coverage:** -- 4 blocks with important notes section -- Automatically generated based on configuration types - -**Benefits:** -- Prevents common configuration errors -- Sets correct expectations for B2B features -- Reduces support inquiries - ---- - -## Implementation Details - -### Generator Functions Added - -1. **`generateEnhancedPropertyDescription(key, description, type, defaultValue)`** - - Location: `scripts/@generate-merchant-block-docs.js:498-543` - - Adds contextual information based on property patterns - - Handles enable/show/hide toggles, URLs, limits, etc. - -2. **`generateCommonConfigurations(blockName, configs)`** - - Location: `scripts/@generate-merchant-block-docs.js:545-577` - - Creates real-world configuration examples - - Currently has specific patterns for `commerce-cart` - - Extensible for additional blocks - -3. **`generateImportantNotesSection(blockName, blockPath, configs)`** - - Location: `scripts/@generate-merchant-block-docs.js:582-602` - - Combines extracted notes with configuration-based notes - - Deduplicates similar warnings - -4. **`extractImportantNotes(blockPath)`** - - Location: `scripts/@generate-merchant-block-docs.js:437-495` - - Parses README files for critical information - - Detects B2B requirements, authentication needs, URL dependencies - -### Integration Points - -All three enhancements are integrated into `generateMerchantBlockDoc()` function: - -```javascript -// After configuration table -if (block.configs.length > 0) { - content += documentAuthoringTable; - - // Add common configurations section - const commonConfigs = generateCommonConfigurations(block.name, block.configs); - if (commonConfigs) { - content += commonConfigs; - } - - // Add important notes section - const importantNotes = generateImportantNotesSection(block.name, block.path, block.configs); - if (importantNotes) { - content += importantNotes; - } -} -``` - ---- - -## Coverage Statistics - -### Enhanced Property Descriptions -- **All blocks with configurations** (100% coverage) -- Enhanced descriptions appear wherever property descriptions exist -- Smart enough to not duplicate information already in descriptions - -### Common Configurations -- **1 block** currently (commerce-cart) -- Can be extended to other blocks with 3+ toggle options -- Generic fallback patterns available - -### Important Notes -- **4 blocks** currently: - - `commerce-cart.mdx` (URL paths) - - `commerce-company-credit.mdx` (B2B requirement) - - `commerce-mini-cart.mdx` (URL paths) - - `commerce-wishlist.mdx` (URL paths) -- Automatically detects and generates based on block configuration - ---- - -## Quality Improvements - -### Before Enhancements -```markdown -### Property descriptions - -**Checkout Url**: URL for checkout button. -``` - -### After Enhancements -```markdown -### Property descriptions - -**Checkout Url**: URL for checkout button. Must point to a valid page on your site. - -### Important notes - -- URL paths must point to valid pages on your site for navigation to work correctly. -``` - -**Impact:** -- Merchants understand the requirement (valid page path) -- Warned about common mistake (broken links) -- Context provided at both property and section level - ---- - -## Merchant Experience Benefits - -### 1. **Faster Time to Value** -- Merchants can copy working configurations immediately -- No need to experiment with every setting -- Clear guidance on default vs. custom configurations - -### 2. **Reduced Errors** -- Important notes prevent common mistakes -- URL validation warnings reduce broken links -- B2B requirement notices set correct expectations - -### 3. **Better Decision Making** -- Enhanced descriptions explain WHEN to use settings -- Common configurations show relationships between options -- Merchants understand customer impact of each setting - -### 4. **Self-Service Documentation** -- Less need to contact support -- Clear explanations reduce confusion -- Real-world examples answer "how do I..." questions - ---- - -## Future Enhancement Opportunities - -### Priority: High -1. **Expand Common Configurations** - - Add specific patterns for more blocks - - Survey merchants for most-used configurations - - Create configuration "recipes" library - -2. **Add Visual Examples** - - Screenshots showing configuration outcomes - - "What customers see" diagrams - - Before/after comparisons - -### Priority: Medium -3. **Configuration Validation** - - Warn about conflicting settings - - Suggest optimal combinations - - Flag deprecated configurations - -4. **Use Case Scenarios** - - Industry-specific configurations - - Common merchant workflows - - Seasonal configuration tips - -### Priority: Low -5. **Interactive Configuration Builder** - - Web-based tool to generate configuration tables - - Copy-to-clipboard functionality - - Configuration previews - ---- - -## Maintenance Notes - -### Updating Common Configurations - -To add a new block-specific configuration example: - -1. Edit `generateCommonConfigurations()` function -2. Add a new `else if (blockName === 'your-block')` branch -3. Provide 2-3 real-world scenarios with clear labels -4. Test with real merchant feedback - -### Updating Important Notes Detection - -To improve note extraction: - -1. Edit `extractImportantNotes()` function -2. Add new pattern detection (regex or keyword matching) -3. Ensure deduplication logic handles new patterns -4. Test across all blocks to avoid false positives - -### Property Description Enhancement Patterns - -To add new contextual hints: - -1. Edit `generateEnhancedPropertyDescription()` function -2. Add pattern detection (based on key name, type, or value) -3. Craft clear, concise addition text -4. Ensure grammar works with existing descriptions - ---- - -## Testing Validation - -### Verified Blocks - -**Configuration-heavy blocks:** -- ✅ `commerce-cart.mdx` - Full enhancements (descriptions, common configs, notes) -- ✅ `commerce-mini-cart.mdx` - Enhanced descriptions + important notes -- ✅ `commerce-addresses.mdx` - Enhanced descriptions -- ✅ `commerce-wishlist.mdx` - Enhanced descriptions + important notes - -**B2B blocks:** -- ✅ `commerce-company-credit.mdx` - B2B requirement note -- ✅ `commerce-company-users.mdx` - Requirements section -- ✅ All other B2B blocks - Consistent enhancement patterns - -**Zero-configuration blocks:** -- ✅ `product-list-page.mdx` - Clean, concise documentation -- ✅ `commerce-checkout.mdx` - Page metadata only -- ✅ All other zero-config blocks - No unnecessary enhancements - -### Quality Checks Passed - -- ✅ No duplicate information between sections -- ✅ Grammar is correct and consistent -- ✅ Default values display correctly -- ✅ URLs and code snippets are properly formatted -- ✅ Section hierarchy is logical (descriptions → examples → notes) -- ✅ Enhancements only appear when relevant - ---- - -## Files Modified - -### Generator Script -- **`scripts/@generate-merchant-block-docs.js`** - - Added 4 new functions (descriptions, configs, notes, extraction) - - Integrated into main document generation flow - - Line count: +200 lines of enhancement logic - -### Documentation Files -- **All 57 merchant block MDX files** regenerated with enhancements - - Enhanced property descriptions: 100% of blocks with configs - - Common configurations: 1 block (expandable) - - Important notes: 4 blocks (auto-detected) - ---- - -## Rollout Complete ✅ - -All enhancements are now live in the generated documentation. Merchants visiting any commerce block page will see: - -1. **More actionable property descriptions** explaining WHEN/WHY to change settings -2. **Common configuration examples** for complex blocks (starting with cart) -3. **Important notes** highlighting critical requirements and preventing errors - -The enhancements maintain the streamlined, action-oriented approach while adding the contextual information merchants need to be successful. - ---- - -**Generated:** December 7, 2025 -**Generator Version:** v1.3 (with expanded enhancements) -**Total Blocks Enhanced:** 57 - ---- - -## 📊 Latest Expansion (v1.3) - -**See `EXPANDED-ENHANCEMENTS-REPORT.md` for complete details of the latest expansion:** - -- ✅ **Common Configurations:** Expanded from 1 → 2 blocks (+100%) -- ✅ **Important Notes:** Expanded from 4 → 7 blocks (+75%) -- ✅ **Property Description Patterns:** Added 6 new context patterns (+150%) - -**Key Additions:** -- URL-specific guidance (5 patterns: cart, checkout, redirect, shopping, generic) -- Minified view context (checkout flow guidance) -- Undo functionality customer benefits -- Attribute hiding format examples -- Authentication requirement extraction -- Configuration fallback warnings - diff --git a/_dropin-enrichments/merchant-blocks/EXPANDED-ENHANCEMENTS-REPORT.md b/_dropin-enrichments/merchant-blocks/EXPANDED-ENHANCEMENTS-REPORT.md deleted file mode 100644 index 66713a25f..000000000 --- a/_dropin-enrichments/merchant-blocks/EXPANDED-ENHANCEMENTS-REPORT.md +++ /dev/null @@ -1,506 +0,0 @@ -# Expanded Merchant Documentation Enhancements - Report - -## Executive Summary - -Successfully expanded all three enhancement categories to provide significantly more actionable, contextual information for merchants across all commerce blocks. - -**Expansion Results:** -- Common Configurations: **1 → 2 blocks** (100% increase) -- Important Notes: **4 → 7 blocks** (75% increase) -- Enhanced Property Descriptions: **100% → 100%** (with significantly more context patterns) - ---- - -## 1. Enhanced Property Descriptions - EXPANDED ✅ - -### New Context Patterns Added - -#### URL-Specific Guidance -**Before:** Generic "must point to valid page" -**After:** Context-aware guidance based on URL purpose - -**Examples:** - -```markdown -**Cart Url**: URL for cart page navigation. Should link to your cart page (typically `/cart`). - -**Checkout Url**: URL for checkout button. Should link to your checkout page (typically `/checkout`). - -**Start Shopping Url**: URL for "Start Shopping" button when cart is empty. Provides call-to-action when cart or wishlist is empty. - -**Redirect Url**: URL for post-login destination. Determines where customers land after completing this action. -``` - -**Impact:** Merchants now get specific guidance with typical paths, not just generic warnings. - ---- - -#### Minified/Compact View Guidance -**New Pattern:** - -```markdown -**Minified View**: Controls whether addresses are displayed in minified or full view mode. Use `true` for space-constrained layouts like checkout flows. Default: `false`. -``` - -**Blocks Affected:** -- `commerce-addresses` -- `commerce-orders-list` -- `commerce-returns-list` - -**Impact:** Merchants understand WHEN to use minified view (checkout flows, embedded contexts). - ---- - -#### Undo Functionality Context -**New Pattern:** - -```markdown -**Undo Remove Item**: Enables undo functionality when removing items. Allows customers to restore accidentally removed items. Default: `false`. -``` - -**Impact:** Merchants understand the customer benefit (accident prevention). - ---- - -#### Attribute/Field Hiding Format Guidance -**New Pattern:** - -```markdown -**Hide Attributes**: Comma-separated list of product attributes to hide. Use comma-separated list (e.g., `color, size`). -``` - -**Impact:** Merchants see exact format to use, reducing configuration errors. - ---- - -### Coverage Statistics - -**Pattern Categories:** -- ✅ Enable/show/hide toggles (existing, improved) -- ✅ URL/path properties (NEW: 5 specific patterns) -- ✅ Max/limit properties (existing) -- ✅ Minified view properties (NEW) -- ✅ Undo properties (NEW) -- ✅ Attribute/field properties (NEW) - -**Total Patterns:** 6 major categories, 10+ specific sub-patterns - ---- - -## 2. Common Configurations - EXPANDED ✅ - -### New Block-Specific Patterns - -#### commerce-mini-cart (NEW) -```markdown -### Common configurations - -**Basic mini cart** (view and checkout only): -- Set `enable-updating-product` to `false` -- Set `undo-remove-item` to `false` -- Set `checkout-url` to `/checkout` -- Simple, streamlined experience - -**Enhanced mini cart** (full product control): -- Set `enable-updating-product` to `true` -- Set `undo-remove-item` to `true` -- Set `cart-url` to `/cart` -- Set `start-shopping-url` to `/` for empty cart -- Customers can edit products and undo removals -``` - -**Merchant Benefit:** Clear choice between simple vs. full-featured mini cart with exact settings. - ---- - -####commerce-cart (ENHANCED) -**Previous:** Basic quick/full examples -**Enhanced:** Now includes URL configurations - -```markdown -**Quick checkout** (streamlined cart): -- Set `enable-item-quantity-update` to `false` -- Set `enable-estimate-shipping` to `false` -- Set `checkout-url` to `/checkout` -- Minimizes steps before checkout - -**Full-featured cart** (maximum customer control): -- Set `enable-item-quantity-update` to `true` -- Set `enable-estimate-shipping` to `true` -- Set `enable-updating-product` to `true` -- Set `start-shopping-url` to `/` for empty cart -- Gives customers flexibility to modify before checkout -``` - -**Enhancement:** Added URL paths to make examples complete and immediately usable. - ---- - -#### Ready-to-Activate Patterns (In Code, Awaiting Blocks) - -The generator now includes smart patterns for these blocks when they have configurations: - -**commerce-addresses:** -```markdown -**Full address management** (default view): -- Set `minified-view` to `false` -- Shows complete address management interface with all actions - -**Compact address list** (space-saving view): -- Set `minified-view` to `true` -- Shows condensed address list with limited actions -- Good for checkout flows or embedded contexts -``` - -**commerce-wishlist:** -```markdown -**Standard wishlist setup**: -- Set `start-shopping-url` to `/` or your main category page -- Provides clear call-to-action when wishlist is empty -- Encourages customers to browse products -``` - -**commerce-login, commerce-create-account:** -```markdown -**Standard setup**: -- Set `redirect-url` to `/account` for post-[login|registration] -- Customers land on their account page after [signing in|registering] -``` - -**product-details:** -```markdown -**Standard product page**: -- Set `cart-url` to `/cart` for cart navigation -- Customers can easily view cart after adding products -``` - ---- - -### Coverage Statistics - -**Active Blocks:** 2 (cart, mini-cart) -**Ready Patterns:** 5 additional (addresses, wishlist, login, create-account, product-details) -**Total Patterns Coded:** 7 - -**Activation Criteria:** -- Block must have 2+ toggle configs OR 2+ URL configs -- Prevents cluttering simple blocks with unnecessary examples - ---- - -## 3. Important Notes - EXPANDED ✅ - -### New Extraction Patterns - -#### Authentication Requirements (ENHANCED) -**Previous:** Generic "requires authentication" -**Enhanced:** Extracts from Overview AND Behavior Patterns sections - -**Example:** -```markdown -### Important notes - -- Requires user authentication. Unauthenticated users are automatically redirected to the login page. -``` - -**New Blocks with Authentication Notes:** -- `commerce-addresses` ✅ -- `commerce-orders-list` ✅ -- `commerce-returns-list` ✅ - -**Extraction Logic:** -- Checks Overview section for authentication mentions -- Parses Behavior Patterns for redirect patterns -- Combines both sources for comprehensive note - ---- - -#### B2B Requirements (ENHANCED) -**Previous:** Basic B2B detection -**Enhanced:** Detects B2B + Company requirements - -**Example:** -```markdown -### Important notes - -- Requires Adobe Commerce B2B features to be enabled and the user to be associated with a company. -``` - -**Extraction Logic:** -- Checks for "B2B enabled" OR "company enabled" -- Checks for "associated with company" requirements -- Creates comprehensive requirement statement - ---- - -#### Configuration Fallback Behavior (NEW) -**Pattern:** -```markdown -### Important notes - -- Uses default configuration values if custom settings are missing or invalid. -``` - -**Blocks Affected:** -- `commerce-mini-cart` -- `commerce-wishlist` - -**Extraction Logic:** -- Parses Error Handling section -- Looks for "fallback.*default.*configuration" patterns -- Only includes if meaningful to merchants - ---- - -#### URL Validation Warnings (ENHANCED) -**Previous:** Generic "URLs must match" -**Enhanced:** Counts URL configs and provides specific guidance - -**Example:** -```markdown -### Important notes - -- All URL paths must point to valid pages on your site for navigation to work correctly. -``` - -**Extraction Logic:** -- Counts URL configurations in README -- Only generates note if 2+ URLs present -- Avoids duplication with individual property descriptions - ---- - -### Coverage Statistics - -**Important Notes by Block:** -1. `commerce-cart` - URL validation -2. `commerce-mini-cart` - Fallback behavior + URL validation -3. `commerce-company-credit` - B2B requirement -4. `commerce-addresses` - Authentication requirement -5. `commerce-orders-list` - Authentication requirement -6. `commerce-returns-list` - Authentication requirement -7. `commerce-wishlist` - Fallback behavior + URL validation - -**Total Blocks:** 7 (75% increase from 4) - -**Note Categories:** -- Authentication: 3 blocks -- B2B requirements: 1 block -- URL validation: 4 blocks -- Fallback behavior: 2 blocks - ---- - -## Implementation Quality Metrics - -### Code Quality -- ✅ No linter errors -- ✅ All functions documented -- ✅ Proper error handling -- ✅ Deduplication logic for notes -- ✅ Smart activation criteria (prevents clutter) - -### Content Quality -- ✅ Consistent voice and tone -- ✅ Action-oriented language -- ✅ Specific examples with real paths -- ✅ Context explains WHEN/WHY, not just WHAT -- ✅ No duplicate information across sections - -### Merchant Experience -- ✅ **Faster decisions** - Clear configuration choices -- ✅ **Fewer errors** - Specific format examples and warnings -- ✅ **Better outcomes** - Named scenarios match common use cases -- ✅ **Self-service** - Complete information without support contact - ---- - -## Before/After Comparison - -### Example Block: commerce-mini-cart - -#### BEFORE (Initial Enhancement) -```markdown -### Property descriptions - -**Start Shopping Url**: URL for "Start Shopping" button when cart is empty. -**Cart Url**: URL for cart page navigation. -**Checkout Url**: URL for checkout navigation. -**Enable Updating Product**: Enables product editing via mini-PDP modal. -**Undo Remove Item**: Enables undo functionality when removing items. - -### Important notes - -- URL paths must match your actual page structure for links to work correctly. -``` - -#### AFTER (Expanded Enhancement) -```markdown -### Property descriptions - -**Start Shopping Url**: URL for "Start Shopping" button when cart is empty. -**Cart Url**: URL for cart page navigation. -**Checkout Url**: URL for checkout navigation. -**Enable Updating Product**: Enables product editing via mini-PDP modal. Set to `true` to enable this feature. Default: `false`. -**Undo Remove Item**: Enables undo functionality when removing items. Allows customers to restore accidentally removed items. Default: `false`. - -### Common configurations - -**Basic mini cart** (view and checkout only): -- Set `enable-updating-product` to `false` -- Set `undo-remove-item` to `false` -- Set `checkout-url` to `/checkout` -- Simple, streamlined experience - -**Enhanced mini cart** (full product control): -- Set `enable-updating-product` to `true` -- Set `undo-remove-item` to `true` -- Set `cart-url` to `/cart` -- Set `start-shopping-url` to `/` for empty cart -- Customers can edit products and undo removals - -### Important notes - -- Uses default configuration values if custom settings are missing or invalid. -- All URL paths must point to valid pages on your site for navigation to work correctly. -``` - -**Improvements:** -1. ✅ Enhanced property descriptions with defaults and customer benefits -2. ✅ Complete common configurations section with 2 real-world scenarios -3. ✅ Additional important note about fallback behavior -4. ✅ Named configurations merchants can immediately identify with - ---- - -## Future Expansion Opportunities - -### High Priority (Next Sprint) - -1. **Add Common Configurations for All URL-Heavy Blocks** - - `product-details` (has cart-url) - - `commerce-login` (has redirect-url) - - `commerce-create-account` (has redirect-url) - - **Impact:** 3 more blocks with copy-pasteable examples - -2. **Extract Use Case Notes from README Examples** - - Many READMEs have "Example" or "Use Case" sections - - Can be transformed into "Best Practices" or "Tips" sections - - **Impact:** More contextual guidance beyond just configuration - -### Medium Priority - -3. **Add "What Customers See" Sections** - - Extract from Behavior Patterns sections - - Helps merchants understand customer experience - - **Format:** "When configured as X, customers will see Y" - -4. **Configuration Dependency Warnings** - - Some configs only work together - - Extract from Side Effects column - - **Example:** "Note: `enable-updating-product` requires configurable products in your catalog" - -### Low Priority (Future Consideration) - -5. **Performance Notes** - - Extract from README performance sections - - **Example:** "Large carts (50+ items) benefit from `max-items` setting" - -6. **Integration Notes** - - When blocks require other blocks - - **Example:** "Works with `commerce-checkout` block for seamless flow" - ---- - -## Testing Validation - -### Blocks Verified End-to-End - -**Multi-config blocks:** -- ✅ `commerce-cart` - All 3 enhancements (descriptions, common configs, important notes) -- ✅ `commerce-mini-cart` - All 3 enhancements -- ✅ `commerce-addresses` - Enhanced descriptions + important notes - -**Authentication-required blocks:** -- ✅ `commerce-addresses` - Authentication requirement note -- ✅ `commerce-orders-list` - Authentication + minified view guidance -- ✅ `commerce-returns-list` - Authentication + minified view guidance - -**B2B blocks:** -- ✅ `commerce-company-credit` - B2B requirement note - -**URL-heavy blocks:** -- ✅ `commerce-cart` - URL-specific descriptions -- ✅ `commerce-mini-cart` - URL-specific descriptions -- ✅ `commerce-wishlist` - URL-specific descriptions + fallback note - -**Zero-config blocks:** -- ✅ `product-list-page` - Clean, no unnecessary enhancements -- ✅ `commerce-checkout` - Only page metadata, no clutter -- ✅ `commerce-login` - Page metadata only - -### Quality Checks Passed - -- ✅ No duplicate content between sections -- ✅ No generic placeholder text remaining -- ✅ All enhancements are specific and actionable -- ✅ Grammar and punctuation consistent -- ✅ Code formatting (backticks) correct -- ✅ Smart activation prevents clutter on simple blocks - ---- - -## Files Modified - -### Generator Enhancement -**File:** `scripts/@generate-merchant-block-docs.js` - -**Functions Enhanced:** -1. `generateEnhancedPropertyDescription()` - Added 6 new pattern categories -2. `generateCommonConfigurations()` - Added 6 new block-specific patterns -3. `extractImportantNotes()` - Added 4 new extraction patterns - -**Lines Changed:** ~150 lines of enhancement logic - -### Documentation Regenerated -**All 57 merchant block MDX files** with expanded enhancements: -- Enhanced property descriptions: 100% of configured blocks -- Common configurations: 2 blocks (with 5 more ready-to-activate) -- Important notes: 7 blocks (75% increase) - ---- - -## Impact Summary - -### Quantitative Improvements -- **Common Configurations:** +100% coverage (1 → 2 blocks) -- **Important Notes:** +75% coverage (4 → 7 blocks) -- **Property Description Patterns:** +150% (4 → 10 patterns) -- **Lines of Generated Context:** ~300% increase per block - -### Qualitative Improvements -- **Merchant Decision Speed:** Reduced from "trial-and-error" to "copy-and-go" -- **Configuration Errors:** Prevented by specific format examples and warnings -- **Support Inquiries:** Reduced by comprehensive important notes -- **Confidence:** Increased by named scenarios matching real use cases - -### Merchant Feedback Readiness -Documentation now answers: -- ✅ "What does this setting do?" (Enhanced descriptions) -- ✅ "When should I use this?" (Common configurations) -- ✅ "What format does this need?" (Specific examples) -- ✅ "What do I need to be careful about?" (Important notes) -- ✅ "What will my customers see?" (Customer benefit context) - ---- - -## Rollout Status: COMPLETE ✅ - -All expanded enhancements are now live and generating comprehensive, actionable documentation for all 57 commerce blocks. - -**Generated:** December 7, 2025 -**Generator Version:** v1.3 (with expanded enhancements) -**Total Blocks Enhanced:** 57 -**Enhancement Layers:** 3 (descriptions, configurations, notes) -**Pattern Library:** 20+ specific patterns coded and active - diff --git a/_dropin-enrichments/merchant-blocks/IMPLEMENTATION-SUMMARY.md b/_dropin-enrichments/merchant-blocks/IMPLEMENTATION-SUMMARY.md deleted file mode 100644 index 8e79307ef..000000000 --- a/_dropin-enrichments/merchant-blocks/IMPLEMENTATION-SUMMARY.md +++ /dev/null @@ -1,276 +0,0 @@ -# Automated Update Detection - Implementation Summary - -## What Was Implemented - -The merchant block documentation generator now includes **automated change detection and tracking** to ensure enrichment files stay current with the boilerplate repository. - -## System Architecture - -### 1. **Metadata Tracking** - -Added to `descriptions.json`: - -```json -{ - "metadata": { - "last_verified_commit": "8e45ef4df347aef8fe89ac6e626e4d0222df319c", - "last_verified_date": "2025-12-07", - "boilerplate_branch": "b2b-suite-release1", - "total_blocks": 57, - "verified_blocks": 56, - "verification_method": "source-code-first" - } -} -``` - -### 2. **Change Detection Functions** - -Added to `scripts/@generate-merchant-block-docs.js`: - -- **`getBoilerplateCommitHash()`** - Gets current commit from boilerplate repo -- **`loadEnrichmentMetadata()`** - Loads metadata from enrichment file -- **`detectChanges()`** - Compares commits and identifies changed files -- **`updateEnrichmentMetadata()`** - Updates metadata after successful generation - -### 3. **Standalone Update Checker** - -Created `scripts/@check-for-updates.js`: -- Runs independently to check for changes -- Generates detailed change report -- Provides specific recommendations based on change type -- Saves report to `change-report.json` - -## User-Facing Changes - -### New Commands - -```bash -# Check for updates (standalone) -npm run check-for-updates - -# Or directly -node scripts/@check-for-updates.js - -# Verification commands (already existed, now in package.json) -npm run verify-merchant-configs -npm run verify-merchant-descriptions -``` - -### Enhanced Generator Output - -The generator now shows: - -**When no changes:** -``` -✅ No changes detected since last verification (2025-12-07) -``` - -**When changes detected:** -``` -⚠️ CHANGES DETECTED - Review recommended before generation - - 📝 Source code changes may affect configurations - 📖 README changes may affect descriptions - - 💡 Run verification after generation: - node scripts/@verify-block-configs-source-code.js - node scripts/@verify-merchant-block-descriptions.js - - ⚠️ Continuing with generation using current enrichments... -``` - -## Workflow Integration - -### Before (Manual): -1. Generate docs -2. Hope nothing changed upstream -3. Manually check if something seems wrong - -### After (Automated): -1. **System automatically checks** for changes -2. **Warns** if source code or READMEs changed -3. **Recommends** specific verification commands -4. **Tracks** metadata for next run -5. Generation continues (never fails) - -## Safety Features - -### ✅ Never Breaks Generation -- Warnings are shown but generation continues -- Uses current enrichments even if stale -- Better to have slightly outdated docs than failed builds - -### ✅ Manual Control Preserved -- Changes require manual review (Option B) -- No automatic overwrites of enrichments -- You decide when to update - -### ✅ Source Code Priority -- Configurations always extracted from `.js` files -- Only descriptions might be stale -- Metadata updates automatically after generation - -## Files Modified - -### Scripts: -1. **`scripts/@generate-merchant-block-docs.js`** - - Added change detection functions - - Integrated into main generation flow - - Auto-updates metadata after success - -2. **`scripts/@check-for-updates.js`** (NEW) - - Standalone update checker - - Generates detailed change reports - - Categorizes changes by type - -### Documentation: -1. **`_dropin-enrichments/merchant-blocks/AUTOMATED-UPDATE-WORKFLOW.md`** (NEW) - - Complete workflow guide - - Examples and scenarios - - Command reference - -2. **`_dropin-enrichments/merchant-blocks/README.md`** - - Updated to reference new workflow - - Added metadata description - -3. **`_dropin-enrichments/merchant-blocks/QUICK-REFERENCE.md`** - - Updated with new commands - - Added automated check step - -4. **`package.json`** - - Added `check-for-updates` script - - Added `verify-merchant-configs` script - - Added `verify-merchant-descriptions` script - -### Data: -1. **`_dropin-enrichments/merchant-blocks/descriptions.json`** - - Added `metadata` object - - Tracks commit hash, date, and verification stats - -## User Preferences Implemented - -All your choices from the questions: - -| Choice | Implementation | -|--------|----------------| -| **Option C**: Track commit hash | ✅ Metadata tracks `last_verified_commit` | -| **Option B**: Warn but require review | ✅ Warnings shown, no auto-updates | -| **Track all three**: configs, READMEs, other | ✅ Change report categorizes all three | -| **Option B**: Warn but continue | ✅ Generator continues with warnings | -| **Track commit + rely on git** | ✅ Commit hash in metadata, git for history | -| **Metadata recommendation** | ✅ All recommended fields included | - -## How It Works (Technical) - -### On Every Generation: - -```javascript -// 1. Get current boilerplate commit -const currentCommit = getBoilerplateCommitHash(); - -// 2. Load last verified commit -const metadata = loadEnrichmentMetadata(); -const lastCommit = metadata.last_verified_commit; - -// 3. Compare commits -if (currentCommit !== lastCommit) { - // 4. Use git diff to find changed files - const changedFiles = git diff --name-only lastCommit HEAD - - // 5. Categorize changes - const sourceCodeChanges = files matching blocks/*.js - const readmeChanges = files matching blocks/README.md - - // 6. Show warnings with specific recommendations - console.log('⚠️ CHANGES DETECTED'); - - // 7. Continue with generation -} - -// 8. After successful generation -updateEnrichmentMetadata(currentCommit); -``` - -### Standalone Checker: - -```javascript -// Same logic but: -// - More detailed output -// - Shows recent commits -// - Generates JSON report -// - Exits without generation -``` - -## Benefits - -### For You: -- **Awareness**: Know immediately when upstream changes -- **Specificity**: Know exactly what changed (code vs docs) -- **Guidance**: Get specific commands to verify changes -- **Confidence**: Metadata proves when last verified - -### For the System: -- **Traceability**: Git history shows verification timeline -- **Reproducibility**: Metadata enables recreation of any version -- **Safety**: Never fails generation, always warns - -## Next Steps - -### Normal Workflow: -```bash -# 1. Generate docs (auto-checks for updates) -npm run generate-merchant-docs - -# 2. If warnings appear, verify -npm run verify-merchant-configs -npm run verify-merchant-descriptions - -# 3. Update enrichments if needed -nano _dropin-enrichments/merchant-blocks/descriptions.json - -# 4. Regenerate (metadata auto-updates) -npm run generate-merchant-docs -``` - -### Proactive Checking: -```bash -# Check anytime without generating -npm run check-for-updates - -# Result: Detailed report of what changed -``` - -## Testing Results - -### Scenario 1: No Changes -``` -✅ NO CHANGES DETECTED - Enrichment files are up-to-date - No action required -``` - -### Scenario 2: With Changes (Simulated) -The system correctly: -- Identifies changed files -- Categorizes by type (source vs README) -- Provides specific recommendations -- Continues with generation -- Updates metadata - -## Documentation - -Three levels of documentation created: - -1. **`AUTOMATED-UPDATE-WORKFLOW.md`** - Complete guide (for learning) -2. **`QUICK-REFERENCE.md`** - Quick reference (for daily use) -3. **`README.md`** - Overview (for discovery) - -All three updated to reference the new system. - ---- - -**Implementation Date**: 2025-12-07 -**Boilerplate Commit**: 8e45ef4df347aef8fe89ac6e626e4d0222df319c -**Branch**: b2b-suite-release1 -**Status**: ✅ Fully Implemented and Tested - diff --git a/_dropin-enrichments/merchant-blocks/INTEGRATION-CONFIRMATION.md b/_dropin-enrichments/merchant-blocks/INTEGRATION-CONFIRMATION.md deleted file mode 100644 index fa2f08f2d..000000000 --- a/_dropin-enrichments/merchant-blocks/INTEGRATION-CONFIRMATION.md +++ /dev/null @@ -1,417 +0,0 @@ -# Merchant Documentation Enhancements - Integration Confirmation - -## ✅ All Enhancements Are Permanently Integrated - -All three enhancement categories are **fully integrated** into the merchant documentation generator. Every future generation will automatically include these enhancements. - ---- - -## Integration Architecture - -### Main Generation Flow - -**File:** `scripts/@generate-merchant-block-docs.js` - -**Function:** `generateMerchantBlockDoc()` (lines 1290-1361) - -```javascript -function generateMerchantBlockDoc(block, outputDir, boilerplateVersion) { - // 1. Generate base content - const description = generateMerchantDescription(block.name, block.path); - const documentAuthoringTable = generateDocumentAuthoringTable(block.name, block.configs); - const metadataTable = generateMetadataTable(block.name, block.displayName); - const requirementsSection = generateRequirementsSection(block.name, block.path); - - // 2. Build document content - let content = `--- frontmatter ---`; - content += description; - content += requirementsSection; - content += metadataTable; - - // 3. **ENHANCEMENT INTEGRATION POINT** - if (block.configs.length > 0) { - content += documentAuthoringTable; // Uses enhanced descriptions - - // ✅ COMMON CONFIGURATIONS (Enhancement #1) - const commonConfigs = generateCommonConfigurations(block.name, block.configs); - if (commonConfigs) { - content += commonConfigs; - } - - // ✅ IMPORTANT NOTES (Enhancement #2) - const importantNotes = generateImportantNotesSection(block.name, block.path, block.configs); - if (importantNotes) { - content += importantNotes; - } - } - - // 4. Add section metadata - content += generateSectionMetadataTable(block.name); - - // 5. Write file - writeFileSync(outputPath, content, 'utf8'); -} -``` - -**Integration Status:** ✅ **Lines 1332-1342 - Permanently integrated** - ---- - -## Enhancement #1: Enhanced Property Descriptions - -### Integration Point - -**Function:** `generateDocumentAuthoringTable()` (lines 955-1164) - -**Calls:** `generateEnhancedPropertyDescription()` (line 1153) - -```javascript -function generateDocumentAuthoringTable(blockName, configs) { - // ... generate configuration table ... - - // Property descriptions section - if (configsWithDescriptions.length > 0) { - output += `### Property descriptions\n\n`; - for (const config of configsWithDescriptions) { - const titleCaseName = toTitleCase(config.key); - - // ✅ ENHANCED PROPERTY DESCRIPTIONS (Enhancement #1) - const enhancedDesc = generateEnhancedPropertyDescription( - config.key, - config.description.trim(), - config.type, - config.default - ); - - output += `**${titleCaseName}**: ${enhancedDesc}\n\n`; - } - } - - return output; -} -``` - -**Enhancement Function:** `generateEnhancedPropertyDescription()` (lines 549-629) - -**Features Integrated:** -- ✅ Enable/show/hide toggle context -- ✅ URL-specific guidance (5 patterns: redirect, cart, checkout, shopping, generic) -- ✅ Minified view guidance -- ✅ Undo functionality customer benefits -- ✅ Max/limit/count guidance -- ✅ Attribute hiding format examples -- ✅ Default value display - -**Integration Status:** ✅ **Permanently integrated - Called on every property description** - ---- - -## Enhancement #2: Common Configurations - -### Integration Point - -**Function:** `generateMerchantBlockDoc()` (line 1333) - -```javascript -// Add common configurations section (for blocks with multiple options) -const commonConfigs = generateCommonConfigurations(block.name, block.configs); -if (commonConfigs) { - content += commonConfigs; -} -``` - -**Enhancement Function:** `generateCommonConfigurations()` (lines 631-729) - -**Block-Specific Patterns Integrated:** -- ✅ `commerce-cart` - Quick checkout vs. Full-featured cart -- ✅ `commerce-mini-cart` - Basic vs. Enhanced mini cart -- ✅ `commerce-addresses` - Full vs. Compact address management -- ✅ `commerce-wishlist` - Standard wishlist setup -- ✅ `commerce-login` - Standard login configuration -- ✅ `commerce-create-account` - Standard registration setup -- ✅ `product-details` - Standard product page -- ✅ Generic pattern for blocks with 3+ toggles - -**Activation Logic:** -```javascript -// Only generate for blocks with multiple boolean/toggle configs or URLs -const toggleConfigs = configs.filter(c => - c.type === 'boolean' || - c.key.includes('enable') || - c.key.includes('hide') || - c.key.includes('show') -); - -const urlConfigs = configs.filter(c => - c.key.includes('url') || c.key.includes('path') -); - -// Need at least 2 toggles OR 2 URLs to generate examples -if (toggleConfigs.length < 2 && urlConfigs.length < 2) { - return ''; // Smart prevention of clutter -} -``` - -**Integration Status:** ✅ **Permanently integrated - Automatically detects and generates** - ---- - -## Enhancement #3: Important Notes - -### Integration Point - -**Function:** `generateMerchantBlockDoc()` (line 1339) - -```javascript -// Add important notes section -const importantNotes = generateImportantNotesSection(block.name, block.path, block.configs); -if (importantNotes) { - content += importantNotes; -} -``` - -**Enhancement Function:** `generateImportantNotesSection()` (lines 739-762) - -**Calls:** `extractImportantNotes()` (lines 437-544) - -**Extraction Patterns Integrated:** - -1. **Authentication Requirements** (lines 445-456) - ```javascript - // Check for authentication requirements - if (overview.match(/authentication|authenticated|sign[- ]in|log[- ]in/i)) { - if (overview.match(/redirect.*login|authentication.*redirect|not authenticated.*redirect/i)) { - notes.push('Requires user authentication. Unauthenticated users are automatically redirected to the login page.'); - } - } - ``` - -2. **B2B/Company Requirements** (lines 459-465) - ```javascript - // Check for company/B2B requirements - if (overview.match(/company|B2B/i)) { - if (overview.match(/company.*enabled|B2B.*enabled|associated.*company/i)) { - notes.push('Requires Adobe Commerce B2B features to be enabled and the user to be associated with a company.'); - } - } - ``` - -3. **Error Handling/Fallback** (lines 483-489) - ```javascript - // Extract fallback behaviors (only if meaningful) - if (errorSection.match(/[Ff]allback.*default.*configuration/)) { - notes.push('Uses default configuration values if custom settings are missing or invalid.'); - } - ``` - -4. **URL Dependencies** (lines 503-510) - ```javascript - // Check for URL requirements (but avoid if already noted from configs) - const urlCount = (configSection.match(/-url`/g) || []).length; - if (urlCount >= 2 && !notes.some(n => n.includes('URL'))) { - notes.push('All URL paths must point to valid pages on your site for navigation to work correctly.'); - } - ``` - -5. **Configuration-Specific Notes** (lines 747-752) - ```javascript - // Add configuration-specific notes - const hasUrlConfigs = configs.some(c => c.key.includes('url') || c.key.includes('path')); - if (hasUrlConfigs && !notes.some(n => n.includes('URL'))) { - notes.push('URL paths must point to valid pages on your site for navigation to work correctly.'); - } - ``` - -**Integration Status:** ✅ **Permanently integrated - Auto-extracts from READMEs** - ---- - -## Verification: Run the Generator - -To confirm all enhancements are integrated, run: - -```bash -node scripts/@generate-merchant-block-docs.js -``` - -**What happens automatically:** - -1. **For every block with configurations:** - - ✅ Property descriptions are enhanced with context - - ✅ Common configurations section generated (if criteria met) - - ✅ Important notes section generated (if patterns detected) - -2. **For blocks without configurations:** - - ✅ Clean, simple documentation (no unnecessary sections) - - ✅ Section metadata table still generated - -3. **Smart activation:** - - ✅ Common configurations only appear when block has 2+ toggles or URLs - - ✅ Important notes only appear when README contains relevant patterns - - ✅ Property enhancements apply to ALL properties automatically - ---- - -## Future Generations Will Include - -### Every Time You Run the Generator: - -**Automatic Enhancements:** -- ✅ **Enhanced Property Descriptions** - All 10+ patterns applied automatically -- ✅ **Common Configurations** - 7 block-specific patterns + generic fallback -- ✅ **Important Notes** - 5 extraction patterns from READMEs - -**No Manual Work Required:** -- ✅ No templates to update separately -- ✅ No enrichment files to maintain for enhancements -- ✅ No post-processing scripts - -**Self-Maintaining:** -- ✅ Reads latest README content from boilerplate -- ✅ Detects new patterns automatically -- ✅ Smart activation prevents clutter - ---- - -## Adding New Patterns (Developer Guide) - -### To Add a New Common Configuration Pattern: - -**File:** `scripts/@generate-merchant-block-docs.js` -**Function:** `generateCommonConfigurations()` (line 631) - -1. Add new `else if (blockName === 'your-block')` branch -2. Define 2-3 configuration scenarios -3. Include exact settings and customer benefits -4. Test with real block - -**Example:** -```javascript -else if (blockName === 'commerce-your-block') { - output += `**Scenario name** (description):\n`; - output += `- Set \`config-key\` to \`value\`\n`; - output += `- Explanation of impact\n\n`; -} -``` - -### To Add a New Important Notes Pattern: - -**File:** `scripts/@generate-merchant-block-docs.js` -**Function:** `extractImportantNotes()` (line 437) - -1. Add new pattern detection (regex or keyword) -2. Extract relevant text from README sections -3. Format as merchant-friendly note -4. Add to `notes` array - -**Example:** -```javascript -// Look for new pattern in README -if (content.match(/your-pattern/i)) { - notes.push('Your merchant-friendly note here.'); -} -``` - -### To Add a New Property Description Pattern: - -**File:** `scripts/@generate-merchant-block-docs.js` -**Function:** `generateEnhancedPropertyDescription()` (line 549) - -1. Detect property type (by key, type, or value) -2. Add contextual information to `additions` array -3. Ensure grammar works with existing description -4. Test across multiple blocks - -**Example:** -```javascript -// For your-type properties -if (cleanKey.includes('your-pattern')) { - if (!enhanced.toLowerCase().includes('existing-context')) { - additions.push('Your contextual guidance here'); - } -} -``` - ---- - -## Integration Checklist - -When the generator runs, it automatically: - -- [x] **Line 1153** - Calls `generateEnhancedPropertyDescription()` for every property -- [x] **Line 1333** - Calls `generateCommonConfigurations()` for configured blocks -- [x] **Line 1339** - Calls `generateImportantNotesSection()` for all blocks -- [x] **Line 437** - Calls `extractImportantNotes()` to parse README -- [x] **Lines 549-629** - Applies 10+ enhancement patterns to descriptions -- [x] **Lines 631-729** - Evaluates 7+ configuration scenarios -- [x] **Lines 437-544** - Extracts 5+ types of important notes - -**All checkboxes are permanently checked** ✅ - ---- - -## Generator Status: PRODUCTION READY - -**Version:** v1.3 (with expanded enhancements) -**Integration:** Complete -**Testing:** Verified across 57 blocks -**Documentation:** Complete -**Maintainability:** High (well-documented functions) - -**Next generation will automatically include all enhancements.** - ---- - -## Files That Contain Integration - -### Generator (Main Integration) -- ✅ `scripts/@generate-merchant-block-docs.js` (lines 437-762, 955-1164, 1290-1361) - -### Documentation (Reference) -- ✅ `_dropin-enrichments/merchant-blocks/ENHANCEMENTS-SUMMARY.md` -- ✅ `_dropin-enrichments/merchant-blocks/EXPANDED-ENHANCEMENTS-REPORT.md` -- ✅ `_dropin-enrichments/merchant-blocks/QUICK-REFERENCE.md` -- ✅ `_dropin-enrichments/merchant-blocks/INTEGRATION-CONFIRMATION.md` (this file) - -### No Separate Templates Required -- ❌ No template files need updating -- ❌ No enrichment files for enhancements -- ❌ No post-processing required - -**Everything is self-contained in the generator.** - ---- - -## Confirmation: Test It Yourself - -### Command: -```bash -cd /Users/bdenham/Sites/storefront -node scripts/@generate-merchant-block-docs.js -``` - -### What to Check: - -**Pick any block with configurations (e.g., `commerce-cart`):** -1. ✅ Property descriptions include "Set to `true` to..." and "Default: ..." -2. ✅ Common configurations section appears with named scenarios -3. ✅ Important notes section appears with URL warning - -**Pick any block without configurations (e.g., `commerce-checkout`):** -1. ✅ Clean, simple documentation -2. ✅ No empty sections -3. ✅ Section metadata still present - -**Pick any authentication-required block (e.g., `commerce-addresses`):** -1. ✅ Important notes include authentication requirement -2. ✅ Minified view description includes "checkout flows" guidance - -**All enhancements will appear automatically** - no manual intervention needed! - ---- - -**Integration Status: ✅ COMPLETE AND PERMANENT** - -Last Updated: December 7, 2025 -Generator Version: v1.3 - diff --git a/_dropin-enrichments/merchant-blocks/MERCHANT-INFORMATION-GAPS.md b/_dropin-enrichments/merchant-blocks/MERCHANT-INFORMATION-GAPS.md deleted file mode 100644 index ff9359566..000000000 --- a/_dropin-enrichments/merchant-blocks/MERCHANT-INFORMATION-GAPS.md +++ /dev/null @@ -1,234 +0,0 @@ -# Merchant Block Documentation - Information Gaps Analysis - -## Current State Assessment - -### ✅ What We Already Have (Complete) -1. **Block description** - Merchant-friendly overview -2. **Requirements section** - Prerequisites for B2B blocks -3. **Configuration table** - All configurable properties with defaults -4. **Property descriptions** - What each configuration does -5. **Page metadata** - Title, Robots, Cache-Control (for specific blocks) -6. **Section metadata** - Styling options with copy-pasteable examples - -### ⚠️ Potentially Missing (From README Files) - -#### 1. **URL Parameters** (Found in some blocks) -**What it is**: Query string parameters that change block behavior - -**Examples:** -- `commerce-b2b-negotiable-quote`: Uses `quoteid` parameter to switch views -- `commerce-b2b-negotiable-quote-template`: Uses `quoteTemplateId` parameter -- `commerce-b2b-po-approval-rule-form`: Uses `approvalRuleId` for editing - -**Merchant Value**: -- ❌ **LOW** - Merchants don't manually construct these URLs -- ❌ URLs are generated automatically by the blocks -- ❌ Technical implementation detail, not merchant-configurable - -**Recommendation**: **DO NOT ADD** - This is developer-focused - ---- - -#### 2. **Event Listeners/Emitters** (Found in all READMEs) -**What it is**: JavaScript events that blocks listen to or emit - -**Examples:** -- Cart listens to `cart/data`, `wishlist/alert`, `quote-management/initialized` -- Quote block listens to `quote-management/quote-deleted` - -**Merchant Value**: -- ❌ **NONE** - Completely technical/developer-focused -- ❌ Merchants can't configure or control events -- ❌ No actionable information for merchants - -**Recommendation**: **DO NOT ADD** - Pure developer documentation - ---- - -#### 3. **Behavior Patterns** (Found in most READMEs) -**What it is**: How blocks behave in different contexts - -**Examples from commerce-cart:** -- "When cart is empty, shows empty cart message" -- "When cart has items, shows full interface" -- "Configurable products show edit buttons when editing enabled" - -**Merchant Value**: -- ⚠️ **MEDIUM** - Helps merchants understand what to expect -- ✅ Some patterns directly relate to configurations -- ⚠️ Most are automatic behaviors merchants can't control - -**Recommendation**: **SELECTIVE** - Only add behavior that explains configuration impact - ---- - -#### 4. **User Interaction Flows** (Found in complex blocks) -**What it is**: Step-by-step user journey through the block - -**Examples from commerce-cart:** -- "Cart Display → Item Management → Product Editing → Checkout" -- Quote request flow with threshold warnings - -**Merchant Value**: -- ❌ **LOW** - Describes end-user UX, not merchant configuration -- ❌ No actionable information -- ❌ Merchants can't change these flows - -**Recommendation**: **DO NOT ADD** - End-user documentation, not merchant docs - ---- - -#### 5. **Error Handling** (Found in all READMEs) -**What it is**: How blocks handle errors and edge cases - -**Examples:** -- "If mini-PDP fails, shows error notification" -- "If cart data is invalid, treats cart as empty" -- "Falls back to defaults for missing configuration" - -**Merchant Value**: -- ❌ **NONE** - Technical implementation details -- ❌ Merchants can't configure error handling -- ❌ No actions merchants can take - -**Recommendation**: **DO NOT ADD** - Technical/developer information - ---- - -#### 6. **Local Storage** (Found in some READMEs) -**What it is**: Browser storage keys used by blocks - -**Merchant Value**: -- ❌ **NONE** - Technical implementation -- ❌ Not configurable by merchants - -**Recommendation**: **DO NOT ADD** - Developer-focused - ---- - -#### 7. **Hardcoded Settings** (Found in some B2B blocks) -**What it is**: Settings that are not configurable but exist in code - -**Example from commerce-b2b-negotiable-quote:** -``` -| showItemRange | boolean | true | Shows the item range text | -| showPageSizePicker | boolean | true | Shows the page size picker | -| showPagination | boolean | true | Shows the pagination controls | -``` - -**Merchant Value**: -- ❌ **CONFUSING** - Shows settings merchants CAN'T change -- ❌ Misleading to document non-configurable options -- ❌ No actionable value - -**Recommendation**: **DO NOT ADD** - Would confuse merchants about what they can control - ---- - -## Recommendations by Information Type - -### ✅ Keep Current Content (Good for Merchants) -1. Block descriptions (what it does) -2. Requirements (prerequisites) -3. Configuration tables (what merchants can change) -4. Property descriptions (how to use each option) -5. Page/Section metadata (document authoring setup) - -### ⚠️ Consider Adding (Context-Dependent) -**ONLY if it directly explains configuration impact:** - -Example for `enable-estimate-shipping` in cart: -```markdown -**Enable Estimate Shipping**: Enables shipping estimation functionality. -*When enabled, customers can estimate shipping costs before checkout.* -``` - -This adds context but stays merchant-focused. - -### ❌ Do NOT Add (Developer-Focused) -1. URL Parameters -2. Event listeners/emitters -3. Local storage keys -4. Error handling details -5. User interaction flows (end-user UX) -6. Technical implementation details -7. Hardcoded settings (non-configurable) - ---- - -## Current Assessment - -### Merchant Documentation is Complete ✅ - -The current merchant block pages contain **exactly what merchants need**: -1. ✅ What the block does (description) -2. ✅ What they must have enabled (requirements) -3. ✅ What they can configure (configuration table) -4. ✅ How to use each setting (property descriptions) -5. ✅ How to add it to their page (metadata tables) - -### Everything in READMEs Not in Merchant Docs is Intentionally Excluded - -The README files contain comprehensive **developer documentation** that includes: -- Technical implementation details -- JavaScript API usage -- Event systems -- Error handling -- URL routing -- Browser storage - -**None of this is relevant for merchant authoring.** - ---- - -## Conclusion - -**✅ NO GAPS FOUND** - -The merchant documentation is **complete and appropriate** for the merchant audience. All information from boilerplate READMEs that is **relevant to merchants** has been extracted: -- Configurations (source-code verified ✅) -- Requirements (extracted from READMEs ✅) -- Descriptions (enriched and verified ✅) -- Metadata (both page and section ✅) - -The information **not** included from READMEs is: -- **Intentionally excluded** because it's developer-focused -- **Not actionable** for merchants -- **Would add confusion** rather than value - -**Recommendation**: **No changes needed** - Documentation is complete for merchant audience. - ---- - -## Alternative: Enhanced Context (Optional) - -If you want to add more **merchant-relevant context** without technical details, consider: - -### Option A: "What Customers See" Brief -Add a short sentence after configuration table: - -```markdown -## Configuration - -[configuration table] - -**What customers experience**: When enabled, customers can [specific visible behavior]. -``` - -### Option B: Common Use Cases -Add brief examples: - -```markdown -### Common configurations - -**Minimal cart**: Set `enable-item-quantity-update` to `false` for a streamlined checkout experience. - -**Full-featured cart**: Enable all options for maximum customer control. -``` - -**But**: This might be overkill given descriptions already explain each option. - ---- - -**Final Recommendation**: The documentation is **merchant-complete** as-is. Any additions would risk adding developer-focused complexity that merchants don't need. - diff --git a/_dropin-enrichments/merchant-blocks/QUICK-REFERENCE.md b/_dropin-enrichments/merchant-blocks/QUICK-REFERENCE.md deleted file mode 100644 index 1f1745a88..000000000 --- a/_dropin-enrichments/merchant-blocks/QUICK-REFERENCE.md +++ /dev/null @@ -1,152 +0,0 @@ -# Merchant Block Descriptions - Quick Reference - -## 🆕 Automated Update Detection - -The system now tracks changes automatically! - -```bash -# Check if boilerplate has updates -node scripts/@check-for-updates.js -``` - -**Result:** -- ✅ No changes = No action needed -- ⚠️ Changes detected = Follow recommendations in output - -## 🚀 Quick Workflow (3 Minutes) - -```bash -# 1. Check for boilerplate updates (NEW!) -node scripts/@check-for-updates.js - -# 2. Verify descriptions (if changes detected) -node scripts/@verify-merchant-block-descriptions.js - -# 3. Verify configurations (if source code changed) -node scripts/@verify-block-configs-source-code.js - -# 4. Update enrichment if needed -nano _dropin-enrichments/merchant-blocks/descriptions.json - -# 5. Regenerate documentation (auto-updates metadata) -node scripts/@generate-merchant-block-docs.js - -# 6. Verify output -cat src/content/docs/merchants/blocks/commerce-[block-name].mdx | head -10 -``` - -## 📋 Checklist - -- [ ] Check for boilerplate updates (`@check-for-updates.js`) -- [ ] Run verification script (if changes detected) -- [ ] Review any blocks marked "NEEDS REVIEW" -- [ ] Update `descriptions.json` with accurate descriptions -- [ ] Set `"verified": true` for reviewed blocks -- [ ] Regenerate merchant block docs (auto-updates commit hash) -- [ ] Spot-check generated pages -- [ ] Commit changes to git - -## 📝 Description Template - -```json -"block-name": { - "description": "Action verb + what merchants can do/see.", - "verified": true, - "source": "README: brief note from Overview section" -} -``` - -## ✅ Good Description Examples - -| Block | Description | -|-------|-------------| -| cart | Configure the shopping cart page to display product details, pricing, and checkout options. | -| mini-cart | Display a compact cart dropdown with product management and checkout options. | -| checkout | Provide a comprehensive one-page checkout with payment processing and order placement. | -| wishlist | Manage product wishlist with authentication and cart integration. | -| b2b-po-status | Display purchase order status with approval actions and real-time updates. | - -## 📂 Key Files - -| File | Purpose | -|------|---------| -| `descriptions.json` | Verified merchant-friendly descriptions | -| `README.md` | Full maintenance workflow documentation | -| `QUICK-REFERENCE.md` | This file - quick lookup guide | -| `ENHANCEMENTS-SUMMARY.md` | Details on enhanced property descriptions, common configs, and important notes | -| `EXPANDED-ENHANCEMENTS-REPORT.md` | Complete expansion details with before/after comparisons | -| `INTEGRATION-CONFIRMATION.md` | Proof that all enhancements are permanently integrated into the generator | - -## 🔍 Source of Truth - -- **Location**: `.temp-repos/boilerplate/blocks/[block-name]/README.md` -- **Branch**: `b2b-suite-release1` -- **Section**: `## Overview` (first paragraph) - -## ⚡ Common Commands - -```bash -# Verify all blocks -node scripts/@verify-merchant-block-descriptions.js - -# Verify specific block README -cat .temp-repos/boilerplate/blocks/commerce-cart/README.md - -# Regenerate all merchant docs -node scripts/@generate-merchant-block-docs.js - -# Check generated page -cat src/content/docs/merchants/blocks/commerce-cart.mdx | head -10 - -# Update boilerplate repository -cd .temp-repos/boilerplate -git fetch origin -git checkout b2b-suite-release1 -git pull origin b2b-suite-release1 -``` - -## 🎯 Priority System - -The generator uses this priority order: - -1. **Priority 1** (BEST): Verified descriptions in `descriptions.json` -2. **Priority 2**: Auto-extracted from README files -3. **Priority 3**: Fallback generic template - -**Always aim for Priority 1** by setting `"verified": true` after review. - -## 📐 Description Rules - -**Start with these action verbs:** -- Display, Manage, Provide, Handle, Create, Show, Configure, Enable, Set up - -**Length:** -- Aim for under 100 characters -- Be specific and actionable - -**Avoid:** -- Technical jargon (dropin names, container names) -- Vague phrases ("Configure the block") -- Developer terminology - -## 🆘 Quick Troubleshooting - -| Problem | Solution | -|---------|----------| -| Wrong description in docs | Set `"verified": true` in `descriptions.json` | -| Block not found | Update boilerplate repo: `cd .temp-repos/boilerplate && git pull` | -| No README Overview | Add verified description manually with note | -| Technical description | Override with merchant-friendly version in `descriptions.json` | - -## 📅 When to Update - -- ✅ New blocks added to boilerplate -- ✅ Block functionality changes -- ✅ Before major doc releases -- ✅ Quarterly reviews -- ✅ User-reported inaccuracies - -## 🎓 Full Documentation - -For complete details, see: `_dropin-enrichments/merchant-blocks/README.md` - diff --git a/_dropin-enrichments/merchant-blocks/SYSTEM-DIAGRAM.md b/_dropin-enrichments/merchant-blocks/SYSTEM-DIAGRAM.md deleted file mode 100644 index 498697a8e..000000000 --- a/_dropin-enrichments/merchant-blocks/SYSTEM-DIAGRAM.md +++ /dev/null @@ -1,315 +0,0 @@ -# Automated Update Detection System - Visual Guide - -## System Flow Diagram - -```mermaid -graph TD - A[Run Generator] --> B{Check Boilerplate Commit} - B -->|Different from Last| C[Detect Changes] - B -->|Same as Last| D[✅ No Changes] - - C --> E{What Changed?} - E -->|Source Code .js| F[⚠️ Config Changes] - E -->|README.md| G[⚠️ Description Changes] - E -->|Both| H[⚠️ Both Need Review] - - F --> I[Show Warning] - G --> I - H --> I - D --> J[Continue Generation] - I --> J - - J --> K[Generate All Docs] - K --> L[Update Metadata] - L --> M[✅ Complete] - - style F fill:#ff9 - style G fill:#ff9 - style H fill:#ff9 - style D fill:#9f9 - style M fill:#9f9 -``` - -## Data Flow Diagram - -```mermaid -graph LR - A[Boilerplate Repo
b2b-suite-release1] -->|git clone| B[.temp-repos/boilerplate] - B -->|Extract Configs| C[Block .js Files] - B -->|Extract Descriptions| D[README Files] - - C --> E[Source Code Parser] - D --> F[README Parser] - - E -->|readBlockConfig calls| G[Configuration Data] - F -->|Overview section| H[Description Data] - - I[descriptions.json
Enrichment File] -->|Verified Descriptions| J[Merge Layer] - - G --> J - H --> J - - J --> K[Generate MDX Files] - K --> L[Merchant Docs] - - B -->|git rev-parse HEAD| M[Current Commit Hash] - I -->|metadata| N[Last Verified Commit] - - M --> O{Compare Commits} - N --> O - - O -->|Different| P[⚠️ Show Warnings] - O -->|Same| Q[✅ Skip Warnings] - - P --> K - Q --> K - - K -->|After Success| R[Update Metadata] - R --> I - - style I fill:#9cf - style M fill:#fcf - style N fill:#fcf - style P fill:#ff9 -``` - -## File Relationship Diagram - -```mermaid -graph TD - A[descriptions.json] -->|Metadata| B[last_verified_commit] - A -->|Block Data| C[Block Descriptions] - - D[Boilerplate Repo] -->|Current| E[8e45ef4df...] - - B -->|Compare| F{Same?} - E -->|Compare| F - - F -->|No| G[Run Verification] - F -->|Yes| H[Skip Verification] - - G --> I[@verify-block-configs-source-code.js] - G --> J[@verify-merchant-block-descriptions.js] - - I -->|Finds| K[Config Mismatches] - J -->|Finds| L[Description Changes] - - K --> M[Update descriptions.json] - L --> M - - M --> N[@generate-merchant-block-docs.js] - - N --> O[Generate All .mdx Files] - O --> P[Update Metadata] - P --> A - - style A fill:#9cf - style E fill:#fcf - style G fill:#ff9 - style M fill:#f96 -``` - -## Workflow Decision Tree - -```mermaid -graph TD - Start([Want to Generate Docs]) --> Check[Run check-for-updates] - - Check --> Q1{Changes
Detected?} - - Q1 -->|No| Gen1[Run Generator] - Q1 -->|Yes| Q2{What Type?} - - Q2 -->|Source Code| V1[Run verify-configs] - Q2 -->|README| V2[Run verify-descriptions] - Q2 -->|Both| V3[Run Both Verifiers] - - V1 --> R1{Issues
Found?} - V2 --> R2{Issues
Found?} - V3 --> R3{Issues
Found?} - - R1 -->|Yes| U1[Update descriptions.json] - R1 -->|No| Gen2[Run Generator] - - R2 -->|Yes| U2[Update descriptions.json] - R2 -->|No| Gen2 - - R3 -->|Yes| U3[Update descriptions.json] - R3 -->|No| Gen2 - - U1 --> Gen2 - U2 --> Gen2 - U3 --> Gen2 - - Gen1 --> Done([✅ Complete]) - Gen2 --> Done - - style Q1 fill:#ff9 - style Q2 fill:#ff9 - style U1 fill:#f96 - style U2 fill:#f96 - style U3 fill:#f96 - style Done fill:#9f9 -``` - -## Change Detection Logic - -```mermaid -graph TD - A[Generator Starts] --> B[Load descriptions.json] - B --> C[Get metadata.last_verified_commit] - - D[Boilerplate Repo] --> E[git rev-parse HEAD] - E --> F[Current Commit Hash] - - C --> G{Compare Hashes} - F --> G - - G -->|Same| H[✅ No Changes] - G -->|Different| I[git diff commitA..commitB] - - I --> J[Get Changed Files List] - - J --> K{Filter by Pattern} - - K -->|blocks/*.js| L[Source Code Changes] - K -->|blocks/README.md| M[README Changes] - K -->|Other| N[Other Changes] - - L --> O[Count: X files] - M --> P[Count: Y files] - N --> Q[Count: Z files] - - O --> R{X > 0?} - P --> S{Y > 0?} - Q --> T[Log Count] - - R -->|Yes| U[⚠️ Warn: Config Verification Needed] - R -->|No| V[Skip Config Warning] - - S -->|Yes| W[⚠️ Warn: Description Verification Needed] - S -->|No| X[Skip Description Warning] - - H --> Y[Continue to Generation] - U --> Y - V --> Y - W --> Y - X --> Y - T --> Y - - Y --> Z[Generate All Docs] - Z --> AA[Update metadata] - AA --> AB[Save descriptions.json] - - style H fill:#9f9 - style U fill:#ff9 - style W fill:#ff9 - style AB fill:#9cf -``` - -## Metadata Update Flow - -```mermaid -sequenceDiagram - participant G as Generator - participant B as Boilerplate - participant E as Enrichment File - participant M as Metadata - - G->>B: Get current commit hash - B-->>G: 8e45ef4df... - - G->>E: Load metadata - E-->>G: last_verified: abc123... - - G->>G: Compare commits - - alt Commits Different - G->>B: git diff abc123..8e45ef4df - B-->>G: Changed files list - G->>G: Categorize changes - G->>G: Show warnings - else Commits Same - G->>G: Skip warnings - end - - G->>G: Generate all docs - - G->>M: Update metadata - M->>M: Set last_verified_commit = 8e45ef4df - M->>M: Set last_verified_date = today - M->>M: Count total_blocks - M->>M: Count verified_blocks - - M->>E: Write updated metadata - E-->>G: ✅ Success -``` - -## Command Hierarchy - -```mermaid -graph TD - A[npm Commands] --> B[check-for-updates] - A --> C[verify-merchant-configs] - A --> D[verify-merchant-descriptions] - A --> E[generate-merchant-docs] - - B --> F[@check-for-updates.js] - C --> G[@verify-block-configs-source-code.js] - D --> H[@verify-merchant-block-descriptions.js] - E --> I[@generate-merchant-block-docs.js] - - F --> J[Read descriptions.json] - G --> J - H --> J - I --> J - - F --> K[Read Boilerplate] - G --> K - H --> K - I --> K - - F --> L[Generate Report] - G --> M[Show Mismatches] - H --> N[Show Changes] - I --> O[Generate Docs] - - O --> P[Update Metadata] - P --> J - - style B fill:#9cf - style C fill:#9cf - style D fill:#9cf - style E fill:#f96 - style P fill:#9f9 -``` - -## Three-Tier Priority System - -```mermaid -graph TD - A[Need Description] --> B{Priority 1:
Enrichment Verified?} - - B -->|Yes| C[✅ Use Enrichment
descriptions.json] - B -->|No| D{Priority 2:
README Available?} - - D -->|Yes| E[📖 Extract from README
Overview section] - D -->|No| F{Priority 3:
Fallback} - - F --> G[⚠️ Generate generic:
Configure the X block] - - C --> H[Generate Doc] - E --> H - G --> H - - H --> I[Output: .mdx file] - - style C fill:#9f9 - style E fill:#ff9 - style G fill:#f99 -``` - ---- - -**These diagrams show the complete automated update detection system from multiple perspectives.** -