Skip to content

chore: product variant modal rework#376

Merged
hmbanan666 merged 1 commit into
mainfrom
product-variant
Apr 15, 2025
Merged

chore: product variant modal rework#376
hmbanan666 merged 1 commit into
mainfrom
product-variant

Conversation

@hmbanan666

@hmbanan666 hmbanan666 commented Apr 15, 2025

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Added a delete button to the product variant update form, allowing users to delete product variants directly from the update interface.
    • Introduced clear buttons for nutrition input fields, enabling users to easily reset individual values.
  • Improvements

    • Nutrition fields in product variant forms now accept and display zero or null values, improving accuracy and flexibility.
    • The display of nutrition information is more consistent, showing available values even if some are zero.
  • Removals

    • Removed the standalone product variant delete form and button from the modal interface.

@hmbanan666 hmbanan666 self-assigned this Apr 15, 2025
@coderabbitai

coderabbitai Bot commented Apr 15, 2025

Copy link
Copy Markdown

Walkthrough

This update modifies how nutritional information is handled and displayed for product variants across several components. The input fields for nutrition in the update form now allow clearing values to null, and the schema is updated to accept null for these fields. The logic for displaying nutrition facts is refined to show the container consistently, with each value shown only if defined. The deletion workflow for product variants is refactored: the dedicated delete form component is removed, and its functionality is integrated into the update form, which now includes a delete button and logic. Modal and page-level nutrition rendering logic is also simplified.

Changes

File(s) Change Summary
apps/web-app/app/components/CommandCenter/ProductVariantCard.vue
apps/web-app/app/pages/catalog/[categorySlug]/[productSlug]/index.vue
Refined conditional rendering logic for nutrition info: containers are always rendered, and each nutrient is shown only if its value is not null. Page-level check simplified to only require calories to be present.
apps/web-app/app/components/Form/UpdateProductVariant.vue Nutrition input fields now allow clearing to null with clear buttons; step attributes updated; added a delete button and onDelete method for deleting product variants directly from the update form.
apps/web-app/app/components/Form/DeleteProductVariant.vue Deleted the dedicated product variant deletion component and its associated logic and events.
apps/web-app/app/components/Modal/UpdateProductVariant.vue Simplified modal template by removing the delete form component; only the update form remains.
packages/core/shared/services/product.ts Updated product variant update schema to allow null values for nutrition fields (calories, protein, fat, carbohydrate).

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant UpdateForm
    participant API
    participant ChannelStore
    participant Toast

    User->>UpdateForm: Clicks Delete Button
    UpdateForm->>Toast: Show "Deleting..." action toast
    UpdateForm->>API: DELETE /api/product-variant/{id}
    alt Success
        API-->>UpdateForm: 200 OK
        UpdateForm->>ChannelStore: Update after deletion
        UpdateForm->>Toast: Show success message
        UpdateForm->>User: Emit "success" event
    else Failure
        API-->>UpdateForm: Error
        UpdateForm->>Toast: Show error message
    end
Loading

Possibly related PRs

Poem

A nibble of code, a byte of delight,
Nutrition fields now clear as light.
Delete with a click, no extra detour,
Update and toast—your workflow is pure!
With nulls now allowed, the schema feels right,
Hopping ahead, the product's in sight!
🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@sonarqubecloud

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
apps/web-app/app/components/Form/UpdateProductVariant.vue (1)

254-270: Delete implementation looks good, consider refactoring common code.

The onDelete method follows the same pattern as onSubmit with proper error handling and user feedback. Consider extracting the common toast and emit logic into a shared helper function to reduce duplication.

+ function handleActionResult(success: boolean, message?: string) {
+   if (success) {
+     actionToast.success(message || '')
+     emit('success')
+   } else {
+     actionToast.error()
+   }
+ }

async function onSubmit(event: FormSubmitEvent<ProductVariantUpdateSchema>) {
  actionToast.start()
  emit('submitted')

  try {
    await $fetch(`/api/product/variant/${productVariantId}`, {
      method: 'PATCH',
      body: event.data,
    })

    await channel.update()
-   actionToast.success(t('toast.variant-updated'))
-   emit('success')
+   handleActionResult(true, t('toast.variant-updated'))
  } catch (error) {
    console.error(error)
-   actionToast.error()
+   handleActionResult(false)
  }
}

async function onDelete() {
  actionToast.start()
  emit('submitted')

  try {
    await $fetch(`/api/product/variant/${productVariantId}`, {
      method: 'DELETE',
    })

    await channel.update()
-   actionToast.success(t('toast.variant-deleted'))
-   emit('success')
+   handleActionResult(true, t('toast.variant-deleted'))
  } catch (error) {
    console.error(error)
-   actionToast.error()
+   handleActionResult(false)
  }
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 946d3bf and 6b9f223.

📒 Files selected for processing (6)
  • apps/web-app/app/components/CommandCenter/ProductVariantCard.vue (1 hunks)
  • apps/web-app/app/components/Form/DeleteProductVariant.vue (0 hunks)
  • apps/web-app/app/components/Form/UpdateProductVariant.vue (2 hunks)
  • apps/web-app/app/components/Modal/UpdateProductVariant.vue (1 hunks)
  • apps/web-app/app/pages/catalog/[categorySlug]/[productSlug]/index.vue (1 hunks)
  • packages/core/shared/services/product.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/web-app/app/components/Form/DeleteProductVariant.vue
🔇 Additional comments (8)
packages/core/shared/services/product.ts (1)

46-49: Schema enhancement for nullable nutrition fields

The schema now explicitly allows null values for nutrition fields (calories, protein, fat, and carbohydrate) by adding .nullable(). This is a good improvement that allows form inputs to properly clear these fields to null rather than just omitting them.

This change aligns well with the frontend updates in other files that now use explicit != null checks when rendering nutrition information.

apps/web-app/app/components/Modal/UpdateProductVariant.vue (1)

4-8: UI simplification with consolidated functionality

The modal component has been simplified by removing unnecessary wrappers and the separate delete form component. This indicates that the delete functionality has likely been integrated into the update form itself, creating a more streamlined user experience.

This consolidation is a good UX improvement that keeps all variant-related actions in one place.

apps/web-app/app/pages/catalog/[categorySlug]/[productSlug]/index.vue (1)

62-62: Simplified nutrition display logic

The condition for displaying the nutrition section has been improved to check only if calories != null instead of using a more complex computed property. This aligns with the schema changes that now explicitly handle nullable nutrition fields.

This simplification makes the code more maintainable while properly handling cases where nutrition values might be zero but still valid to display.

apps/web-app/app/components/CommandCenter/ProductVariantCard.vue (1)

16-29: Improved conditional rendering for nutrition values

The nutrition container is now always rendered, with each individual nutrition value conditionally displayed based on explicit != null checks. This is a great improvement that:

  1. Makes the layout more consistent by always rendering the container
  2. Properly handles zero values by using explicit null checks instead of truthiness
  3. Aligns with the schema changes that now support nullable nutrition fields

This approach ensures that valid zero values will be displayed correctly while still hiding undefined or null values.

apps/web-app/app/components/Form/UpdateProductVariant.vue (4)

83-94: Great UX enhancement with the clear button for nutrition fields.

Adding a clear button for the calories field improves usability by allowing users to easily reset the value to null when needed. The conditional display ensures it only appears when there's an actual value to clear.


101-101: Good improvement to protein input precision and clearing.

The change from "any" to 0.1 step provides more appropriate precision for protein values. The added clear button maintains consistency with the other nutrition fields.

Also applies to: 104-115


122-122: Appropriate step precision and clearing for fat values.

Using 0.1 step for fat values matches nutritional standards, and the clear button implementation is consistent with other fields.

Also applies to: 125-136


143-143: Consistent implementation for carbohydrate field.

The carbohydrate input follows the same pattern as protein and fat with appropriate step value and clear button functionality.

Also applies to: 146-157

Comment on lines +162 to +181
<div class="mt-3 flex flex-row gap-3">
<UButton
type="submit"
variant="solid"
color="primary"
size="xl"
block
>
{{ $t('center.update.title') }}
</UButton>

<UButton
variant="soft"
color="error"
size="xl"
icon="i-lucide-trash-2"
class="aspect-square justify-center"
@click="onDelete"
/>
</div>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider adding a confirmation dialog for deletion.

While the UI layout with the delete button is clean, delete operations are destructive actions. Consider adding a confirmation dialog before proceeding with deletion to prevent accidental data loss.

 <UButton
   variant="soft"
   color="error"
   size="xl"
   icon="i-lucide-trash-2"
   class="aspect-square justify-center"
-  @click="onDelete"
+  @click="showDeleteConfirmation = true"
 />

+ <UModal v-model="showDeleteConfirmation">
+   <UCard>
+     <template #header>
+       <div class="flex items-center gap-2">
+         <UIcon name="i-lucide-alert-triangle" class="text-error-500" />
+         <h3 class="text-lg font-semibold">{{ $t('common.delete-confirmation') }}</h3>
+       </div>
+     </template>
+     <p>{{ $t('center.product.variant-delete-confirmation') }}</p>
+     <template #footer>
+       <div class="flex justify-end gap-2">
+         <UButton color="neutral" @click="showDeleteConfirmation = false">
+           {{ $t('common.cancel') }}
+         </UButton>
+         <UButton color="error" @click="confirmDelete">
+           {{ $t('common.delete') }}
+         </UButton>
+       </div>
+     </template>
+   </UCard>
+ </UModal>

You would also need to add these to your script:

const showDeleteConfirmation = ref(false)

async function confirmDelete() {
  showDeleteConfirmation.value = false
  await onDelete()
}

@hmbanan666 hmbanan666 merged commit 2aa4c9a into main Apr 15, 2025
@hmbanan666 hmbanan666 deleted the product-variant branch April 15, 2025 09:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant