Compare commits
8 Commits
feature/is
...
12c5304638
| Author | SHA1 | Date | |
|---|---|---|---|
| 12c5304638 | |||
|
|
080d2424c8 | ||
|
|
6b1c34ceff | ||
| 231f594004 | |||
|
|
7d35a3e7b3 | ||
| 670b2f9200 | |||
|
|
521e3f552f | ||
| 627e970986 |
@@ -68,37 +68,7 @@
|
|||||||
|
|
||||||
<!-- Tags -->
|
<!-- Tags -->
|
||||||
<UFormGroup label="Tags" hint="Optional">
|
<UFormGroup label="Tags" hint="Optional">
|
||||||
<div class="space-y-2">
|
<TagsTagPicker v-model="selectedTags" />
|
||||||
<!-- Selected Tags -->
|
|
||||||
<div v-if="selectedTags.length > 0" class="flex flex-wrap gap-1 mb-2">
|
|
||||||
<UBadge
|
|
||||||
v-for="tag in selectedTags"
|
|
||||||
:key="tag.id"
|
|
||||||
:style="{ backgroundColor: tag.color }"
|
|
||||||
class="text-white cursor-pointer"
|
|
||||||
@click="removeTag(tag.id)"
|
|
||||||
>
|
|
||||||
{{ tag.icon }} {{ tag.name }} ✕
|
|
||||||
</UBadge>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Tag Selection by Category -->
|
|
||||||
<div v-for="category in tagCategories" :key="category.name" class="space-y-1">
|
|
||||||
<p class="text-xs font-medium text-gray-500 uppercase">{{ category.name }}</p>
|
|
||||||
<div class="flex flex-wrap gap-1">
|
|
||||||
<UButton
|
|
||||||
v-for="tag in category.tags"
|
|
||||||
:key="tag.id"
|
|
||||||
size="xs"
|
|
||||||
:color="isTagSelected(tag.id) ? 'primary' : 'gray'"
|
|
||||||
:variant="isTagSelected(tag.id) ? 'solid' : 'outline'"
|
|
||||||
@click="toggleTag(tag)"
|
|
||||||
>
|
|
||||||
{{ tag.icon }} {{ tag.name }}
|
|
||||||
</UButton>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</UFormGroup>
|
</UFormGroup>
|
||||||
|
|
||||||
<!-- Submit -->
|
<!-- Submit -->
|
||||||
@@ -129,7 +99,16 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
const { addInventoryItem, addItemTags } = useInventory()
|
const { addInventoryItem, addItemTags } = useInventory()
|
||||||
const { getUnits } = useUnits()
|
const { getUnits } = useUnits()
|
||||||
const { getTags } = useTags()
|
|
||||||
|
const props = defineProps<{
|
||||||
|
initialData?: {
|
||||||
|
barcode?: string
|
||||||
|
name?: string
|
||||||
|
brand?: string
|
||||||
|
image_url?: string
|
||||||
|
quantity?: string
|
||||||
|
}
|
||||||
|
}>()
|
||||||
|
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
close: []
|
close: []
|
||||||
@@ -148,24 +127,52 @@ const form = reactive({
|
|||||||
const submitting = ref(false)
|
const submitting = ref(false)
|
||||||
const selectedTags = ref<any[]>([])
|
const selectedTags = ref<any[]>([])
|
||||||
|
|
||||||
// Load units and tags
|
// Load units
|
||||||
const units = ref<any[]>([])
|
const units = ref<any[]>([])
|
||||||
const tags = ref<any[]>([])
|
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
const [unitsResult, tagsResult] = await Promise.all([
|
const unitsResult = await getUnits()
|
||||||
getUnits(),
|
|
||||||
getTags()
|
|
||||||
])
|
|
||||||
|
|
||||||
units.value = unitsResult.data || []
|
units.value = unitsResult.data || []
|
||||||
tags.value = tagsResult.data || []
|
|
||||||
|
|
||||||
// Set default unit (Piece)
|
// Set default unit (Piece)
|
||||||
const defaultUnit = units.value.find(u => u.abbreviation === 'pc')
|
const defaultUnit = units.value.find(u => u.abbreviation === 'pc')
|
||||||
if (defaultUnit) {
|
if (defaultUnit) {
|
||||||
form.unit_id = defaultUnit.id
|
form.unit_id = defaultUnit.id
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Pre-fill from initial data (scan-to-add flow)
|
||||||
|
if (props.initialData) {
|
||||||
|
if (props.initialData.name) {
|
||||||
|
form.name = props.initialData.name
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add brand to notes if available
|
||||||
|
if (props.initialData.brand) {
|
||||||
|
form.notes = `Brand: ${props.initialData.brand}`
|
||||||
|
|
||||||
|
if (props.initialData.barcode) {
|
||||||
|
form.notes += `\nBarcode: ${props.initialData.barcode}`
|
||||||
|
}
|
||||||
|
} else if (props.initialData.barcode) {
|
||||||
|
form.notes = `Barcode: ${props.initialData.barcode}`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse quantity if available (e.g., "750g")
|
||||||
|
if (props.initialData.quantity) {
|
||||||
|
const quantityMatch = props.initialData.quantity.match(/^([\d.]+)\s*([a-zA-Z]+)$/)
|
||||||
|
if (quantityMatch) {
|
||||||
|
form.quantity = parseFloat(quantityMatch[1])
|
||||||
|
// Try to match unit
|
||||||
|
const unitAbbr = quantityMatch[2].toLowerCase()
|
||||||
|
const matchedUnit = units.value.find(u =>
|
||||||
|
u.abbreviation.toLowerCase() === unitAbbr
|
||||||
|
)
|
||||||
|
if (matchedUnit) {
|
||||||
|
form.unit_id = matchedUnit.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
// Unit options for select
|
// Unit options for select
|
||||||
@@ -187,39 +194,6 @@ const unitOptions = computed(() => {
|
|||||||
])
|
])
|
||||||
})
|
})
|
||||||
|
|
||||||
// Tag categories for display
|
|
||||||
const tagCategories = computed(() => {
|
|
||||||
const categories: Record<string, any[]> = {}
|
|
||||||
|
|
||||||
for (const tag of tags.value) {
|
|
||||||
const cat = tag.category
|
|
||||||
if (!categories[cat]) categories[cat] = []
|
|
||||||
categories[cat].push(tag)
|
|
||||||
}
|
|
||||||
|
|
||||||
return Object.entries(categories).map(([name, tags]) => ({
|
|
||||||
name,
|
|
||||||
tags
|
|
||||||
}))
|
|
||||||
})
|
|
||||||
|
|
||||||
// Tag selection helpers
|
|
||||||
const isTagSelected = (tagId: string) => {
|
|
||||||
return selectedTags.value.some(t => t.id === tagId)
|
|
||||||
}
|
|
||||||
|
|
||||||
const toggleTag = (tag: any) => {
|
|
||||||
if (isTagSelected(tag.id)) {
|
|
||||||
removeTag(tag.id)
|
|
||||||
} else {
|
|
||||||
selectedTags.value.push(tag)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const removeTag = (tagId: string) => {
|
|
||||||
selectedTags.value = selectedTags.value.filter(t => t.id !== tagId)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validation
|
// Validation
|
||||||
const isValid = computed(() => {
|
const isValid = computed(() => {
|
||||||
return form.name.trim().length > 0 && form.quantity > 0 && form.unit_id
|
return form.name.trim().length > 0 && form.quantity > 0 && form.unit_id
|
||||||
|
|||||||
@@ -50,15 +50,12 @@
|
|||||||
|
|
||||||
<!-- Tags -->
|
<!-- Tags -->
|
||||||
<div v-if="item.tags && item.tags.length > 0" class="flex flex-wrap gap-1">
|
<div v-if="item.tags && item.tags.length > 0" class="flex flex-wrap gap-1">
|
||||||
<UBadge
|
<TagsTagBadge
|
||||||
v-for="tagItem in item.tags.slice(0, 3)"
|
v-for="tagItem in item.tags.slice(0, 3)"
|
||||||
:key="tagItem.tag.id"
|
:key="tagItem.tag.id"
|
||||||
:style="{ backgroundColor: tagItem.tag.color }"
|
:tag="tagItem.tag"
|
||||||
size="xs"
|
size="sm"
|
||||||
class="text-white"
|
/>
|
||||||
>
|
|
||||||
{{ tagItem.tag.icon }} {{ tagItem.tag.name }}
|
|
||||||
</UBadge>
|
|
||||||
<UBadge v-if="item.tags.length > 3" size="xs" color="gray">
|
<UBadge v-if="item.tags.length > 3" size="xs" color="gray">
|
||||||
+{{ item.tags.length - 3 }}
|
+{{ item.tags.length - 3 }}
|
||||||
</UBadge>
|
</UBadge>
|
||||||
|
|||||||
71
app/components/tags/TagBadge.vue
Normal file
71
app/components/tags/TagBadge.vue
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
<template>
|
||||||
|
<UBadge
|
||||||
|
:style="badgeStyle"
|
||||||
|
:class="badgeClasses"
|
||||||
|
v-bind="$attrs"
|
||||||
|
>
|
||||||
|
<span v-if="tag.icon" class="mr-1">{{ tag.icon }}</span>
|
||||||
|
<span>{{ tag.name }}</span>
|
||||||
|
<UButton
|
||||||
|
v-if="removable"
|
||||||
|
icon="i-heroicons-x-mark"
|
||||||
|
size="2xs"
|
||||||
|
color="white"
|
||||||
|
variant="link"
|
||||||
|
class="ml-1 -mr-1"
|
||||||
|
@click.stop="$emit('remove', tag.id)"
|
||||||
|
/>
|
||||||
|
</UBadge>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
interface Tag {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
color: string
|
||||||
|
icon?: string
|
||||||
|
category: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const props = withDefaults(defineProps<{
|
||||||
|
tag: Tag
|
||||||
|
removable?: boolean
|
||||||
|
size?: 'sm' | 'md' | 'lg'
|
||||||
|
}>(), {
|
||||||
|
removable: false,
|
||||||
|
size: 'md'
|
||||||
|
})
|
||||||
|
|
||||||
|
defineEmits<{
|
||||||
|
remove: [tagId: string]
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const badgeStyle = computed(() => ({
|
||||||
|
backgroundColor: props.tag.color,
|
||||||
|
color: getContrastColor(props.tag.color)
|
||||||
|
}))
|
||||||
|
|
||||||
|
const badgeClasses = computed(() => ({
|
||||||
|
'cursor-pointer': props.removable,
|
||||||
|
'text-xs px-2 py-1': props.size === 'sm',
|
||||||
|
'text-sm px-2.5 py-1': props.size === 'md',
|
||||||
|
'text-base px-3 py-1.5': props.size === 'lg'
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Calculate contrast color for text (black or white)
|
||||||
|
function getContrastColor(hexColor: string): string {
|
||||||
|
// Remove # if present
|
||||||
|
const hex = hexColor.replace('#', '')
|
||||||
|
|
||||||
|
// Convert to RGB
|
||||||
|
const r = parseInt(hex.slice(0, 2), 16)
|
||||||
|
const g = parseInt(hex.slice(2, 4), 16)
|
||||||
|
const b = parseInt(hex.slice(4, 6), 16)
|
||||||
|
|
||||||
|
// Calculate luminance
|
||||||
|
const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255
|
||||||
|
|
||||||
|
// Return white for dark colors, black for light colors
|
||||||
|
return luminance > 0.5 ? '#000000' : '#FFFFFF'
|
||||||
|
}
|
||||||
|
</script>
|
||||||
125
app/components/tags/TagPicker.vue
Normal file
125
app/components/tags/TagPicker.vue
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
<template>
|
||||||
|
<div class="space-y-4">
|
||||||
|
<!-- Selected Tags -->
|
||||||
|
<div v-if="selectedTags.length > 0" class="flex flex-wrap gap-2">
|
||||||
|
<TagsTagBadge
|
||||||
|
v-for="tag in selectedTags"
|
||||||
|
:key="tag.id"
|
||||||
|
:tag="tag"
|
||||||
|
:removable="true"
|
||||||
|
@remove="removeTag"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Empty State -->
|
||||||
|
<div v-else class="text-sm text-gray-500 italic">
|
||||||
|
No tags selected
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Tag Selection by Category -->
|
||||||
|
<div v-for="category in tagsByCategory" :key="category.name" class="space-y-2">
|
||||||
|
<h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wide">
|
||||||
|
{{ category.name }}
|
||||||
|
</h4>
|
||||||
|
<div class="flex flex-wrap gap-2">
|
||||||
|
<UButton
|
||||||
|
v-for="tag in category.tags"
|
||||||
|
:key="tag.id"
|
||||||
|
size="sm"
|
||||||
|
:color="isSelected(tag.id) ? 'primary' : 'gray'"
|
||||||
|
:variant="isSelected(tag.id) ? 'solid' : 'outline'"
|
||||||
|
@click="toggleTag(tag)"
|
||||||
|
>
|
||||||
|
<span v-if="tag.icon" class="mr-1">{{ tag.icon }}</span>
|
||||||
|
{{ tag.name }}
|
||||||
|
</UButton>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Loading State -->
|
||||||
|
<div v-if="loading" class="text-center py-4">
|
||||||
|
<div class="inline-block animate-spin rounded-full h-6 w-6 border-b-2 border-primary-500"></div>
|
||||||
|
<p class="text-sm text-gray-500 mt-2">Loading tags...</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Empty State (no tags available) -->
|
||||||
|
<div v-if="!loading && availableTags.length === 0" class="text-center py-4">
|
||||||
|
<p class="text-gray-500">No tags available</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
interface Tag {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
color: string
|
||||||
|
icon?: string
|
||||||
|
category: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
modelValue: Tag[]
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
'update:modelValue': [tags: Tag[]]
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const { getTags } = useTags()
|
||||||
|
|
||||||
|
const availableTags = ref<Tag[]>([])
|
||||||
|
const loading = ref(true)
|
||||||
|
|
||||||
|
// Load tags on mount
|
||||||
|
onMounted(async () => {
|
||||||
|
const { data, error } = await getTags()
|
||||||
|
if (data) {
|
||||||
|
availableTags.value = data
|
||||||
|
}
|
||||||
|
loading.value = false
|
||||||
|
})
|
||||||
|
|
||||||
|
// Computed
|
||||||
|
const selectedTags = computed(() => props.modelValue)
|
||||||
|
|
||||||
|
const tagsByCategory = computed(() => {
|
||||||
|
const grouped: Record<string, Tag[]> = {}
|
||||||
|
|
||||||
|
for (const tag of availableTags.value) {
|
||||||
|
if (!grouped[tag.category]) {
|
||||||
|
grouped[tag.category] = []
|
||||||
|
}
|
||||||
|
grouped[tag.category].push(tag)
|
||||||
|
}
|
||||||
|
|
||||||
|
return Object.entries(grouped).map(([name, tags]) => ({
|
||||||
|
name: name.charAt(0).toUpperCase() + name.slice(1),
|
||||||
|
tags: tags.sort((a, b) => a.name.localeCompare(b.name))
|
||||||
|
})).sort((a, b) => {
|
||||||
|
// Position category first, then others alphabetically
|
||||||
|
if (a.name === 'Position') return -1
|
||||||
|
if (b.name === 'Position') return 1
|
||||||
|
return a.name.localeCompare(b.name)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// Methods
|
||||||
|
const isSelected = (tagId: string) => {
|
||||||
|
return selectedTags.value.some(t => t.id === tagId)
|
||||||
|
}
|
||||||
|
|
||||||
|
const toggleTag = (tag: Tag) => {
|
||||||
|
const isCurrentlySelected = isSelected(tag.id)
|
||||||
|
|
||||||
|
if (isCurrentlySelected) {
|
||||||
|
removeTag(tag.id)
|
||||||
|
} else {
|
||||||
|
emit('update:modelValue', [...selectedTags.value, tag])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const removeTag = (tagId: string) => {
|
||||||
|
emit('update:modelValue', selectedTags.value.filter(t => t.id !== tagId))
|
||||||
|
}
|
||||||
|
</script>
|
||||||
61
app/composables/useProductLookup.ts
Normal file
61
app/composables/useProductLookup.ts
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
// Composable for product lookup via Edge Function
|
||||||
|
|
||||||
|
export interface ProductData {
|
||||||
|
barcode: string
|
||||||
|
name: string
|
||||||
|
brand?: string
|
||||||
|
quantity?: string
|
||||||
|
image_url?: string
|
||||||
|
category?: string
|
||||||
|
cached?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useProductLookup = () => {
|
||||||
|
const supabase = useSupabaseClient()
|
||||||
|
const isLoading = ref(false)
|
||||||
|
const error = ref<string | null>(null)
|
||||||
|
|
||||||
|
const lookupProduct = async (barcode: string): Promise<ProductData | null> => {
|
||||||
|
isLoading.value = true
|
||||||
|
error.value = null
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { data, error: functionError } = await supabase.functions.invoke('product-lookup', {
|
||||||
|
body: { barcode }
|
||||||
|
})
|
||||||
|
|
||||||
|
if (functionError) {
|
||||||
|
console.error('Product lookup error:', functionError)
|
||||||
|
error.value = functionError.message || 'Failed to lookup product'
|
||||||
|
|
||||||
|
// Return basic product data even on error
|
||||||
|
return {
|
||||||
|
barcode,
|
||||||
|
name: `Product ${barcode}`,
|
||||||
|
cached: false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return data as ProductData
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Unexpected error during product lookup:', err)
|
||||||
|
error.value = err instanceof Error ? err.message : 'Unknown error'
|
||||||
|
|
||||||
|
// Return basic product data even on error
|
||||||
|
return {
|
||||||
|
barcode,
|
||||||
|
name: `Product ${barcode}`,
|
||||||
|
cached: false
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
isLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
lookupProduct,
|
||||||
|
isLoading: readonly(isLoading),
|
||||||
|
error: readonly(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -28,7 +28,8 @@
|
|||||||
<div v-if="showAddForm" class="fixed inset-0 z-50 flex items-start justify-center pt-20 px-4 bg-black/50">
|
<div v-if="showAddForm" class="fixed inset-0 z-50 flex items-start justify-center pt-20 px-4 bg-black/50">
|
||||||
<div class="w-full max-w-lg">
|
<div class="w-full max-w-lg">
|
||||||
<AddItemForm
|
<AddItemForm
|
||||||
@close="showAddForm = false"
|
:initial-data="prefilledData"
|
||||||
|
@close="handleCloseAddForm"
|
||||||
@added="handleItemAdded"
|
@added="handleItemAdded"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -56,13 +57,42 @@ definePageMeta({
|
|||||||
layout: 'default'
|
layout: 'default'
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const route = useRoute()
|
||||||
|
const router = useRouter()
|
||||||
|
|
||||||
const showAddForm = ref(false)
|
const showAddForm = ref(false)
|
||||||
const editingItem = ref<any>(null)
|
const editingItem = ref<any>(null)
|
||||||
const refreshKey = ref(0)
|
const refreshKey = ref(0)
|
||||||
const inventoryListRef = ref()
|
const inventoryListRef = ref()
|
||||||
|
const prefilledData = ref<any>(null)
|
||||||
|
|
||||||
|
// Handle scan-to-add flow (Issue #25)
|
||||||
|
onMounted(() => {
|
||||||
|
if (route.query.action === 'add') {
|
||||||
|
// Pre-fill data from query params (from scan)
|
||||||
|
prefilledData.value = {
|
||||||
|
barcode: route.query.barcode as string || undefined,
|
||||||
|
name: route.query.name as string || undefined,
|
||||||
|
brand: route.query.brand as string || undefined,
|
||||||
|
image_url: route.query.image_url as string || undefined,
|
||||||
|
quantity: route.query.quantity as string || undefined,
|
||||||
|
}
|
||||||
|
|
||||||
|
showAddForm.value = true
|
||||||
|
|
||||||
|
// Clean up URL
|
||||||
|
router.replace({ query: {} })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const handleCloseAddForm = () => {
|
||||||
|
showAddForm.value = false
|
||||||
|
prefilledData.value = null
|
||||||
|
}
|
||||||
|
|
||||||
const handleItemAdded = (item: any) => {
|
const handleItemAdded = (item: any) => {
|
||||||
showAddForm.value = false
|
showAddForm.value = false
|
||||||
|
prefilledData.value = null
|
||||||
// Reload the inventory list
|
// Reload the inventory list
|
||||||
inventoryListRef.value?.reload()
|
inventoryListRef.value?.reload()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -72,49 +72,33 @@ definePageMeta({
|
|||||||
|
|
||||||
const scannedBarcode = ref<string | null>(null)
|
const scannedBarcode = ref<string | null>(null)
|
||||||
const productData = ref<any>(null)
|
const productData = ref<any>(null)
|
||||||
const isLookingUp = ref(false)
|
|
||||||
const lookupError = ref<string | null>(null)
|
|
||||||
const showManualEntry = ref(false)
|
const showManualEntry = ref(false)
|
||||||
|
|
||||||
|
// Use product lookup composable
|
||||||
|
const { lookupProduct, isLoading: isLookingUp, error: lookupError } = useProductLookup()
|
||||||
|
|
||||||
const handleBarcodeDetected = async (barcode: string) => {
|
const handleBarcodeDetected = async (barcode: string) => {
|
||||||
scannedBarcode.value = barcode
|
scannedBarcode.value = barcode
|
||||||
lookupError.value = null
|
|
||||||
isLookingUp.value = true
|
|
||||||
|
|
||||||
try {
|
// Fetch product data from Edge Function
|
||||||
// TODO: Implement product lookup via Edge Function (Issue #24)
|
const data = await lookupProduct(barcode)
|
||||||
// For now, create a basic product object
|
|
||||||
await new Promise(resolve => setTimeout(resolve, 1000)) // Simulate API call
|
|
||||||
|
|
||||||
productData.value = {
|
if (data) {
|
||||||
name: `Product ${barcode}`,
|
productData.value = data
|
||||||
brand: 'Unknown Brand',
|
|
||||||
barcode: barcode,
|
|
||||||
image_url: null
|
|
||||||
}
|
|
||||||
|
|
||||||
lookupError.value = 'Product lookup not yet implemented. Using default data.'
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Product lookup error:', error)
|
|
||||||
lookupError.value = 'Failed to look up product. You can still add it manually.'
|
|
||||||
productData.value = {
|
|
||||||
name: `Product ${barcode}`,
|
|
||||||
barcode: barcode
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
isLookingUp.value = false
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const addToInventory = () => {
|
const addToInventory = () => {
|
||||||
// TODO: Implement scan-to-add flow (Issue #25)
|
// Navigate to home page with add form open and pre-filled
|
||||||
// Navigate to add form with pre-filled data
|
|
||||||
navigateTo({
|
navigateTo({
|
||||||
path: '/',
|
path: '/',
|
||||||
query: {
|
query: {
|
||||||
|
action: 'add',
|
||||||
barcode: scannedBarcode.value,
|
barcode: scannedBarcode.value,
|
||||||
name: productData.value?.name,
|
name: productData.value?.name || undefined,
|
||||||
brand: productData.value?.brand
|
brand: productData.value?.brand || undefined,
|
||||||
|
image_url: productData.value?.image_url || undefined,
|
||||||
|
quantity: productData.value?.quantity || undefined
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
83
supabase/functions/product-lookup/README.md
Normal file
83
supabase/functions/product-lookup/README.md
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
# Product Lookup Edge Function
|
||||||
|
|
||||||
|
Fetches product data from Open Food Facts API by barcode and caches results in the database.
|
||||||
|
|
||||||
|
## Endpoint
|
||||||
|
|
||||||
|
`POST /functions/v1/product-lookup`
|
||||||
|
|
||||||
|
## Request
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"barcode": "8000500310427"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Response
|
||||||
|
|
||||||
|
### Success (200)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"barcode": "8000500310427",
|
||||||
|
"name": "Nutella",
|
||||||
|
"brand": "Ferrero",
|
||||||
|
"quantity": "750g",
|
||||||
|
"image_url": "https://...",
|
||||||
|
"category": "spreads",
|
||||||
|
"cached": false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Not Found (404)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"barcode": "1234567890123",
|
||||||
|
"name": "Unknown Product (1234567890123)",
|
||||||
|
"cached": false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Error (500)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"error": "Error message",
|
||||||
|
"barcode": null,
|
||||||
|
"name": null
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- ✅ Queries Open Food Facts API
|
||||||
|
- ✅ Caches results in `products` table
|
||||||
|
- ✅ Returns cached data for subsequent requests
|
||||||
|
- ✅ Handles product not found gracefully
|
||||||
|
- ✅ CORS enabled for frontend access
|
||||||
|
|
||||||
|
## Environment Variables
|
||||||
|
|
||||||
|
- `SUPABASE_URL`: Auto-injected by Supabase
|
||||||
|
- `SUPABASE_SERVICE_ROLE_KEY`: Auto-injected by Supabase
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Local (with Supabase CLI)
|
||||||
|
supabase functions serve product-lookup
|
||||||
|
|
||||||
|
# Test request
|
||||||
|
curl -X POST http://localhost:54321/functions/v1/product-lookup \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-H "Authorization: Bearer YOUR_ANON_KEY" \
|
||||||
|
-d '{"barcode":"8000500310427"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
```bash
|
||||||
|
supabase functions deploy product-lookup
|
||||||
|
```
|
||||||
140
supabase/functions/product-lookup/index.ts
Normal file
140
supabase/functions/product-lookup/index.ts
Normal file
@@ -0,0 +1,140 @@
|
|||||||
|
// Product Lookup Edge Function
|
||||||
|
// Fetches product data from Open Food Facts API by barcode
|
||||||
|
|
||||||
|
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
|
||||||
|
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
|
||||||
|
|
||||||
|
const corsHeaders = {
|
||||||
|
'Access-Control-Allow-Origin': '*',
|
||||||
|
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ProductData {
|
||||||
|
barcode: string
|
||||||
|
name: string
|
||||||
|
brand?: string
|
||||||
|
quantity?: string
|
||||||
|
image_url?: string
|
||||||
|
category?: string
|
||||||
|
cached?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
serve(async (req) => {
|
||||||
|
// Handle CORS preflight
|
||||||
|
if (req.method === 'OPTIONS') {
|
||||||
|
return new Response('ok', { headers: corsHeaders })
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { barcode } = await req.json()
|
||||||
|
|
||||||
|
if (!barcode) {
|
||||||
|
throw new Error('Barcode is required')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize Supabase client
|
||||||
|
const supabaseUrl = Deno.env.get('SUPABASE_URL')!
|
||||||
|
const supabaseKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
|
||||||
|
const supabase = createClient(supabaseUrl, supabaseKey)
|
||||||
|
|
||||||
|
// Check cache first (products table can store known products)
|
||||||
|
const { data: cachedProduct } = await supabase
|
||||||
|
.from('products')
|
||||||
|
.select('*')
|
||||||
|
.eq('barcode', barcode)
|
||||||
|
.single()
|
||||||
|
|
||||||
|
if (cachedProduct) {
|
||||||
|
console.log(`Cache HIT for barcode: ${barcode}`)
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
barcode: cachedProduct.barcode,
|
||||||
|
name: cachedProduct.name,
|
||||||
|
brand: cachedProduct.brand,
|
||||||
|
quantity: cachedProduct.quantity,
|
||||||
|
image_url: cachedProduct.image_url,
|
||||||
|
category: cachedProduct.category,
|
||||||
|
cached: true,
|
||||||
|
} as ProductData),
|
||||||
|
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`Cache MISS for barcode: ${barcode}, fetching from Open Food Facts...`)
|
||||||
|
|
||||||
|
// Fetch from Open Food Facts
|
||||||
|
const offResponse = await fetch(
|
||||||
|
`https://world.openfoodfacts.org/api/v2/product/${barcode}.json`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
'User-Agent': 'Pantry/1.0 (https://github.com/pantry-app/pantry)',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!offResponse.ok) {
|
||||||
|
throw new Error(`Open Food Facts API error: ${offResponse.status}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const offData = await offResponse.json()
|
||||||
|
|
||||||
|
if (offData.status !== 1 || !offData.product) {
|
||||||
|
// Product not found in Open Food Facts
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
barcode,
|
||||||
|
name: `Unknown Product (${barcode})`,
|
||||||
|
cached: false,
|
||||||
|
} as ProductData),
|
||||||
|
{
|
||||||
|
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||||
|
status: 404
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const product = offData.product
|
||||||
|
|
||||||
|
// Extract relevant data
|
||||||
|
const productData: ProductData = {
|
||||||
|
barcode,
|
||||||
|
name: product.product_name || product.generic_name || `Product ${barcode}`,
|
||||||
|
brand: product.brands || undefined,
|
||||||
|
quantity: product.quantity || undefined,
|
||||||
|
image_url: product.image_url || product.image_front_url || undefined,
|
||||||
|
category: product.categories || undefined,
|
||||||
|
cached: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cache the product in our database (upsert)
|
||||||
|
await supabase.from('products').upsert({
|
||||||
|
barcode: productData.barcode,
|
||||||
|
name: productData.name,
|
||||||
|
brand: productData.brand,
|
||||||
|
quantity: productData.quantity,
|
||||||
|
image_url: productData.image_url,
|
||||||
|
category: productData.category,
|
||||||
|
}, { onConflict: 'barcode' })
|
||||||
|
|
||||||
|
console.log(`Successfully fetched and cached product: ${productData.name}`)
|
||||||
|
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify(productData),
|
||||||
|
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
|
||||||
|
)
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in product-lookup:', error)
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
error: error instanceof Error ? error.message : 'Unknown error',
|
||||||
|
barcode: null,
|
||||||
|
name: null,
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||||
|
status: 500
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user