Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Webhook product update #168

Merged
merged 4 commits into from
Jul 1, 2024
Merged

Webhook product update #168

merged 4 commits into from
Jul 1, 2024

Conversation

jamalsoueidan
Copy link
Owner

@jamalsoueidan jamalsoueidan commented Jul 1, 2024

PR Type

Enhancement, Tests


Description

  • Added new webhook orchestration for product updates.
  • Implemented new webhook for product updates.
  • Added article update logic to product orchestration.
  • Refactored product update logic and added active field.
  • Simplified product categorization logic.
  • Fixed import paths in various test files.
  • Added new data files for orders with and without shipping.
  • Implemented webhookOrderProcess function and added related test.
  • Added new SSH tunnel script tunnel2.

Changes walkthrough 📝

Relevant files
Enhancement
11 files
update.ts
Add article update logic to product orchestration.             

src/functions/customer/orchestrations/product/update.ts

  • Added updateArticle and updateArticleName imports.
  • Added updateArticle activity call in the orchestrator.
  • Updated return object to include article.
  • +17/-1   
    update-product.ts
    Refactor product update logic and add active field.           

    src/functions/customer/orchestrations/product/update/update-product.ts

  • Modified product update logic to handle single rule categories.
  • Added active field to the product update.
  • +6/-4     
    product-categorize.ts
    Simplify product categorization logic.                                     

    src/functions/openai/services/product-categorize.ts

    • Simplified product categorization logic by removing filter.
    +1/-6     
    webhook-customer.function.ts
    Fix formatting and add TODO in webhook customer function.

    src/functions/webhook-customer.function.ts

  • Fixed formatting issues in error handling.
  • Added TODO comment for deleting content in Shopify.
  • +4/-2     
    webhook-order.function.ts
    Refactor import path for webhook order process.                   

    src/functions/webhook-order.function.ts

    • Moved webhookOrderProcess import to a new directory structure.
    +2/-2     
    data-order-with-shipping.ts
    Add data file for orders with shipping.                                   

    src/functions/webhook/order/data-order-with-shipping.ts

    • Added new data file for orders with shipping.
    +415/-1 
    data-order-with-without-shipping.ts
    Add data file for orders with and without shipping.           

    src/functions/webhook/order/data-order-with-without-shipping.ts

    • Added new data file for orders with and without shipping.
    +784/-1 
    data-order.ts
    Add data file for orders without fulfillment.                       

    src/functions/webhook/order/data-order.ts

    • Added new data file for orders without fulfillment.
    +372/-1 
    order.ts
    Implement webhook order process function.                               

    src/functions/webhook/order/order.ts

  • Implemented webhookOrderProcess function.
  • Added logic to preserve line-item properties.
  • +48/-1   
    update.ts
    Implement webhook orchestration for product updates.         

    src/functions/webhook/product/update.ts

    • Implemented new webhook orchestration for product updates.
    +53/-0   
    webook-product.function.ts
    Implement new webhook for product updates.                             

    src/functions/webook-product.function.ts

    • Implemented new webhook for product updates.
    +98/-0   
    Tests
    4 files
    get-by-group.spec.ts
    Fix import path in booking get-by-group test.                       

    src/functions/customer/services/booking/get-by-group.spec.ts

    • Fixed import path for orderWithoutShipping.
    +1/-1     
    range.spec.ts
    Fix import paths in booking range test.                                   

    src/functions/customer/services/booking/range.spec.ts

  • Fixed import paths for orderWithShipping and orderWithoutShipping.
  • +2/-2     
    get.spec.ts
    Fix import path in order get test.                                             

    src/functions/customer/services/order/get.spec.ts

    • Fixed import path for orderWithoutShipping.
    +1/-1     
    order.spec.ts
    Add test for webhook order process.                                           

    src/functions/webhook/order/order.spec.ts

    • Added new test for webhookOrderProcess.
    +24/-1   
    Configuration changes
    1 files
    package.json
    Add new SSH tunnel script.                                                             

    package.json

    • Added new SSH tunnel script tunnel2.
    +1/-0     

    💡 PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    This commit message captures the addition of article update functionality to the product update orchestration and the correction of import paths for order data in test files.
     - Add a new SSH tunnel script 'tunnel2' to package.json
     - Simplify the product categorization logic in product-categorize.ts by removing the filter and using all collection nodes
     - Implement a new webhook for product updates in webook-product.function.ts
     - Move webhookOrderProcess import to a new directory structure in webhook-order.function.ts
    @github-actions github-actions bot added enhancement New feature or request tests labels Jul 1, 2024
    Copy link

    github-actions bot commented Jul 1, 2024

    PR Reviewer Guide 🔍

    ⏱️ Estimated effort to review [1-5] 4
    🧪 Relevant tests Yes
    🔒 Security concerns No
    ⚡ Key issues to review Possible Bug:
    The logic in update-product.ts only applies tags if there is exactly one rule in the category's rule set. This might not be the intended behavior if categories with multiple rules also need processing.
    Code Duplication:
    Similar code patterns are used across multiple test files for handling orders with and without shipping. Consider refactoring to reduce duplication and improve maintainability.
    Error Handling:
    In webhook-customer.function.ts, the error handling could be improved by logging the error details to help with debugging.

    Copy link

    github-actions bot commented Jul 1, 2024

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Possible bug
    Add robust error handling around order parsing to prevent runtime errors

    Ensure that the Order.parse function properly handles cases where queueItem might not be a
    valid order object, potentially using a try-catch block or validation logic.

    src/functions/webhook/order/order.ts [13]

    -const order = Order.parse(queueItem);
    +let order;
    +try {
    +  order = Order.parse(queueItem);
    +} catch (error) {
    +  context.error(`Failed to parse order from queue item: ${error}`);
    +  throw error;
    +}
     
    Suggestion importance[1-10]: 10

    Why: Ensuring that the Order.parse function handles invalid input properly is critical for preventing runtime errors and maintaining the stability of the application.

    10
    Add error handling for the updateArticle activity call

    Consider handling the case where the updateArticle activity might fail or return an
    unexpected result. You can wrap the call in a try-catch block to handle any potential
    errors gracefully.

    src/functions/customer/orchestrations/product/update.ts [43-46]

    -const article: Awaited<ReturnType<typeof updateArticle>> =
    -  yield context.df.callActivity(
    +let article: Awaited<ReturnType<typeof updateArticle>>;
    +try {
    +  article = yield context.df.callActivity(
         updateArticleName,
         activityType<typeof updateArticle>(input)
       );
    +} catch (error) {
    +  console.error('Failed to update article:', error);
    +  // Handle error appropriately
    +}
     
    Suggestion importance[1-10]: 9

    Why: This suggestion adds important error handling to the updateArticle activity call, which can prevent the function from failing silently and allows for better debugging and error management.

    9
    Ensure rules is not undefined before iterating over it

    It's recommended to check if category.ruleSet?.rules is not only of length 1 but also not
    undefined before proceeding to iterate over it. This prevents potential runtime errors
    when rules is undefined.

    src/functions/customer/orchestrations/product/update/update-product.ts [98-101]

    -if (category.ruleSet?.rules.length === 1) {
    -  category.ruleSet?.rules.forEach((r) => {
    +if (category.ruleSet?.rules?.length === 1) {
    +  category.ruleSet.rules.forEach((r) => {
         tags.push(r.condition);
       });
     }
     
    Suggestion importance[1-10]: 8

    Why: This suggestion prevents potential runtime errors by ensuring that rules is defined before iterating over it, which is a good practice for robust code.

    8
    Privacy
    Improve privacy by anonymizing IP addresses

    Consider using a more secure method to handle IP addresses to ensure privacy and
    compliance with data protection regulations. Storing raw IP addresses can be sensitive.
    You might want to anonymize or hash IP addresses before storing them.

    src/functions/webhook/order/data-order-with-without-shipping.ts [5]

    -browser_ip: "176.89.108.222"
    +browser_ip: anonymizeIP("176.89.108.222")
     
    Suggestion importance[1-10]: 9

    Why: Anonymizing IP addresses is crucial for privacy and compliance with data protection regulations. This suggestion addresses a significant privacy concern.

    9
    Possible issue
    Add error handling for database operations to improve reliability

    Consider adding error handling for the findOne and findOneAndUpdate operations to manage
    potential database errors effectively.

    src/functions/webhook/order/order.ts [19-34]

    -const existingOrder = await OrderModel.findOne({ id: order.id });
    +const existingOrder = await OrderModel.findOne({ id: order.id }).catch(err => {
    +  context.error(`Error fetching existing order: ${err}`);
    +  throw err;
    +});
     return OrderModel.findOneAndUpdate({ id: order.id }, order, {
       new: true,
       upsert: true,
    +}).catch(err => {
    +  context.error(`Error updating order: ${err}`);
    +  throw err;
     });
     
    Suggestion importance[1-10]: 9

    Why: Adding error handling for database operations is crucial for ensuring the reliability and robustness of the application. This suggestion addresses potential runtime issues that could arise from database errors.

    9
    Enhancement
    Enhance error handling in the webhook function

    Implement actual error handling logic in the catch block instead of just returning an
    empty body. This could include logging the error or returning a meaningful error message
    to the caller.

    src/functions/webhook-customer.function.ts [130-131]

     } catch (err) {
    -  return { body: "" };
    +  console.error('Error processing webhook:', err);
    +  return { body: "Error processing request" };
     }
     
    Suggestion importance[1-10]: 8

    Why: This suggestion improves error handling by logging the error and returning a meaningful message, which aids in debugging and provides better feedback to the caller.

    8
    Data integrity
    Add validation for the email format to ensure data integrity

    To ensure data integrity and avoid potential bugs, validate the email field to ensure it
    is in a proper format before using it in your application.

    src/functions/webhook/order/data-order-with-without-shipping.ts [52]

    -email: "test@soueidan.com"
    +email: validateEmail("test@soueidan.com") ? "test@soueidan.com" : throw new Error("Invalid email format")
     
    Suggestion importance[1-10]: 8

    Why: Validating the email format ensures data integrity and prevents potential bugs related to invalid email addresses, which is important for reliable application behavior.

    8
    Best practice
    Use optional chaining for safer and cleaner property access

    Use TypeScript's optional chaining to simplify the property access and improve code
    safety.

    src/functions/webhook/order/order.ts [26-28]

    -if (existingItem) {
    -  newItem.properties = existingItem.properties;
    -}
    +newItem.properties = existingItem?.properties ?? newItem.properties;
     
    Suggestion importance[1-10]: 8

    Why: Using optional chaining simplifies the code and makes it safer by handling cases where properties might be undefined, reducing the risk of runtime errors.

    8
    Performance
    Optimize the data processing by including only necessary collection details

    Instead of stringifying all collections data, consider filtering or processing the data to
    include only necessary details. This can improve performance and reduce memory usage.

    src/functions/openai/services/product-categorize.ts [19]

    -const collectionsContext = JSON.stringify(data?.collections.nodes, null, 2);
    +const essentialCollections = data?.collections.nodes.map(node => ({
    +  id: node.id,
    +  title: node.title
    +}));
    +const collectionsContext = JSON.stringify(essentialCollections, null, 2);
     
    Suggestion importance[1-10]: 7

    Why: This suggestion improves performance and reduces memory usage by filtering the collections data to include only necessary details, which is beneficial for efficiency.

    7
    Maintainability
    Refactor repeated money object creation to a single function for better maintainability

    Refactor the hardcoded values for shop_money and presentment_money into a function that
    returns these objects to reduce redundancy and improve maintainability.

    src/functions/webhook/order/data-order-with-without-shipping.ts [29-30]

    -shop_money: { amount: "0.00", currency_code: "DKK" },
    -presentment_money: { amount: "0.00", currency_code: "DKK" }
    +shop_money: getMoneyObject("0.00", "DKK"),
    +presentment_money: getMoneyObject("0.00", "DKK")
     
    Suggestion importance[1-10]: 7

    Why: Refactoring repeated code into a function improves maintainability and reduces redundancy, making the codebase cleaner and easier to manage.

    7
    Refactor line item mapping to a separate function for clarity

    Refactor the mapping logic inside the if condition to a separate function for better code
    readability and maintainability.

    src/functions/webhook/order/order.ts [20-31]

     if (existingOrder) {
    -  order.line_items = order.line_items.map((newItem) => {
    -    const existingItem = existingOrder.line_items.find(
    -      (eItem) => eItem.id === newItem.id
    -    );
    +  order.line_items = mapLineItems(order.line_items, existingOrder.line_items);
    +}
    +
    +function mapLineItems(newItems, existingItems) {
    +  return newItems.map(newItem => {
    +    const existingItem = existingItems.find(eItem => eItem.id === newItem.id);
         if (existingItem) {
           newItem.properties = existingItem.properties;
         }
         return newItem;
       });
     }
     
    Suggestion importance[1-10]: 7

    Why: Refactoring the mapping logic into a separate function improves code readability and maintainability, making it easier to understand and manage.

    7

    @jamalsoueidan jamalsoueidan merged commit 92e6267 into main Jul 1, 2024
    3 checks passed
    @jamalsoueidan jamalsoueidan deleted the webhook-product-update branch July 1, 2024 00:57
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    1 participant