diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 142bc1404..3b88ecb1b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -165,11 +165,11 @@ jobs: timeout-minutes: 75 steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v4 - - uses: actions/setup-node@v6 + - uses: actions/setup-node@v4 with: - node-version: 20 + node-version-file: '.nvmrc' cache: npm - name: Install dependencies @@ -189,7 +189,7 @@ jobs: - name: Upload coverage report if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@v4 with: name: coverage-report-${{ github.run_id }} path: coverage/ diff --git a/scripts/fix_migrations_idempotent.py b/scripts/fix_migrations_idempotent.py new file mode 100644 index 000000000..de4b9d295 --- /dev/null +++ b/scripts/fix_migrations_idempotent.py @@ -0,0 +1,568 @@ +#!/usr/bin/env python3 +""" +Fix SQL migration files to be idempotent (safe to run on empty DB). + +Transformations applied: +1. CREATE TABLE -> CREATE TABLE IF NOT EXISTS +2. CREATE INDEX / UNIQUE INDEX -> CREATE INDEX/UNIQUE INDEX IF NOT EXISTS +3. CREATE SEQUENCE -> CREATE SEQUENCE IF NOT EXISTS +4. CREATE VIEW -> CREATE OR REPLACE VIEW +5. CREATE MATERIALIZED VIEW -> DROP IF EXISTS before +6. CREATE FUNCTION/PROCEDURE -> CREATE OR REPLACE FUNCTION/PROCEDURE +7. CREATE TRIGGER -> DROP TRIGGER IF EXISTS before +8. CREATE POLICY -> DROP POLICY IF EXISTS before +9. CREATE TYPE AS ENUM -> wrap in DO block +10. DROP without IF EXISTS -> add IF EXISTS +11. ALTER TABLE ADD COLUMN -> ADD COLUMN IF NOT EXISTS +12. CREATE EXTENSION -> CREATE EXTENSION IF NOT EXISTS +""" + +import re +import os +import sys +from pathlib import Path + +MIGRATIONS_DIR = Path("/home/user/Promo_Gifts/supabase/migrations") + +# The list of files NOT in production that need fixing (from the task description) +NOT_IN_PRODUCTION_TIMESTAMPS = set(""" +20260107013155 20260107141013 20260107141630 20260108014732 20260108173818 +20260109125132 20260109154430 20260109154850 20260109202835 20260109210025 +20260110114755 20260110114831 20260110114839 20260110122053 20260201155941 +20260208141021 20260211135257 20260213150148 20260213150342 20260213150532 +20260213151101 20260213151403 20260214005421 20260214152115 20260215185444 +20260216110718 20260216125012 20260219024635 20260219121904 20260219133353 +20260220001443 20260220174735 20260222134246 20260222203852 20260226190748 +20260226200633 20260301135215 20260301142954 20260301143055 20260301150840 +20260304004120 20260304014416 20260304014707 20260305220938 20260306011448 +20260306011719 20260306011759 20260306013723 20260312110229 20260312111512 +20260312115440 20260312124638 20260314133410 20260314134333 20260314172451 +20260314175106 20260314190936 20260314190948 20260314192448 20260317020422 +20260317140334 20260317155554 20260317194959 20260317195011 20260317200129 +20260317205124 20260317205135 20260317212837 20260317213620 20260317214344 +20260317214358 20260317221652 20260317221910 20260317222414 20260317222739 +20260320135344 20260320141635 20260320171208 20260321200700 20260322010007 +20260322133758 20260322143211 20260322170128 20260322174557 20260322215809 +20260322222206 20260322224817 20260323145546 20260323162846 20260323164400 +20260323225021 20260324114359 20260324201423 20260325124134 20260325152410 +20260326160831 20260326191912 20260326193116 20260326193133 20260326233438 +20260330104621 20260402110456 20260402110748 20260402112639 20260404160306 +20260404163500 20260404163525 20260404163550 20260404163714 20260404163738 +20260404164044 20260404164132 20260404164216 20260404164259 20260404171222 +20260405151750 20260405222509 20260406124228 20260406202212 20260406210155 +20260406210254 20260407014300 20260410165642 20260411210929 20260412182408 +20260412183140 20260412184314 20260412231916 20260412231951 20260412232015 +20260412232711 20260413005750 20260414193435 20260414232135 20260414232158 +20260414234635 20260415010140 20260416153503 20260416153731 20260416154332 +20260416180602 20260416181632 20260416182003 20260416182133 20260416183342 +20260416183415 20260416183821 20260416184056 20260416190742 20260416194706 +20260416195918 20260416200125 20260416200310 20260416220648 20260416231122 +20260416231145 20260416232134 20260416235610 20260417000818 20260417001408 +20260417002650 20260417005020 20260417011314 20260417015121 20260417112433 +20260417115234 20260417170750 20260417170948 20260417171441 20260417174309 +20260418131950 20260418175315 20260418183756 20260418191039 20260419024908 +20260419024928 20260419024944 20260419025022 20260419120255 20260419121414 +20260419125044 20260419130037 20260419132122 20260419184445 20260419185334 +20260420123931 20260420130407 20260420142509 20260420142542 20260420164558 +20260420172157 20260420185009 20260423145604 20260423150337 20260423155736 +20260423161848 20260423163018 20260423165603 20260423183908 20260423184705 +20260423184855 20260423185624 20260423190222 20260423190831 20260423193705 +20260424105620 20260424110636 20260424152415 20260424154125 20260424155746 +20260424160905 20260424213841 20260425104654 20260425104801 20260425164021 +20260425172528 20260425175855 20260425192845 20260425194004 20260425194941 +20260425200038 20260425201131 20260425202739 20260425202806 20260425203103 +20260425203612 20260425205426 20260425210505 20260425212616 20260425212807 +20260425213721 20260425213902 20260425214848 20260426010557 20260426013235 +20260426101255 20260426101707 20260426102150 20260426102335 20260426103109 +20260426105906 20260426110946 20260426113207 20260426122751 20260426123111 +20260426124539 20260426124745 20260426125603 20260426130335 20260426130639 +20260426130701 20260426131442 20260426134439 20260426134707 20260426135145 +20260426135521 20260426142016 20260426142609 20260426145642 20260426200011 +20260426200348 20260426224900 20260427114657 20260427115542 20260427121006 +20260427122230 20260427143410 20260427211500 20260427212820 20260427213016 +20260427213631 20260427213832 20260427213920 20260428140401 20260429155414 +20260429163414 20260429163441 20260503132831 20260503133538 20260503133611 +20260503134608 20260503134916 20260503225233 20260504141259 20260507145245 +20260507161547 20260512000001 20260512000002 20260512000003 20260512000004 +20260512000005 20260512000006 20260512000007 20260512000008 20260512000009 +20260512000010 20260512000011 20260512000012 20260512000013 20260512000014 +20260512153020 20260512163615 20260512163629 20260512164738 20260512201500 +20260512201600 20260512210000 20260512230000 20260512230500 20260513000001 +20260513000002 20260513000003 20260513000004 20260513000005 +""".split()) + + +def should_process(filename: str) -> bool: + """Determine if a file should be processed (not in production).""" + stem = Path(filename).stem + + # Always process pre-2026 files (001-005, 2024*, 2025*) + for prefix in ("001_", "002_", "003_", "004_", "005_"): + if stem.startswith(prefix): + return True + + if stem.startswith("20241") or stem.startswith("2025"): + return True + + # For 2026 files, check if timestamp is in the not-in-production list + if stem.startswith("2026"): + ts = stem[:14] + return ts in NOT_IN_PRODUCTION_TIMESTAMPS + + return False + + +def extract_quoted_name(text: str, pos: int) -> tuple[str, int]: + """Extract a (possibly quoted) name starting at pos in text. + Returns (name_with_quotes, end_pos). + """ + if pos >= len(text): + return ('', pos) + + if text[pos] == '"': + # Double-quoted name + end = pos + 1 + while end < len(text) and text[end] != '"': + end += 1 + return (text[pos:end+1], end + 1) + elif text[pos] == "'": + # Single-quoted name + end = pos + 1 + while end < len(text) and text[pos] != "'": + end += 1 + return (text[pos:end+1], end + 1) + else: + # Unquoted name - read until whitespace or special char + end = pos + while end < len(text) and text[end] not in (' ', '\t', '\n', '(', ',', ';'): + end += 1 + return (text[pos:end], end) + + +def fix_simple_regex(content: str) -> str: + """Apply simple regex-based fixes.""" + + # 1. CREATE EXTENSION IF NOT EXISTS + content = re.sub( + r'\bCREATE\s+EXTENSION\s+(?!IF\s+NOT\s+EXISTS\b)', + 'CREATE EXTENSION IF NOT EXISTS ', + content, + flags=re.IGNORECASE + ) + + # 2. CREATE TABLE IF NOT EXISTS + content = re.sub( + r'\bCREATE\s+TABLE\s+(?!IF\s+NOT\s+EXISTS\b)', + 'CREATE TABLE IF NOT EXISTS ', + content, + flags=re.IGNORECASE + ) + + # 3. CREATE SEQUENCE IF NOT EXISTS + content = re.sub( + r'\bCREATE\s+SEQUENCE\s+(?!IF\s+NOT\s+EXISTS\b)', + 'CREATE SEQUENCE IF NOT EXISTS ', + content, + flags=re.IGNORECASE + ) + + # 4. CREATE INDEX IF NOT EXISTS (non-CONCURRENTLY) + # Must handle UNIQUE separately + content = re.sub( + r'\bCREATE\s+(UNIQUE\s+)?INDEX\s+(?!CONCURRENTLY\b)(?!IF\s+NOT\s+EXISTS\b)', + lambda m: f'CREATE {(m.group(1) or "").upper()}INDEX IF NOT EXISTS ', + content, + flags=re.IGNORECASE + ) + + # 5. CREATE INDEX CONCURRENTLY -> remove CONCURRENTLY, add IF NOT EXISTS + content = re.sub( + r'\bCREATE\s+(UNIQUE\s+)?INDEX\s+CONCURRENTLY\s+(?!IF\s+NOT\s+EXISTS\b)', + lambda m: f'CREATE {(m.group(1) or "").upper()}INDEX IF NOT EXISTS ', + content, + flags=re.IGNORECASE + ) + + # 6. CREATE OR REPLACE VIEW (not MATERIALIZED) + # This regex must not match MATERIALIZED VIEW + content = re.sub( + r'\bCREATE\s+(?!OR\s+REPLACE\b)(?!MATERIALIZED\b)VIEW\s+', + 'CREATE OR REPLACE VIEW ', + content, + flags=re.IGNORECASE + ) + + # 7. CREATE OR REPLACE FUNCTION/PROCEDURE + content = re.sub( + r'\bCREATE\s+(?!OR\s+REPLACE\b)(FUNCTION|PROCEDURE)\s+', + r'CREATE OR REPLACE \1 ', + content, + flags=re.IGNORECASE + ) + + # 8. ALTER TABLE ADD COLUMN IF NOT EXISTS + content = re.sub( + r'\bADD\s+COLUMN\s+(?!IF\s+NOT\s+EXISTS\b)', + 'ADD COLUMN IF NOT EXISTS ', + content, + flags=re.IGNORECASE + ) + + # 9. DROP TABLE IF EXISTS + content = re.sub( + r'\bDROP\s+TABLE\s+(?!IF\s+EXISTS\b)', + 'DROP TABLE IF EXISTS ', + content, + flags=re.IGNORECASE + ) + + # 10. DROP INDEX IF EXISTS + content = re.sub( + r'\bDROP\s+INDEX\s+(?!IF\s+EXISTS\b)(?!CONCURRENTLY\b)', + 'DROP INDEX IF EXISTS ', + content, + flags=re.IGNORECASE + ) + content = re.sub( + r'\bDROP\s+INDEX\s+CONCURRENTLY\s+(?!IF\s+EXISTS\b)', + 'DROP INDEX CONCURRENTLY IF EXISTS ', + content, + flags=re.IGNORECASE + ) + + # 11. DROP FUNCTION IF EXISTS + content = re.sub( + r'\bDROP\s+FUNCTION\s+(?!IF\s+EXISTS\b)', + 'DROP FUNCTION IF EXISTS ', + content, + flags=re.IGNORECASE + ) + + # 12. DROP PROCEDURE IF EXISTS + content = re.sub( + r'\bDROP\s+PROCEDURE\s+(?!IF\s+EXISTS\b)', + 'DROP PROCEDURE IF EXISTS ', + content, + flags=re.IGNORECASE + ) + + # 13. DROP TRIGGER IF EXISTS + content = re.sub( + r'\bDROP\s+TRIGGER\s+(?!IF\s+EXISTS\b)', + 'DROP TRIGGER IF EXISTS ', + content, + flags=re.IGNORECASE + ) + + # 14. DROP POLICY IF EXISTS + content = re.sub( + r'\bDROP\s+POLICY\s+(?!IF\s+EXISTS\b)', + 'DROP POLICY IF EXISTS ', + content, + flags=re.IGNORECASE + ) + + # 15. DROP SEQUENCE IF EXISTS + content = re.sub( + r'\bDROP\s+SEQUENCE\s+(?!IF\s+EXISTS\b)', + 'DROP SEQUENCE IF EXISTS ', + content, + flags=re.IGNORECASE + ) + + # 16. DROP VIEW IF EXISTS (but not MATERIALIZED VIEW) + content = re.sub( + r'\bDROP\s+(?!MATERIALIZED\b)VIEW\s+(?!IF\s+EXISTS\b)', + 'DROP VIEW IF EXISTS ', + content, + flags=re.IGNORECASE + ) + + # 17. DROP MATERIALIZED VIEW IF EXISTS + content = re.sub( + r'\bDROP\s+MATERIALIZED\s+VIEW\s+(?!IF\s+EXISTS\b)', + 'DROP MATERIALIZED VIEW IF EXISTS ', + content, + flags=re.IGNORECASE + ) + + # 18. DROP TYPE IF EXISTS + content = re.sub( + r'\bDROP\s+TYPE\s+(?!IF\s+EXISTS\b)', + 'DROP TYPE IF EXISTS ', + content, + flags=re.IGNORECASE + ) + + # 19. DROP SCHEMA IF EXISTS + content = re.sub( + r'\bDROP\s+SCHEMA\s+(?!IF\s+EXISTS\b)', + 'DROP SCHEMA IF EXISTS ', + content, + flags=re.IGNORECASE + ) + + return content + + +def fix_create_type_enum(content: str) -> str: + """Fix CREATE TYPE AS ENUM by wrapping in DO block.""" + lines = content.split('\n') + new_lines = [] + i = 0 + + while i < len(lines): + line = lines[i] + + # Check if this is a CREATE TYPE ... AS ENUM line + type_match = re.match( + r'^(\s*)CREATE\s+TYPE\s+(\S+)\s+AS\s+ENUM\s*\(', + line, + re.IGNORECASE + ) + if type_match: + indent = type_match.group(1) + + # Check if already wrapped in DO block + already_wrapped = False + for j in range(len(new_lines) - 1, -1, -1): + stripped = new_lines[j].strip() + if stripped: + upper = stripped.upper() + if upper.startswith('DO ') or upper.startswith('DO$'): + already_wrapped = True + break + + if not already_wrapped: + # Collect the full CREATE TYPE statement (until semicolon) + stmt_lines = [line] + j = i + 1 + while j < len(lines) and ';' not in lines[j - 1]: + stmt_lines.append(lines[j]) + j += 1 + # j is now pointing to the line after the semicolon (or we consumed too far) + # Actually re-check: we need to find the ; in the collected lines + stmt_lines = [line] + j = i + 1 + accumulated = line + while ';' not in accumulated and j < len(lines): + stmt_lines.append(lines[j]) + accumulated += '\n' + lines[j] + j += 1 + + stmt = '\n'.join(stmt_lines) + stmt_stripped = stmt.rstrip() + if not stmt_stripped.endswith(';'): + stmt_stripped += ';' + + wrapped = ( + f'{indent}DO $$ BEGIN\n' + f'{stmt_stripped}\n' + f'{indent}EXCEPTION WHEN duplicate_object THEN NULL;\n' + f'{indent}END $$;' + ) + new_lines.append(wrapped) + i = j # Skip lines we already consumed + continue + + new_lines.append(line) + i += 1 + + return '\n'.join(new_lines) + + +def fix_create_materialized_view(content: str) -> str: + """Fix CREATE MATERIALIZED VIEW by adding DROP IF EXISTS before.""" + lines = content.split('\n') + new_lines = [] + i = 0 + + while i < len(lines): + line = lines[i] + mv_match = re.match( + r'^(\s*)CREATE\s+MATERIALIZED\s+VIEW\s+(?!IF\s+NOT\s+EXISTS\b)(\S+)', + line, + re.IGNORECASE + ) + if mv_match: + indent = mv_match.group(1) + view_name = mv_match.group(2).rstrip('(').rstrip(';').rstrip() + + # Check if previous non-empty line already has DROP MATERIALIZED VIEW IF EXISTS + already_dropped = False + for j in range(len(new_lines) - 1, -1, -1): + stripped = new_lines[j].strip() + if stripped: + if 'DROP MATERIALIZED VIEW IF EXISTS' in stripped.upper(): + already_dropped = True + break + + if not already_dropped: + new_lines.append(f'{indent}DROP MATERIALIZED VIEW IF EXISTS {view_name};') + + new_lines.append(line) + i += 1 + + return '\n'.join(new_lines) + + +def fix_create_trigger(content: str) -> str: + """Fix CREATE TRIGGER by adding DROP TRIGGER IF EXISTS before.""" + lines = content.split('\n') + new_lines = [] + i = 0 + + while i < len(lines): + line = lines[i] + # Match CREATE [CONSTRAINT] TRIGGER name + trigger_match = re.match( + r'^(\s*)CREATE\s+(?:CONSTRAINT\s+)?TRIGGER\s+("(?:[^"]+)"|\S+)', + line, + re.IGNORECASE + ) + if trigger_match: + indent = trigger_match.group(1) + trigger_name = trigger_match.group(2) + + # Check if previous non-empty line already has DROP TRIGGER IF EXISTS + already_dropped = False + for j in range(len(new_lines) - 1, -1, -1): + stripped = new_lines[j].strip() + if stripped: + if 'DROP TRIGGER IF EXISTS' in stripped.upper(): + already_dropped = True + break + + if not already_dropped: + # Find ON table_name - scan ahead for the ON clause + combined = ' '.join(lines[i:min(i+15, len(lines))]) + # Strip comments for matching + combined_clean = re.sub(r'--[^\n]*', '', combined) + on_match = re.search( + r'\bON\s+((?:public\.|private\.|extensions\.|backup\.|storage\.|auth\.)?(?:"[^"]+"|[A-Za-z_]\w*))', + combined_clean, + re.IGNORECASE + ) + if on_match: + table_name = on_match.group(1) + new_lines.append(f'{indent}DROP TRIGGER IF EXISTS {trigger_name} ON {table_name};') + # If no ON found, skip (might be inside a function body etc.) + + new_lines.append(line) + i += 1 + + return '\n'.join(new_lines) + + +def fix_create_policy(content: str) -> str: + """Fix CREATE POLICY by adding DROP POLICY IF EXISTS before. + + Policy names can be quoted strings with spaces: CREATE POLICY "my name here" ON table + """ + lines = content.split('\n') + new_lines = [] + i = 0 + + # Pattern to match beginning of CREATE POLICY line and capture the policy name + # Policy name can be: "quoted name with spaces", 'single quoted', or unquoted_word + policy_re = re.compile( + r'^(\s*)CREATE\s+POLICY\s+("(?:[^"]+)"|\'' r'(?:[^\']+)' r"'|\S+)", + re.IGNORECASE + ) + + while i < len(lines): + line = lines[i] + policy_match = policy_re.match(line) + if policy_match: + indent = policy_match.group(1) + policy_name = policy_match.group(2) + + # Check if previous non-empty line already has DROP POLICY IF EXISTS + already_dropped = False + for j in range(len(new_lines) - 1, -1, -1): + stripped = new_lines[j].strip() + if stripped: + if 'DROP POLICY IF EXISTS' in stripped.upper(): + already_dropped = True + break + + if not already_dropped: + # Find ON table_name + # The ON clause might be on the same or next lines + combined = ' '.join(lines[i:min(i+20, len(lines))]) + combined_clean = re.sub(r'--[^\n]*', '', combined) + on_match = re.search( + r'\bON\s+((?:public\.|private\.|extensions\.|backup\.|storage\.|auth\.)?(?:"[^"]+"|[A-Za-z_]\w*))', + combined_clean, + re.IGNORECASE + ) + if on_match: + table_name = on_match.group(1) + new_lines.append(f'{indent}DROP POLICY IF EXISTS {policy_name} ON {table_name};') + + new_lines.append(line) + i += 1 + + return '\n'.join(new_lines) + + +def apply_all_fixes(content: str, filename: str) -> str: + """Apply all idempotency fixes to the content.""" + content = fix_simple_regex(content) + content = fix_create_materialized_view(content) + content = fix_create_type_enum(content) + content = fix_create_trigger(content) + content = fix_create_policy(content) + return content + + +def get_files_to_process(): + """Get list of files to process.""" + files = [] + for f in sorted(MIGRATIONS_DIR.glob("*.sql")): + if f.name == "README.md": + continue + if should_process(f.name): + files.append(f) + return files + + +def main(): + files = get_files_to_process() + print(f"Files to process: {len(files)}") + + modified = 0 + errors = [] + + for filepath in files: + try: + with open(filepath, 'r', encoding='utf-8') as fh: + original = fh.read() + + fixed = apply_all_fixes(original, filepath.name) + + if fixed != original: + with open(filepath, 'w', encoding='utf-8') as fh: + fh.write(fixed) + modified += 1 + print(f" MODIFIED: {filepath.name}") + else: + print(f" unchanged: {filepath.name}") + + except Exception as e: + errors.append((filepath.name, str(e))) + print(f" ERROR: {filepath.name}: {e}") + import traceback + traceback.print_exc() + + print(f"\nDone. Modified: {modified}/{len(files)} files") + if errors: + print(f"Errors ({len(errors)}):") + for name, err in errors: + print(f" {name}: {err}") + + return 0 if not errors else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/supabase/migrations/20241231000000_saved_filters.sql b/supabase/migrations/20241231000000_saved_filters.sql index 6fdf695cf..69137acae 100644 --- a/supabase/migrations/20241231000000_saved_filters.sql +++ b/supabase/migrations/20241231000000_saved_filters.sql @@ -38,18 +38,21 @@ CREATE INDEX IF NOT EXISTS idx_saved_filters_default ALTER TABLE public.saved_filters ENABLE ROW LEVEL SECURITY; -- Política: usuários podem ver apenas seus próprios filtros +DROP POLICY IF EXISTS "Users can view own filters" ON public.saved_filters; CREATE POLICY "Users can view own filters" ON public.saved_filters FOR SELECT USING (auth.uid() = user_id); -- Política: usuários podem inserir seus próprios filtros +DROP POLICY IF EXISTS "Users can insert own filters" ON public.saved_filters; CREATE POLICY "Users can insert own filters" ON public.saved_filters FOR INSERT WITH CHECK (auth.uid() = user_id); -- Política: usuários podem atualizar seus próprios filtros +DROP POLICY IF EXISTS "Users can update own filters" ON public.saved_filters; CREATE POLICY "Users can update own filters" ON public.saved_filters FOR UPDATE @@ -57,6 +60,7 @@ CREATE POLICY "Users can update own filters" WITH CHECK (auth.uid() = user_id); -- Política: usuários podem deletar seus próprios filtros +DROP POLICY IF EXISTS "Users can delete own filters" ON public.saved_filters; CREATE POLICY "Users can delete own filters" ON public.saved_filters FOR DELETE diff --git a/supabase/migrations/20241231000001_entity_versions.sql b/supabase/migrations/20241231000001_entity_versions.sql index f8160215f..d091aa9e8 100644 --- a/supabase/migrations/20241231000001_entity_versions.sql +++ b/supabase/migrations/20241231000001_entity_versions.sql @@ -16,5 +16,7 @@ CREATE INDEX IF NOT EXISTS idx_versions_date ON public.entity_versions(changed_a ALTER TABLE public.entity_versions ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view versions" ON public.entity_versions; CREATE POLICY "Users can view versions" ON public.entity_versions FOR SELECT USING (true); +DROP POLICY IF EXISTS "Users can insert versions" ON public.entity_versions; CREATE POLICY "Users can insert versions" ON public.entity_versions FOR INSERT WITH CHECK (auth.uid() = changed_by OR changed_by IS NULL); diff --git a/supabase/migrations/20250102000000_gifts_production.sql b/supabase/migrations/20250102000000_gifts_production.sql index 8250d1773..ca4098b4c 100644 --- a/supabase/migrations/20250102000000_gifts_production.sql +++ b/supabase/migrations/20250102000000_gifts_production.sql @@ -84,7 +84,11 @@ ALTER TABLE public.suppliers ENABLE ROW LEVEL SECURITY; ALTER TABLE public.products ENABLE ROW LEVEL SECURITY; ALTER TABLE public.quotes ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Allow all" ON public.categories; CREATE POLICY "Allow all" ON public.categories FOR ALL USING (true); +DROP POLICY IF EXISTS "Allow all" ON public.suppliers; CREATE POLICY "Allow all" ON public.suppliers FOR ALL USING (true); +DROP POLICY IF EXISTS "Allow all" ON public.products; CREATE POLICY "Allow all" ON public.products FOR ALL USING (true); +DROP POLICY IF EXISTS "Allow all" ON public.quotes; CREATE POLICY "Allow all" ON public.quotes FOR ALL USING (true); diff --git a/supabase/migrations/20250103_02_rls_organizations.sql b/supabase/migrations/20250103_02_rls_organizations.sql index e84f05b07..07f4e6a82 100644 --- a/supabase/migrations/20250103_02_rls_organizations.sql +++ b/supabase/migrations/20250103_02_rls_organizations.sql @@ -98,19 +98,23 @@ BEGIN -- PARTE 4: POLICIES - CATEGORIES -- ============================================================ + DROP POLICY IF EXISTS "org_members_view_categories" ON public.categories; CREATE POLICY "org_members_view_categories" ON public.categories FOR SELECT TO authenticated USING (public.user_is_org_member(organization_id)); + DROP POLICY IF EXISTS "org_admins_create_categories" ON public.categories; CREATE POLICY "org_admins_create_categories" ON public.categories FOR INSERT TO authenticated WITH CHECK (public.is_org_owner_or_admin(organization_id)); + DROP POLICY IF EXISTS "org_admins_update_categories" ON public.categories; CREATE POLICY "org_admins_update_categories" ON public.categories FOR UPDATE TO authenticated USING (public.is_org_owner_or_admin(organization_id)) WITH CHECK (public.is_org_owner_or_admin(organization_id)); + DROP POLICY IF EXISTS "org_admins_delete_categories" ON public.categories; CREATE POLICY "org_admins_delete_categories" ON public.categories FOR DELETE TO authenticated USING (public.is_org_owner_or_admin(organization_id)); @@ -119,10 +123,12 @@ BEGIN -- PARTE 5: POLICIES - SUPPLIERS -- ============================================================ + DROP POLICY IF EXISTS "org_members_view_suppliers" ON public.suppliers; CREATE POLICY "org_members_view_suppliers" ON public.suppliers FOR SELECT TO authenticated USING (public.user_is_org_member(organization_id)); + DROP POLICY IF EXISTS "org_admins_manage_suppliers" ON public.suppliers; CREATE POLICY "org_admins_manage_suppliers" ON public.suppliers FOR ALL TO authenticated USING (public.is_org_owner_or_admin(organization_id)) @@ -132,10 +138,12 @@ BEGIN -- PARTE 6: POLICIES - PRODUCTS -- ============================================================ + DROP POLICY IF EXISTS "org_members_view_products" ON public.products; CREATE POLICY "org_members_view_products" ON public.products FOR SELECT TO authenticated USING (public.user_is_org_member(organization_id)); + DROP POLICY IF EXISTS "org_admins_manage_products" ON public.products; CREATE POLICY "org_admins_manage_products" ON public.products FOR ALL TO authenticated USING (public.is_org_owner_or_admin(organization_id)) @@ -145,6 +153,7 @@ BEGIN -- PARTE 7: POLICIES - PRODUCT_VARIANTS -- ============================================================ + DROP POLICY IF EXISTS "org_members_view_variants" ON public.product_variants; CREATE POLICY "org_members_view_variants" ON public.product_variants FOR SELECT TO authenticated USING ( @@ -155,6 +164,7 @@ BEGIN ) ); + DROP POLICY IF EXISTS "org_admins_manage_variants" ON public.product_variants; CREATE POLICY "org_admins_manage_variants" ON public.product_variants FOR ALL TO authenticated USING ( @@ -176,14 +186,17 @@ BEGIN -- PARTE 8: POLICIES - QUOTES -- ============================================================ + DROP POLICY IF EXISTS "org_members_view_quotes" ON public.quotes; CREATE POLICY "org_members_view_quotes" ON public.quotes FOR SELECT TO authenticated USING (public.user_is_org_member(organization_id)); + DROP POLICY IF EXISTS "org_members_create_quotes" ON public.quotes; CREATE POLICY "org_members_create_quotes" ON public.quotes FOR INSERT TO authenticated WITH CHECK (public.user_is_org_member(organization_id)); + DROP POLICY IF EXISTS "org_members_update_own_quotes" ON public.quotes; CREATE POLICY "org_members_update_own_quotes" ON public.quotes FOR UPDATE TO authenticated USING ( @@ -191,6 +204,7 @@ BEGIN AND (created_by = auth.uid() OR public.is_org_admin(organization_id)) ); + DROP POLICY IF EXISTS "org_admins_delete_quotes" ON public.quotes; CREATE POLICY "org_admins_delete_quotes" ON public.quotes FOR DELETE TO authenticated USING (public.is_org_owner_or_admin(organization_id)); @@ -199,6 +213,7 @@ BEGIN -- PARTE 9: POLICIES - QUOTE_ITEMS -- ============================================================ + DROP POLICY IF EXISTS "org_members_view_quote_items" ON public.quote_items; CREATE POLICY "org_members_view_quote_items" ON public.quote_items FOR SELECT TO authenticated USING ( @@ -209,6 +224,7 @@ BEGIN ) ); + DROP POLICY IF EXISTS "org_members_manage_quote_items" ON public.quote_items; CREATE POLICY "org_members_manage_quote_items" ON public.quote_items FOR ALL TO authenticated USING ( @@ -230,14 +246,17 @@ BEGIN -- PARTE 10: POLICIES - ORDERS -- ============================================================ + DROP POLICY IF EXISTS "org_members_view_orders" ON public.orders; CREATE POLICY "org_members_view_orders" ON public.orders FOR SELECT TO authenticated USING (public.user_is_org_member(organization_id)); + DROP POLICY IF EXISTS "org_members_create_orders" ON public.orders; CREATE POLICY "org_members_create_orders" ON public.orders FOR INSERT TO authenticated WITH CHECK (public.user_is_org_member(organization_id)); + DROP POLICY IF EXISTS "org_members_update_own_orders" ON public.orders; CREATE POLICY "org_members_update_own_orders" ON public.orders FOR UPDATE TO authenticated USING ( @@ -245,6 +264,7 @@ BEGIN AND (created_by = auth.uid() OR public.is_org_admin(organization_id)) ); + DROP POLICY IF EXISTS "org_admins_delete_orders" ON public.orders; CREATE POLICY "org_admins_delete_orders" ON public.orders FOR DELETE TO authenticated USING (public.is_org_owner_or_admin(organization_id)); @@ -253,6 +273,7 @@ BEGIN -- PARTE 11: POLICIES - ORDER_ITEMS -- ============================================================ + DROP POLICY IF EXISTS "org_members_view_order_items" ON public.order_items; CREATE POLICY "org_members_view_order_items" ON public.order_items FOR SELECT TO authenticated USING ( @@ -263,6 +284,7 @@ BEGIN ) ); + DROP POLICY IF EXISTS "org_members_manage_order_items" ON public.order_items; CREATE POLICY "org_members_manage_order_items" ON public.order_items FOR ALL TO authenticated USING ( @@ -284,6 +306,7 @@ BEGIN -- PARTE 12: POLICIES - PAYMENTS -- ============================================================ + DROP POLICY IF EXISTS "org_members_view_payments" ON public.payments; CREATE POLICY "org_members_view_payments" ON public.payments FOR SELECT TO authenticated USING ( @@ -294,6 +317,7 @@ BEGIN ) ); + DROP POLICY IF EXISTS "org_admins_manage_payments" ON public.payments; CREATE POLICY "org_admins_manage_payments" ON public.payments FOR ALL TO authenticated USING ( @@ -315,10 +339,12 @@ BEGIN -- PARTE 13: POLICIES - BITRIX_CLIENTS -- ============================================================ + DROP POLICY IF EXISTS "org_members_view_clients" ON public.bitrix_clients; CREATE POLICY "org_members_view_clients" ON public.bitrix_clients FOR SELECT TO authenticated USING (public.user_is_org_member(organization_id)); + DROP POLICY IF EXISTS "org_admins_manage_clients" ON public.bitrix_clients; CREATE POLICY "org_admins_manage_clients" ON public.bitrix_clients FOR ALL TO authenticated USING (public.is_org_owner_or_admin(organization_id)) @@ -328,14 +354,17 @@ BEGIN -- PARTE 14: POLICIES - MOCKUPS -- ============================================================ + DROP POLICY IF EXISTS "org_members_view_mockup_jobs" ON public.mockup_generation_jobs; CREATE POLICY "org_members_view_mockup_jobs" ON public.mockup_generation_jobs FOR SELECT TO authenticated USING (public.user_is_org_member(organization_id)); + DROP POLICY IF EXISTS "org_members_create_mockup_jobs" ON public.mockup_generation_jobs; CREATE POLICY "org_members_create_mockup_jobs" ON public.mockup_generation_jobs FOR INSERT TO authenticated WITH CHECK (public.user_is_org_member(organization_id)); + DROP POLICY IF EXISTS "org_members_view_generated_mockups" ON public.generated_mockups; CREATE POLICY "org_members_view_generated_mockups" ON public.generated_mockups FOR SELECT TO authenticated USING ( @@ -350,10 +379,12 @@ BEGIN -- PARTE 15: POLICIES - COLLECTIONS -- ============================================================ + DROP POLICY IF EXISTS "org_members_view_collections" ON public.collections; CREATE POLICY "org_members_view_collections" ON public.collections FOR SELECT TO authenticated USING (public.user_is_org_member(organization_id)); + DROP POLICY IF EXISTS "org_admins_manage_collections" ON public.collections; CREATE POLICY "org_admins_manage_collections" ON public.collections FOR ALL TO authenticated USING (public.is_org_owner_or_admin(organization_id)) @@ -363,10 +394,12 @@ BEGIN -- PARTE 16: POLICIES - PERSONALIZATION_TECHNIQUES (GLOBAL) -- ============================================================ + DROP POLICY IF EXISTS "anyone_view_techniques" ON public.personalization_techniques; CREATE POLICY "anyone_view_techniques" ON public.personalization_techniques FOR SELECT TO authenticated USING (is_active = true); + DROP POLICY IF EXISTS "admins_manage_techniques" ON public.personalization_techniques; CREATE POLICY "admins_manage_techniques" ON public.personalization_techniques FOR ALL TO authenticated USING ( @@ -381,10 +414,12 @@ BEGIN -- PARTE 17: POLICIES - NOTIFICATIONS (USER-SCOPED) -- ============================================================ + DROP POLICY IF EXISTS "users_view_own_notifications" ON public.notifications; CREATE POLICY "users_view_own_notifications" ON public.notifications FOR SELECT TO authenticated USING (user_id = auth.uid()); + DROP POLICY IF EXISTS "users_update_own_notifications" ON public.notifications; CREATE POLICY "users_update_own_notifications" ON public.notifications FOR UPDATE TO authenticated USING (user_id = auth.uid()); @@ -393,6 +428,7 @@ BEGIN -- PARTE 18: POLICIES - SYSTEM TABLES (ADMIN ONLY) -- ============================================================ + DROP POLICY IF EXISTS "admins_view_feature_flags" ON public.feature_flags; CREATE POLICY "admins_view_feature_flags" ON public.feature_flags FOR SELECT TO authenticated USING ( @@ -403,6 +439,7 @@ BEGIN ) ); + DROP POLICY IF EXISTS "admins_manage_system_settings" ON public.system_settings; CREATE POLICY "admins_manage_system_settings" ON public.system_settings FOR ALL TO authenticated USING ( diff --git a/supabase/migrations/20250103_05_rls_remaining.sql b/supabase/migrations/20250103_05_rls_remaining.sql index 24cbc00e7..7a7a9e9c2 100644 --- a/supabase/migrations/20250103_05_rls_remaining.sql +++ b/supabase/migrations/20250103_05_rls_remaining.sql @@ -45,18 +45,21 @@ ALTER TABLE public.notification_templates ENABLE ROW LEVEL SECURITY; -- ============================================================ -- Users veem apenas seus próprios favoritos +DROP POLICY IF EXISTS "users_view_own_favorites" ON public.user_favorites; CREATE POLICY "users_view_own_favorites" ON public.user_favorites FOR SELECT TO authenticated USING (user_id = auth.uid()); -- Users criam favoritos para si mesmos +DROP POLICY IF EXISTS "users_create_own_favorites" ON public.user_favorites; CREATE POLICY "users_create_own_favorites" ON public.user_favorites FOR INSERT TO authenticated WITH CHECK (user_id = auth.uid()); -- Users deletam seus próprios favoritos +DROP POLICY IF EXISTS "users_delete_own_favorites" ON public.user_favorites; CREATE POLICY "users_delete_own_favorites" ON public.user_favorites FOR DELETE TO authenticated @@ -66,11 +69,13 @@ USING (user_id = auth.uid()); -- PARTE 3: POLICIES - USER FILTER PRESETS -- ============================================================ +DROP POLICY IF EXISTS "users_view_own_presets" ON public.user_filter_presets; CREATE POLICY "users_view_own_presets" ON public.user_filter_presets FOR SELECT TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "users_manage_own_presets" ON public.user_filter_presets; CREATE POLICY "users_manage_own_presets" ON public.user_filter_presets FOR ALL TO authenticated @@ -81,11 +86,13 @@ WITH CHECK (user_id = auth.uid()); -- PARTE 4: POLICIES - SAVED FILTERS -- ============================================================ +DROP POLICY IF EXISTS "users_view_own_filters" ON public.saved_filters; CREATE POLICY "users_view_own_filters" ON public.saved_filters FOR SELECT TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "users_manage_own_filters" ON public.saved_filters; CREATE POLICY "users_manage_own_filters" ON public.saved_filters FOR ALL TO authenticated @@ -96,11 +103,13 @@ WITH CHECK (user_id = auth.uid()); -- PARTE 5: POLICIES - PUSH SUBSCRIPTIONS -- ============================================================ +DROP POLICY IF EXISTS "users_view_own_subscriptions" ON public.push_subscriptions; CREATE POLICY "users_view_own_subscriptions" ON public.push_subscriptions FOR SELECT TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "users_manage_own_subscriptions" ON public.push_subscriptions; CREATE POLICY "users_manage_own_subscriptions" ON public.push_subscriptions FOR ALL TO authenticated @@ -111,11 +120,13 @@ WITH CHECK (user_id = auth.uid()); -- PARTE 6: POLICIES - NOTIFICATION PREFERENCES -- ============================================================ +DROP POLICY IF EXISTS "users_view_own_notification_prefs" ON public.notification_preferences; CREATE POLICY "users_view_own_notification_prefs" ON public.notification_preferences FOR SELECT TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "users_manage_own_notification_prefs" ON public.notification_preferences; CREATE POLICY "users_manage_own_notification_prefs" ON public.notification_preferences FOR ALL TO authenticated @@ -127,6 +138,7 @@ WITH CHECK (user_id = auth.uid()); -- ============================================================ -- Members da org podem ver analytics de produtos da org +DROP POLICY IF EXISTS "org_members_view_product_views" ON public.product_views; CREATE POLICY "org_members_view_product_views" ON public.product_views FOR SELECT TO authenticated @@ -139,6 +151,7 @@ USING ( ); -- Qualquer user autenticado pode registrar view +DROP POLICY IF EXISTS "authenticated_create_product_views" ON public.product_views; CREATE POLICY "authenticated_create_product_views" ON public.product_views FOR INSERT TO authenticated @@ -149,6 +162,7 @@ WITH CHECK (true); -- ============================================================ -- Todos da org podem ver reviews de produtos da org +DROP POLICY IF EXISTS "org_members_view_product_reviews" ON public.product_reviews; CREATE POLICY "org_members_view_product_reviews" ON public.product_reviews FOR SELECT TO authenticated @@ -161,6 +175,7 @@ USING ( ); -- Members podem criar reviews +DROP POLICY IF EXISTS "org_members_create_reviews" ON public.product_reviews; CREATE POLICY "org_members_create_reviews" ON public.product_reviews FOR INSERT TO authenticated @@ -173,6 +188,7 @@ WITH CHECK ( ); -- Users podem editar/deletar próprios reviews +DROP POLICY IF EXISTS "users_manage_own_reviews" ON public.product_reviews; CREATE POLICY "users_manage_own_reviews" ON public.product_reviews FOR ALL TO authenticated @@ -183,11 +199,13 @@ WITH CHECK (user_id = auth.uid()); -- PARTE 9: POLICIES - PRODUCT COMPARISONS -- ============================================================ +DROP POLICY IF EXISTS "users_view_own_comparisons" ON public.product_comparisons; CREATE POLICY "users_view_own_comparisons" ON public.product_comparisons FOR SELECT TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "users_manage_own_comparisons" ON public.product_comparisons; CREATE POLICY "users_manage_own_comparisons" ON public.product_comparisons FOR ALL TO authenticated @@ -199,6 +217,7 @@ WITH CHECK (user_id = auth.uid()); -- ============================================================ -- Members da org podem ver histórico de preços +DROP POLICY IF EXISTS "org_members_view_price_history" ON public.product_price_history; CREATE POLICY "org_members_view_price_history" ON public.product_price_history FOR SELECT TO authenticated @@ -212,6 +231,7 @@ USING ( -- Sistema cria histórico automaticamente (via trigger) -- Admins podem inserir manualmente se necessário +DROP POLICY IF EXISTS "admins_create_price_history" ON public.product_price_history; CREATE POLICY "admins_create_price_history" ON public.product_price_history FOR INSERT TO authenticated @@ -228,6 +248,7 @@ WITH CHECK ( -- ============================================================ -- Members da org podem ver comentários de quotes da org +DROP POLICY IF EXISTS "org_members_view_quote_comments" ON public.quote_comments; CREATE POLICY "org_members_view_quote_comments" ON public.quote_comments FOR SELECT TO authenticated @@ -240,6 +261,7 @@ USING ( ); -- Members podem criar comentários +DROP POLICY IF EXISTS "org_members_create_quote_comments" ON public.quote_comments; CREATE POLICY "org_members_create_quote_comments" ON public.quote_comments FOR INSERT TO authenticated @@ -252,6 +274,7 @@ WITH CHECK ( ); -- Users podem editar/deletar próprios comentários +DROP POLICY IF EXISTS "users_manage_own_comments" ON public.quote_comments; CREATE POLICY "users_manage_own_comments" ON public.quote_comments FOR ALL TO authenticated @@ -263,6 +286,7 @@ WITH CHECK (user_id = auth.uid()); -- ============================================================ -- Members da org podem ver versões de quotes da org +DROP POLICY IF EXISTS "org_members_view_quote_versions" ON public.quote_versions; CREATE POLICY "org_members_view_quote_versions" ON public.quote_versions FOR SELECT TO authenticated @@ -275,6 +299,7 @@ USING ( ); -- Sistema cria versões automaticamente (via trigger) +DROP POLICY IF EXISTS "system_create_quote_versions" ON public.quote_versions; CREATE POLICY "system_create_quote_versions" ON public.quote_versions FOR INSERT TO authenticated @@ -291,6 +316,7 @@ WITH CHECK ( -- ============================================================ -- Members podem ver templates da org +DROP POLICY IF EXISTS "org_members_view_quote_templates" ON public.quote_templates; CREATE POLICY "org_members_view_quote_templates" ON public.quote_templates FOR SELECT TO authenticated @@ -300,6 +326,7 @@ USING ( ); -- Admins podem criar templates +DROP POLICY IF EXISTS "admins_create_quote_templates" ON public.quote_templates; CREATE POLICY "admins_create_quote_templates" ON public.quote_templates FOR INSERT TO authenticated @@ -309,6 +336,7 @@ WITH CHECK ( ); -- Admins podem editar templates da org +DROP POLICY IF EXISTS "admins_manage_quote_templates" ON public.quote_templates; CREATE POLICY "admins_manage_quote_templates" ON public.quote_templates FOR ALL TO authenticated @@ -320,6 +348,7 @@ WITH CHECK (public.is_org_admin(organization_id)); -- ============================================================ -- Members da org podem ver contatos de clientes da org +DROP POLICY IF EXISTS "org_members_view_client_contacts" ON public.client_contacts; CREATE POLICY "org_members_view_client_contacts" ON public.client_contacts FOR SELECT TO authenticated @@ -332,6 +361,7 @@ USING ( ); -- Members podem criar contatos +DROP POLICY IF EXISTS "org_members_create_client_contacts" ON public.client_contacts; CREATE POLICY "org_members_create_client_contacts" ON public.client_contacts FOR INSERT TO authenticated @@ -344,6 +374,7 @@ WITH CHECK ( ); -- Admins podem editar/deletar contatos +DROP POLICY IF EXISTS "admins_manage_client_contacts" ON public.client_contacts; CREATE POLICY "admins_manage_client_contacts" ON public.client_contacts FOR ALL TO authenticated @@ -367,6 +398,7 @@ WITH CHECK ( -- ============================================================ -- Members da org podem ver notas de clientes da org +DROP POLICY IF EXISTS "org_members_view_client_notes" ON public.client_notes; CREATE POLICY "org_members_view_client_notes" ON public.client_notes FOR SELECT TO authenticated @@ -379,6 +411,7 @@ USING ( ); -- Members podem criar notas +DROP POLICY IF EXISTS "org_members_create_client_notes" ON public.client_notes; CREATE POLICY "org_members_create_client_notes" ON public.client_notes FOR INSERT TO authenticated @@ -391,6 +424,7 @@ WITH CHECK ( ); -- Criador ou admins podem editar/deletar +DROP POLICY IF EXISTS "creators_or_admins_manage_notes" ON public.client_notes; CREATE POLICY "creators_or_admins_manage_notes" ON public.client_notes FOR ALL TO authenticated @@ -416,6 +450,7 @@ WITH CHECK ( -- ============================================================ -- Admins podem ver analytics +DROP POLICY IF EXISTS "admins_view_analytics" ON public.analytics_events; CREATE POLICY "admins_view_analytics" ON public.analytics_events FOR SELECT TO authenticated @@ -428,6 +463,7 @@ USING ( ); -- Sistema pode criar eventos +DROP POLICY IF EXISTS "system_create_analytics" ON public.analytics_events; CREATE POLICY "system_create_analytics" ON public.analytics_events FOR INSERT TO authenticated @@ -438,12 +474,14 @@ WITH CHECK (true); -- ============================================================ -- Users veem próprias buscas +DROP POLICY IF EXISTS "users_view_own_searches" ON public.search_queries; CREATE POLICY "users_view_own_searches" ON public.search_queries FOR SELECT TO authenticated USING (user_id = auth.uid() OR user_id IS NULL); -- Qualquer um pode registrar busca +DROP POLICY IF EXISTS "authenticated_create_searches" ON public.search_queries; CREATE POLICY "authenticated_create_searches" ON public.search_queries FOR INSERT TO authenticated @@ -454,6 +492,7 @@ WITH CHECK (true); -- ============================================================ -- Apenas owners podem ver audit log +DROP POLICY IF EXISTS "owners_view_audit_log" ON public.audit_log; CREATE POLICY "owners_view_audit_log" ON public.audit_log FOR SELECT TO authenticated @@ -466,6 +505,7 @@ USING ( ); -- Sistema cria logs automaticamente +DROP POLICY IF EXISTS "system_create_audit_log" ON public.audit_log; CREATE POLICY "system_create_audit_log" ON public.audit_log FOR INSERT TO authenticated @@ -476,6 +516,7 @@ WITH CHECK (true); -- ============================================================ -- Admins podem ver jobs de sync +DROP POLICY IF EXISTS "admins_view_sync_jobs" ON public.sync_jobs; CREATE POLICY "admins_view_sync_jobs" ON public.sync_jobs FOR SELECT TO authenticated @@ -488,12 +529,14 @@ USING ( ); -- Sistema cria jobs +DROP POLICY IF EXISTS "system_create_sync_jobs" ON public.sync_jobs; CREATE POLICY "system_create_sync_jobs" ON public.sync_jobs FOR INSERT TO authenticated WITH CHECK (true); -- Admins podem atualizar status +DROP POLICY IF EXISTS "admins_update_sync_jobs" ON public.sync_jobs; CREATE POLICY "admins_update_sync_jobs" ON public.sync_jobs FOR UPDATE TO authenticated @@ -510,12 +553,14 @@ USING ( -- ============================================================ -- Links públicos podem ser vistos por qualquer um +DROP POLICY IF EXISTS "public_view_approval_links" ON public.mockup_approval_links; CREATE POLICY "public_view_approval_links" ON public.mockup_approval_links FOR SELECT TO anon, authenticated USING (is_active = true AND expires_at > NOW()); -- Members da org podem criar links +DROP POLICY IF EXISTS "org_members_create_approval_links" ON public.mockup_approval_links; CREATE POLICY "org_members_create_approval_links" ON public.mockup_approval_links FOR INSERT TO authenticated @@ -532,12 +577,14 @@ WITH CHECK ( -- ============================================================ -- Todos podem ler templates ativos +DROP POLICY IF EXISTS "all_view_active_templates" ON public.notification_templates; CREATE POLICY "all_view_active_templates" ON public.notification_templates FOR SELECT TO authenticated USING (is_active = true); -- Apenas admins podem gerenciar templates +DROP POLICY IF EXISTS "admins_manage_templates" ON public.notification_templates; CREATE POLICY "admins_manage_templates" ON public.notification_templates FOR ALL TO authenticated diff --git a/supabase/migrations/20250103_05_rls_remaining_FIXED.sql b/supabase/migrations/20250103_05_rls_remaining_FIXED.sql index ea140c8fb..3cbc62b91 100644 --- a/supabase/migrations/20250103_05_rls_remaining_FIXED.sql +++ b/supabase/migrations/20250103_05_rls_remaining_FIXED.sql @@ -45,16 +45,19 @@ ALTER TABLE public.notification_templates ENABLE ROW LEVEL SECURITY; -- PARTE 2: POLICIES - USER FAVORITES (USER-SCOPED) -- ============================================================ +DROP POLICY IF EXISTS "users_view_own_favorites" ON public.user_favorites; CREATE POLICY "users_view_own_favorites" ON public.user_favorites FOR SELECT TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "users_create_own_favorites" ON public.user_favorites; CREATE POLICY "users_create_own_favorites" ON public.user_favorites FOR INSERT TO authenticated WITH CHECK (user_id = auth.uid()); +DROP POLICY IF EXISTS "users_delete_own_favorites" ON public.user_favorites; CREATE POLICY "users_delete_own_favorites" ON public.user_favorites FOR DELETE TO authenticated @@ -64,11 +67,13 @@ USING (user_id = auth.uid()); -- PARTE 3: POLICIES - USER FILTER PRESETS (USER-SCOPED) -- ============================================================ +DROP POLICY IF EXISTS "users_view_own_presets" ON public.user_filter_presets; CREATE POLICY "users_view_own_presets" ON public.user_filter_presets FOR SELECT TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "users_manage_own_presets" ON public.user_filter_presets; CREATE POLICY "users_manage_own_presets" ON public.user_filter_presets FOR ALL TO authenticated @@ -79,11 +84,13 @@ WITH CHECK (user_id = auth.uid()); -- PARTE 4: POLICIES - SAVED FILTERS (USER-SCOPED) -- ============================================================ +DROP POLICY IF EXISTS "users_view_own_filters" ON public.saved_filters; CREATE POLICY "users_view_own_filters" ON public.saved_filters FOR SELECT TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "users_manage_own_filters" ON public.saved_filters; CREATE POLICY "users_manage_own_filters" ON public.saved_filters FOR ALL TO authenticated @@ -94,11 +101,13 @@ WITH CHECK (user_id = auth.uid()); -- PARTE 5: POLICIES - PUSH SUBSCRIPTIONS (USER-SCOPED) -- ============================================================ +DROP POLICY IF EXISTS "users_view_own_subscriptions" ON public.push_subscriptions; CREATE POLICY "users_view_own_subscriptions" ON public.push_subscriptions FOR SELECT TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "users_manage_own_subscriptions" ON public.push_subscriptions; CREATE POLICY "users_manage_own_subscriptions" ON public.push_subscriptions FOR ALL TO authenticated @@ -109,11 +118,13 @@ WITH CHECK (user_id = auth.uid()); -- PARTE 6: POLICIES - NOTIFICATION PREFERENCES (USER-SCOPED) -- ============================================================ +DROP POLICY IF EXISTS "users_view_own_notification_prefs" ON public.notification_preferences; CREATE POLICY "users_view_own_notification_prefs" ON public.notification_preferences FOR SELECT TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "users_manage_own_notification_prefs" ON public.notification_preferences; CREATE POLICY "users_manage_own_notification_prefs" ON public.notification_preferences FOR ALL TO authenticated @@ -125,12 +136,14 @@ WITH CHECK (user_id = auth.uid()); -- ============================================================ -- Qualquer user autenticado pode ver views (analytics público) +DROP POLICY IF EXISTS "authenticated_view_product_views" ON public.product_views; CREATE POLICY "authenticated_view_product_views" ON public.product_views FOR SELECT TO authenticated USING (true); -- Qualquer user autenticado pode registrar view +DROP POLICY IF EXISTS "authenticated_create_product_views" ON public.product_views; CREATE POLICY "authenticated_create_product_views" ON public.product_views FOR INSERT TO authenticated @@ -186,11 +199,13 @@ END $$; -- PARTE 9: POLICIES - PRODUCT COMPARISONS (USER-SCOPED) -- ============================================================ +DROP POLICY IF EXISTS "users_view_own_comparisons" ON public.product_comparisons; CREATE POLICY "users_view_own_comparisons" ON public.product_comparisons FOR SELECT TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "users_manage_own_comparisons" ON public.product_comparisons; CREATE POLICY "users_manage_own_comparisons" ON public.product_comparisons FOR ALL TO authenticated @@ -313,16 +328,19 @@ END $$; -- ============================================================ -- Templates podem ser globais (NULL) ou por org +DROP POLICY IF EXISTS "all_view_quote_templates" ON public.quote_templates; CREATE POLICY "all_view_quote_templates" ON public.quote_templates FOR SELECT TO authenticated USING (true); +DROP POLICY IF EXISTS "authenticated_create_quote_templates" ON public.quote_templates; CREATE POLICY "authenticated_create_quote_templates" ON public.quote_templates FOR INSERT TO authenticated WITH CHECK (true); +DROP POLICY IF EXISTS "users_manage_own_templates" ON public.quote_templates; CREATE POLICY "users_manage_own_templates" ON public.quote_templates FOR ALL TO authenticated @@ -418,12 +436,14 @@ END $$; -- ============================================================ -- Analytics podem ser vistos por todos autenticados +DROP POLICY IF EXISTS "authenticated_view_analytics" ON public.analytics_events; CREATE POLICY "authenticated_view_analytics" ON public.analytics_events FOR SELECT TO authenticated USING (true); -- Sistema pode criar eventos +DROP POLICY IF EXISTS "system_create_analytics" ON public.analytics_events; CREATE POLICY "system_create_analytics" ON public.analytics_events FOR INSERT TO authenticated @@ -434,12 +454,14 @@ WITH CHECK (true); -- ============================================================ -- Users veem todas buscas (para insights) +DROP POLICY IF EXISTS "authenticated_view_searches" ON public.search_queries; CREATE POLICY "authenticated_view_searches" ON public.search_queries FOR SELECT TO authenticated USING (true); -- Qualquer um pode registrar busca +DROP POLICY IF EXISTS "authenticated_create_searches" ON public.search_queries; CREATE POLICY "authenticated_create_searches" ON public.search_queries FOR INSERT TO authenticated @@ -450,12 +472,14 @@ WITH CHECK (true); -- ============================================================ -- Todos podem ver audit log (transparência) +DROP POLICY IF EXISTS "authenticated_view_audit_log" ON public.audit_log; CREATE POLICY "authenticated_view_audit_log" ON public.audit_log FOR SELECT TO authenticated USING (true); -- Sistema cria logs automaticamente +DROP POLICY IF EXISTS "system_create_audit_log" ON public.audit_log; CREATE POLICY "system_create_audit_log" ON public.audit_log FOR INSERT TO authenticated @@ -466,18 +490,21 @@ WITH CHECK (true); -- ============================================================ -- Todos podem ver status de jobs +DROP POLICY IF EXISTS "authenticated_view_sync_jobs" ON public.sync_jobs; CREATE POLICY "authenticated_view_sync_jobs" ON public.sync_jobs FOR SELECT TO authenticated USING (true); -- Sistema cria jobs +DROP POLICY IF EXISTS "system_create_sync_jobs" ON public.sync_jobs; CREATE POLICY "system_create_sync_jobs" ON public.sync_jobs FOR INSERT TO authenticated WITH CHECK (true); -- Sistema atualiza status +DROP POLICY IF EXISTS "system_update_sync_jobs" ON public.sync_jobs; CREATE POLICY "system_update_sync_jobs" ON public.sync_jobs FOR UPDATE TO authenticated @@ -488,12 +515,14 @@ USING (true); -- ============================================================ -- Links públicos podem ser vistos por qualquer um +DROP POLICY IF EXISTS "public_view_approval_links" ON public.mockup_approval_links; CREATE POLICY "public_view_approval_links" ON public.mockup_approval_links FOR SELECT TO anon, authenticated USING (is_active = true AND expires_at > NOW()); -- Authenticated podem criar links +DROP POLICY IF EXISTS "authenticated_create_approval_links" ON public.mockup_approval_links; CREATE POLICY "authenticated_create_approval_links" ON public.mockup_approval_links FOR INSERT TO authenticated @@ -504,12 +533,14 @@ WITH CHECK (true); -- ============================================================ -- Todos podem ler templates ativos +DROP POLICY IF EXISTS "all_view_active_templates" ON public.notification_templates; CREATE POLICY "all_view_active_templates" ON public.notification_templates FOR SELECT TO authenticated USING (is_active = true); -- Authenticated podem gerenciar templates +DROP POLICY IF EXISTS "authenticated_manage_templates" ON public.notification_templates; CREATE POLICY "authenticated_manage_templates" ON public.notification_templates FOR ALL TO authenticated diff --git a/supabase/migrations/20250103_07_complete_catalog_structure.sql b/supabase/migrations/20250103_07_complete_catalog_structure.sql index 20f7376c7..b39fff6d6 100644 --- a/supabase/migrations/20250103_07_complete_catalog_structure.sql +++ b/supabase/migrations/20250103_07_complete_catalog_structure.sql @@ -10,7 +10,7 @@ -- Diferenciar produtos simples de kits ALTER TABLE public.products -ADD COLUMN product_type TEXT DEFAULT 'simple' +ADD COLUMN IF NOT EXISTS product_type TEXT DEFAULT 'simple' CHECK (product_type IN ('simple', 'kit', 'component')); COMMENT ON COLUMN public.products.product_type IS ' @@ -24,7 +24,7 @@ component = componente usado apenas dentro de kits -- Define quais produtos compõem um kit -- ============================================================ -CREATE TABLE public.product_kit_components ( +CREATE TABLE IF NOT EXISTS public.product_kit_components ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), -- Produto KIT pai @@ -66,10 +66,11 @@ COMMENT ON TABLE public.product_kit_components IS 'Componentes que formam um produto KIT. Ex: Kit Executivo = Caneta + Caderno + Mouse Pad'; -- Índices -CREATE INDEX idx_kit_components_kit ON public.product_kit_components(kit_product_id); -CREATE INDEX idx_kit_components_component ON public.product_kit_components(component_product_id); +CREATE INDEX IF NOT EXISTS idx_kit_components_kit ON public.product_kit_components(kit_product_id); +CREATE INDEX IF NOT EXISTS idx_kit_components_component ON public.product_kit_components(component_product_id); -- Trigger updated_at +DROP TRIGGER IF EXISTS update_product_kit_components_updated_at ON public.product_kit_components; CREATE TRIGGER update_product_kit_components_updated_at BEFORE UPDATE ON public.product_kit_components FOR EACH ROW @@ -80,7 +81,7 @@ CREATE TRIGGER update_product_kit_components_updated_at -- Define quais técnicas cada produto aceita e seus preços -- ============================================================ -CREATE TABLE public.product_personalization_options ( +CREATE TABLE IF NOT EXISTS public.product_personalization_options ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), -- Produto @@ -136,11 +137,12 @@ COMMENT ON TABLE public.product_personalization_options IS 'Define quais técnicas de personalização cada produto aceita e preços específicos. Ex: Caneca aceita Serigrafia e Sublimação, mas NÃO Bordado.'; -- Índices -CREATE INDEX idx_personalization_options_product ON public.product_personalization_options(product_id); -CREATE INDEX idx_personalization_options_technique ON public.product_personalization_options(technique_id); -CREATE INDEX idx_personalization_options_available ON public.product_personalization_options(is_available) WHERE is_available = true; +CREATE INDEX IF NOT EXISTS idx_personalization_options_product ON public.product_personalization_options(product_id); +CREATE INDEX IF NOT EXISTS idx_personalization_options_technique ON public.product_personalization_options(technique_id); +CREATE INDEX IF NOT EXISTS idx_personalization_options_available ON public.product_personalization_options(is_available) WHERE is_available = true; -- Trigger updated_at +DROP TRIGGER IF EXISTS update_product_personalization_options_updated_at ON public.product_personalization_options; CREATE TRIGGER update_product_personalization_options_updated_at BEFORE UPDATE ON public.product_personalization_options FOR EACH ROW @@ -151,7 +153,7 @@ CREATE TRIGGER update_product_personalization_options_updated_at -- Define áreas específicas de impressão em cada produto -- ============================================================ -CREATE TABLE public.product_print_areas ( +CREATE TABLE IF NOT EXISTS public.product_print_areas ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), -- Produto @@ -204,11 +206,12 @@ COMMENT ON TABLE public.product_print_areas IS 'Áreas específicas de impressão em cada produto. Ex: Camiseta tem Frente, Costas, Manga, Bolso.'; -- Índices -CREATE INDEX idx_print_areas_product ON public.product_print_areas(product_id); -CREATE INDEX idx_print_areas_active ON public.product_print_areas(is_active) WHERE is_active = true; -CREATE INDEX idx_print_areas_primary ON public.product_print_areas(is_primary) WHERE is_primary = true; +CREATE INDEX IF NOT EXISTS idx_print_areas_product ON public.product_print_areas(product_id); +CREATE INDEX IF NOT EXISTS idx_print_areas_active ON public.product_print_areas(is_active) WHERE is_active = true; +CREATE INDEX IF NOT EXISTS idx_print_areas_primary ON public.product_print_areas(is_primary) WHERE is_primary = true; -- Trigger updated_at +DROP TRIGGER IF EXISTS update_product_print_areas_updated_at ON public.product_print_areas; CREATE TRIGGER update_product_print_areas_updated_at BEFORE UPDATE ON public.product_print_areas FOR EACH ROW @@ -219,7 +222,7 @@ CREATE TRIGGER update_product_print_areas_updated_at -- Tabela de preços escalonados por quantidade -- ============================================================ -CREATE TABLE public.product_technique_pricing_tiers ( +CREATE TABLE IF NOT EXISTS public.product_technique_pricing_tiers ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), -- Referência à opção de personalização @@ -244,7 +247,7 @@ COMMENT ON TABLE public.product_technique_pricing_tiers IS 'Preços escalonados por quantidade. Ex: 1-50 unidades = R$ 10,00 | 51-100 = R$ 8,50 | 101+ = R$ 7,00'; -- Índices -CREATE INDEX idx_pricing_tiers_option ON public.product_technique_pricing_tiers(personalization_option_id); +CREATE INDEX IF NOT EXISTS idx_pricing_tiers_option ON public.product_technique_pricing_tiers(personalization_option_id); -- ============================================================ -- PARTE 6: VIEW - Produtos com Técnicas Disponíveis @@ -481,6 +484,7 @@ COMMENT ON FUNCTION public.create_default_print_areas_for_product IS -- PRODUCT_KIT_COMPONENTS ALTER TABLE public.product_kit_components ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "org_members_view_kit_components" ON public.product_kit_components; CREATE POLICY "org_members_view_kit_components" ON public.product_kit_components FOR SELECT TO authenticated @@ -492,6 +496,7 @@ USING ( ) ); +DROP POLICY IF EXISTS "org_admins_manage_kit_components" ON public.product_kit_components; CREATE POLICY "org_admins_manage_kit_components" ON public.product_kit_components FOR ALL TO authenticated @@ -513,6 +518,7 @@ WITH CHECK ( -- PRODUCT_PERSONALIZATION_OPTIONS ALTER TABLE public.product_personalization_options ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "org_members_view_personalization_options" ON public.product_personalization_options; CREATE POLICY "org_members_view_personalization_options" ON public.product_personalization_options FOR SELECT TO authenticated @@ -524,6 +530,7 @@ USING ( ) ); +DROP POLICY IF EXISTS "org_admins_manage_personalization_options" ON public.product_personalization_options; CREATE POLICY "org_admins_manage_personalization_options" ON public.product_personalization_options FOR ALL TO authenticated @@ -545,6 +552,7 @@ WITH CHECK ( -- PRODUCT_PRINT_AREAS ALTER TABLE public.product_print_areas ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "org_members_view_print_areas" ON public.product_print_areas; CREATE POLICY "org_members_view_print_areas" ON public.product_print_areas FOR SELECT TO authenticated @@ -556,6 +564,7 @@ USING ( ) ); +DROP POLICY IF EXISTS "org_admins_manage_print_areas" ON public.product_print_areas; CREATE POLICY "org_admins_manage_print_areas" ON public.product_print_areas FOR ALL TO authenticated @@ -577,6 +586,7 @@ WITH CHECK ( -- PRODUCT_TECHNIQUE_PRICING_TIERS ALTER TABLE public.product_technique_pricing_tiers ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "org_members_view_pricing_tiers" ON public.product_technique_pricing_tiers; CREATE POLICY "org_members_view_pricing_tiers" ON public.product_technique_pricing_tiers FOR SELECT TO authenticated @@ -589,6 +599,7 @@ USING ( ) ); +DROP POLICY IF EXISTS "org_admins_manage_pricing_tiers" ON public.product_technique_pricing_tiers; CREATE POLICY "org_admins_manage_pricing_tiers" ON public.product_technique_pricing_tiers FOR ALL TO authenticated diff --git a/supabase/migrations/20250103_rls_no_gamification.sql b/supabase/migrations/20250103_rls_no_gamification.sql index 0f1d7d8ac..10e5dc1f1 100644 --- a/supabase/migrations/20250103_rls_no_gamification.sql +++ b/supabase/migrations/20250103_rls_no_gamification.sql @@ -51,24 +51,29 @@ $$ LANGUAGE plpgsql SECURITY DEFINER; ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY; -- Users podem ver e editar apenas seu próprio perfil +DROP POLICY IF EXISTS "Users can view own profile" ON public.profiles; CREATE POLICY "Users can view own profile" ON public.profiles FOR SELECT USING (auth.uid() = id); +DROP POLICY IF EXISTS "Users can update own profile" ON public.profiles; CREATE POLICY "Users can update own profile" ON public.profiles FOR UPDATE USING (auth.uid() = id); -- Admins veem todos os perfis +DROP POLICY IF EXISTS "Admins can view all profiles" ON public.profiles; CREATE POLICY "Admins can view all profiles" ON public.profiles FOR SELECT USING (public.is_admin()); +DROP POLICY IF EXISTS "Admins can update all profiles" ON public.profiles; CREATE POLICY "Admins can update all profiles" ON public.profiles FOR UPDATE USING (public.is_admin()); -- Managers veem perfis do seu departamento +DROP POLICY IF EXISTS "Managers can view department profiles" ON public.profiles; CREATE POLICY "Managers can view department profiles" ON public.profiles FOR SELECT USING ( @@ -83,24 +88,29 @@ CREATE POLICY "Managers can view department profiles" ALTER TABLE public.products ENABLE ROW LEVEL SECURITY; -- Todos podem ver produtos ativos +DROP POLICY IF EXISTS "Anyone can view active products" ON public.products; CREATE POLICY "Anyone can view active products" ON public.products FOR SELECT USING (is_active = true); -- Admins e managers podem ver todos os produtos +DROP POLICY IF EXISTS "Admins can view all products" ON public.products; CREATE POLICY "Admins can view all products" ON public.products FOR SELECT USING (public.is_manager_or_admin()); -- Apenas admins podem criar/editar produtos +DROP POLICY IF EXISTS "Admins can insert products" ON public.products; CREATE POLICY "Admins can insert products" ON public.products FOR INSERT WITH CHECK (public.is_admin()); +DROP POLICY IF EXISTS "Admins can update products" ON public.products; CREATE POLICY "Admins can update products" ON public.products FOR UPDATE USING (public.is_admin()); +DROP POLICY IF EXISTS "Admins can delete products" ON public.products; CREATE POLICY "Admins can delete products" ON public.products FOR DELETE USING (public.is_admin()); @@ -112,11 +122,13 @@ CREATE POLICY "Admins can delete products" ALTER TABLE public.categories ENABLE ROW LEVEL SECURITY; -- Todos podem ver categorias ativas +DROP POLICY IF EXISTS "Anyone can view active categories" ON public.categories; CREATE POLICY "Anyone can view active categories" ON public.categories FOR SELECT USING (is_active = true); -- Admins gerenciam categorias +DROP POLICY IF EXISTS "Admins can manage categories" ON public.categories; CREATE POLICY "Admins can manage categories" ON public.categories FOR ALL USING (public.is_admin()); @@ -128,11 +140,13 @@ CREATE POLICY "Admins can manage categories" ALTER TABLE public.suppliers ENABLE ROW LEVEL SECURITY; -- Authenticated users podem ver fornecedores ativos +DROP POLICY IF EXISTS "Authenticated users can view active suppliers" ON public.suppliers; CREATE POLICY "Authenticated users can view active suppliers" ON public.suppliers FOR SELECT USING (is_active = true AND auth.role() = 'authenticated'); -- Admins gerenciam fornecedores +DROP POLICY IF EXISTS "Admins can manage suppliers" ON public.suppliers; CREATE POLICY "Admins can manage suppliers" ON public.suppliers FOR ALL USING (public.is_admin()); @@ -144,6 +158,7 @@ CREATE POLICY "Admins can manage suppliers" ALTER TABLE public.quotes ENABLE ROW LEVEL SECURITY; -- Users veem orçamentos que criaram ou foram atribuídos +DROP POLICY IF EXISTS "Users can view own quotes" ON public.quotes; CREATE POLICY "Users can view own quotes" ON public.quotes FOR SELECT USING ( @@ -153,11 +168,13 @@ CREATE POLICY "Users can view own quotes" ); -- Users podem criar orçamentos +DROP POLICY IF EXISTS "Authenticated users can create quotes" ON public.quotes; CREATE POLICY "Authenticated users can create quotes" ON public.quotes FOR INSERT WITH CHECK (auth.role() = 'authenticated'); -- Users podem editar orçamentos que criaram +DROP POLICY IF EXISTS "Users can update own quotes" ON public.quotes; CREATE POLICY "Users can update own quotes" ON public.quotes FOR UPDATE USING ( @@ -166,11 +183,13 @@ CREATE POLICY "Users can update own quotes" ); -- Apenas admins podem deletar +DROP POLICY IF EXISTS "Admins can delete quotes" ON public.quotes; CREATE POLICY "Admins can delete quotes" ON public.quotes FOR DELETE USING (public.is_admin()); -- Aprovação pública (via token) +DROP POLICY IF EXISTS "Public can view quotes with valid token" ON public.quotes; CREATE POLICY "Public can view quotes with valid token" ON public.quotes FOR SELECT USING (approval_token IS NOT NULL); @@ -182,6 +201,7 @@ CREATE POLICY "Public can view quotes with valid token" ALTER TABLE public.quote_items ENABLE ROW LEVEL SECURITY; -- Mesma lógica das quotes (via quote_id) +DROP POLICY IF EXISTS "Users can view own quote items" ON public.quote_items; CREATE POLICY "Users can view own quote items" ON public.quote_items FOR SELECT USING ( @@ -196,6 +216,7 @@ CREATE POLICY "Users can view own quote items" ) ); +DROP POLICY IF EXISTS "Users can manage own quote items" ON public.quote_items; CREATE POLICY "Users can manage own quote items" ON public.quote_items FOR ALL USING ( @@ -213,6 +234,7 @@ CREATE POLICY "Users can manage own quote items" ALTER TABLE public.orders ENABLE ROW LEVEL SECURITY; -- Users veem pedidos que criaram ou foram atribuídos +DROP POLICY IF EXISTS "Users can view own orders" ON public.orders; CREATE POLICY "Users can view own orders" ON public.orders FOR SELECT USING ( @@ -222,11 +244,13 @@ CREATE POLICY "Users can view own orders" ); -- Apenas authenticated podem criar +DROP POLICY IF EXISTS "Authenticated users can create orders" ON public.orders; CREATE POLICY "Authenticated users can create orders" ON public.orders FOR INSERT WITH CHECK (auth.role() = 'authenticated'); -- Users editam seus próprios pedidos +DROP POLICY IF EXISTS "Users can update own orders" ON public.orders; CREATE POLICY "Users can update own orders" ON public.orders FOR UPDATE USING ( @@ -241,6 +265,7 @@ CREATE POLICY "Users can update own orders" ALTER TABLE public.order_items ENABLE ROW LEVEL SECURITY; -- Mesma lógica dos orders +DROP POLICY IF EXISTS "Users can view own order items" ON public.order_items; CREATE POLICY "Users can view own order items" ON public.order_items FOR SELECT USING ( @@ -255,6 +280,7 @@ CREATE POLICY "Users can view own order items" ) ); +DROP POLICY IF EXISTS "Users can manage own order items" ON public.order_items; CREATE POLICY "Users can manage own order items" ON public.order_items FOR ALL USING ( @@ -272,11 +298,13 @@ CREATE POLICY "Users can manage own order items" ALTER TABLE public.bitrix_clients ENABLE ROW LEVEL SECURITY; -- Authenticated users podem ver clientes +DROP POLICY IF EXISTS "Authenticated users can view clients" ON public.bitrix_clients; CREATE POLICY "Authenticated users can view clients" ON public.bitrix_clients FOR SELECT USING (auth.role() = 'authenticated'); -- Admins e managers gerenciam clientes +DROP POLICY IF EXISTS "Admins can manage clients" ON public.bitrix_clients; CREATE POLICY "Admins can manage clients" ON public.bitrix_clients FOR ALL USING (public.is_manager_or_admin()); @@ -288,11 +316,13 @@ CREATE POLICY "Admins can manage clients" ALTER TABLE public.mockup_generation_jobs ENABLE ROW LEVEL SECURITY; -- Users veem seus próprios jobs +DROP POLICY IF EXISTS "Users can view own mockup jobs" ON public.mockup_generation_jobs; CREATE POLICY "Users can view own mockup jobs" ON public.mockup_generation_jobs FOR SELECT USING (user_id = auth.uid() OR public.is_manager_or_admin()); -- Users criam seus próprios jobs +DROP POLICY IF EXISTS "Authenticated users can create mockup jobs" ON public.mockup_generation_jobs; CREATE POLICY "Authenticated users can create mockup jobs" ON public.mockup_generation_jobs FOR INSERT WITH CHECK (auth.role() = 'authenticated'); @@ -304,11 +334,13 @@ CREATE POLICY "Authenticated users can create mockup jobs" ALTER TABLE public.generated_mockups ENABLE ROW LEVEL SECURITY; -- Users veem seus próprios mockups +DROP POLICY IF EXISTS "Users can view own mockups" ON public.generated_mockups; CREATE POLICY "Users can view own mockups" ON public.generated_mockups FOR SELECT USING (user_id = auth.uid() OR public.is_manager_or_admin()); -- Sistema cria mockups +DROP POLICY IF EXISTS "System can create mockups" ON public.generated_mockups; CREATE POLICY "System can create mockups" ON public.generated_mockups FOR INSERT WITH CHECK (auth.role() = 'authenticated'); @@ -320,16 +352,19 @@ CREATE POLICY "System can create mockups" ALTER TABLE public.notifications ENABLE ROW LEVEL SECURITY; -- Users veem apenas suas notificações +DROP POLICY IF EXISTS "Users can view own notifications" ON public.notifications; CREATE POLICY "Users can view own notifications" ON public.notifications FOR SELECT USING (user_id = auth.uid()); -- Users podem marcar como lidas +DROP POLICY IF EXISTS "Users can update own notifications" ON public.notifications; CREATE POLICY "Users can update own notifications" ON public.notifications FOR UPDATE USING (user_id = auth.uid()); -- Sistema pode criar notificações +DROP POLICY IF EXISTS "System can create notifications" ON public.notifications; CREATE POLICY "System can create notifications" ON public.notifications FOR INSERT WITH CHECK (auth.role() = 'authenticated'); @@ -343,27 +378,33 @@ ALTER TABLE public.product_views ENABLE ROW LEVEL SECURITY; ALTER TABLE public.search_queries ENABLE ROW LEVEL SECURITY; -- Qualquer um pode criar eventos de analytics +DROP POLICY IF EXISTS "Anyone can create analytics events" ON public.analytics_events; CREATE POLICY "Anyone can create analytics events" ON public.analytics_events FOR INSERT WITH CHECK (true); +DROP POLICY IF EXISTS "Anyone can create product views" ON public.product_views; CREATE POLICY "Anyone can create product views" ON public.product_views FOR INSERT WITH CHECK (true); +DROP POLICY IF EXISTS "Anyone can create search queries" ON public.search_queries; CREATE POLICY "Anyone can create search queries" ON public.search_queries FOR INSERT WITH CHECK (true); -- Apenas admins podem ver analytics +DROP POLICY IF EXISTS "Admins can view analytics" ON public.analytics_events; CREATE POLICY "Admins can view analytics" ON public.analytics_events FOR SELECT USING (public.is_admin()); +DROP POLICY IF EXISTS "Admins can view product views" ON public.product_views; CREATE POLICY "Admins can view product views" ON public.product_views FOR SELECT USING (public.is_admin()); +DROP POLICY IF EXISTS "Admins can view search queries" ON public.search_queries; CREATE POLICY "Admins can view search queries" ON public.search_queries FOR SELECT USING (public.is_admin()); @@ -376,11 +417,13 @@ ALTER TABLE public.user_favorites ENABLE ROW LEVEL SECURITY; ALTER TABLE public.product_comparisons ENABLE ROW LEVEL SECURITY; -- Users gerenciam seus próprios favoritos +DROP POLICY IF EXISTS "Users can manage own favorites" ON public.user_favorites; CREATE POLICY "Users can manage own favorites" ON public.user_favorites FOR ALL USING (user_id = auth.uid()); -- Users gerenciam suas próprias comparações +DROP POLICY IF EXISTS "Users can manage own comparisons" ON public.product_comparisons; CREATE POLICY "Users can manage own comparisons" ON public.product_comparisons FOR ALL USING (user_id = auth.uid()); @@ -395,18 +438,22 @@ ALTER TABLE public.audit_log ENABLE ROW LEVEL SECURITY; ALTER TABLE public.sync_jobs ENABLE ROW LEVEL SECURITY; -- Apenas admins +DROP POLICY IF EXISTS "Admins can manage feature flags" ON public.feature_flags; CREATE POLICY "Admins can manage feature flags" ON public.feature_flags FOR ALL USING (public.is_admin()); +DROP POLICY IF EXISTS "Admins can manage system settings" ON public.system_settings; CREATE POLICY "Admins can manage system settings" ON public.system_settings FOR ALL USING (public.is_admin()); +DROP POLICY IF EXISTS "Admins can view audit log" ON public.audit_log; CREATE POLICY "Admins can view audit log" ON public.audit_log FOR SELECT USING (public.is_admin()); +DROP POLICY IF EXISTS "Admins can view sync jobs" ON public.sync_jobs; CREATE POLICY "Admins can view sync jobs" ON public.sync_jobs FOR SELECT USING (public.is_admin()); @@ -418,11 +465,13 @@ CREATE POLICY "Admins can view sync jobs" ALTER TABLE public.personalization_techniques ENABLE ROW LEVEL SECURITY; -- Todos podem ver técnicas ativas +DROP POLICY IF EXISTS "Anyone can view active techniques" ON public.personalization_techniques; CREATE POLICY "Anyone can view active techniques" ON public.personalization_techniques FOR SELECT USING (is_active = true); -- Apenas admins editam +DROP POLICY IF EXISTS "Admins can manage techniques" ON public.personalization_techniques; CREATE POLICY "Admins can manage techniques" ON public.personalization_techniques FOR ALL USING (public.is_admin()); diff --git a/supabase/migrations/20250103_rls_policies.sql b/supabase/migrations/20250103_rls_policies.sql index fce578938..ec69fdfec 100644 --- a/supabase/migrations/20250103_rls_policies.sql +++ b/supabase/migrations/20250103_rls_policies.sql @@ -51,24 +51,29 @@ $$ LANGUAGE plpgsql SECURITY DEFINER; ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY; -- Users podem ver e editar apenas seu próprio perfil +DROP POLICY IF EXISTS "Users can view own profile" ON public.profiles; CREATE POLICY "Users can view own profile" ON public.profiles FOR SELECT USING (auth.uid() = id); +DROP POLICY IF EXISTS "Users can update own profile" ON public.profiles; CREATE POLICY "Users can update own profile" ON public.profiles FOR UPDATE USING (auth.uid() = id); -- Admins veem todos os perfis +DROP POLICY IF EXISTS "Admins can view all profiles" ON public.profiles; CREATE POLICY "Admins can view all profiles" ON public.profiles FOR SELECT USING (public.is_admin()); +DROP POLICY IF EXISTS "Admins can update all profiles" ON public.profiles; CREATE POLICY "Admins can update all profiles" ON public.profiles FOR UPDATE USING (public.is_admin()); -- Managers veem perfis do seu departamento +DROP POLICY IF EXISTS "Managers can view department profiles" ON public.profiles; CREATE POLICY "Managers can view department profiles" ON public.profiles FOR SELECT USING ( @@ -83,24 +88,29 @@ CREATE POLICY "Managers can view department profiles" ALTER TABLE public.products ENABLE ROW LEVEL SECURITY; -- Todos podem ver produtos ativos +DROP POLICY IF EXISTS "Anyone can view active products" ON public.products; CREATE POLICY "Anyone can view active products" ON public.products FOR SELECT USING (is_active = true); -- Admins e managers podem ver todos os produtos +DROP POLICY IF EXISTS "Admins can view all products" ON public.products; CREATE POLICY "Admins can view all products" ON public.products FOR SELECT USING (public.is_manager_or_admin()); -- Apenas admins podem criar/editar produtos +DROP POLICY IF EXISTS "Admins can insert products" ON public.products; CREATE POLICY "Admins can insert products" ON public.products FOR INSERT WITH CHECK (public.is_admin()); +DROP POLICY IF EXISTS "Admins can update products" ON public.products; CREATE POLICY "Admins can update products" ON public.products FOR UPDATE USING (public.is_admin()); +DROP POLICY IF EXISTS "Admins can delete products" ON public.products; CREATE POLICY "Admins can delete products" ON public.products FOR DELETE USING (public.is_admin()); @@ -112,11 +122,13 @@ CREATE POLICY "Admins can delete products" ALTER TABLE public.categories ENABLE ROW LEVEL SECURITY; -- Todos podem ver categorias ativas +DROP POLICY IF EXISTS "Anyone can view active categories" ON public.categories; CREATE POLICY "Anyone can view active categories" ON public.categories FOR SELECT USING (is_active = true); -- Admins gerenciam categorias +DROP POLICY IF EXISTS "Admins can manage categories" ON public.categories; CREATE POLICY "Admins can manage categories" ON public.categories FOR ALL USING (public.is_admin()); @@ -128,11 +140,13 @@ CREATE POLICY "Admins can manage categories" ALTER TABLE public.suppliers ENABLE ROW LEVEL SECURITY; -- Authenticated users podem ver fornecedores ativos +DROP POLICY IF EXISTS "Authenticated users can view active suppliers" ON public.suppliers; CREATE POLICY "Authenticated users can view active suppliers" ON public.suppliers FOR SELECT USING (is_active = true AND auth.role() = 'authenticated'); -- Admins gerenciam fornecedores +DROP POLICY IF EXISTS "Admins can manage suppliers" ON public.suppliers; CREATE POLICY "Admins can manage suppliers" ON public.suppliers FOR ALL USING (public.is_admin()); @@ -144,6 +158,7 @@ CREATE POLICY "Admins can manage suppliers" ALTER TABLE public.quotes ENABLE ROW LEVEL SECURITY; -- Users veem orçamentos que criaram ou foram atribuídos +DROP POLICY IF EXISTS "Users can view own quotes" ON public.quotes; CREATE POLICY "Users can view own quotes" ON public.quotes FOR SELECT USING ( @@ -153,11 +168,13 @@ CREATE POLICY "Users can view own quotes" ); -- Users podem criar orçamentos +DROP POLICY IF EXISTS "Authenticated users can create quotes" ON public.quotes; CREATE POLICY "Authenticated users can create quotes" ON public.quotes FOR INSERT WITH CHECK (auth.role() = 'authenticated'); -- Users podem editar orçamentos que criaram +DROP POLICY IF EXISTS "Users can update own quotes" ON public.quotes; CREATE POLICY "Users can update own quotes" ON public.quotes FOR UPDATE USING ( @@ -166,11 +183,13 @@ CREATE POLICY "Users can update own quotes" ); -- Apenas admins podem deletar +DROP POLICY IF EXISTS "Admins can delete quotes" ON public.quotes; CREATE POLICY "Admins can delete quotes" ON public.quotes FOR DELETE USING (public.is_admin()); -- Aprovação pública (via token) +DROP POLICY IF EXISTS "Public can view quotes with valid token" ON public.quotes; CREATE POLICY "Public can view quotes with valid token" ON public.quotes FOR SELECT USING (approval_token IS NOT NULL); @@ -182,6 +201,7 @@ CREATE POLICY "Public can view quotes with valid token" ALTER TABLE public.quote_items ENABLE ROW LEVEL SECURITY; -- Mesma lógica das quotes (via quote_id) +DROP POLICY IF EXISTS "Users can view own quote items" ON public.quote_items; CREATE POLICY "Users can view own quote items" ON public.quote_items FOR SELECT USING ( @@ -196,6 +216,7 @@ CREATE POLICY "Users can view own quote items" ) ); +DROP POLICY IF EXISTS "Users can manage own quote items" ON public.quote_items; CREATE POLICY "Users can manage own quote items" ON public.quote_items FOR ALL USING ( @@ -213,6 +234,7 @@ CREATE POLICY "Users can manage own quote items" ALTER TABLE public.orders ENABLE ROW LEVEL SECURITY; -- Users veem pedidos que criaram ou foram atribuídos +DROP POLICY IF EXISTS "Users can view own orders" ON public.orders; CREATE POLICY "Users can view own orders" ON public.orders FOR SELECT USING ( @@ -222,11 +244,13 @@ CREATE POLICY "Users can view own orders" ); -- Apenas authenticated podem criar +DROP POLICY IF EXISTS "Authenticated users can create orders" ON public.orders; CREATE POLICY "Authenticated users can create orders" ON public.orders FOR INSERT WITH CHECK (auth.role() = 'authenticated'); -- Users editam seus próprios pedidos +DROP POLICY IF EXISTS "Users can update own orders" ON public.orders; CREATE POLICY "Users can update own orders" ON public.orders FOR UPDATE USING ( @@ -241,6 +265,7 @@ CREATE POLICY "Users can update own orders" ALTER TABLE public.order_items ENABLE ROW LEVEL SECURITY; -- Mesma lógica dos orders +DROP POLICY IF EXISTS "Users can view own order items" ON public.order_items; CREATE POLICY "Users can view own order items" ON public.order_items FOR SELECT USING ( @@ -255,6 +280,7 @@ CREATE POLICY "Users can view own order items" ) ); +DROP POLICY IF EXISTS "Users can manage own order items" ON public.order_items; CREATE POLICY "Users can manage own order items" ON public.order_items FOR ALL USING ( @@ -272,11 +298,13 @@ CREATE POLICY "Users can manage own order items" ALTER TABLE public.bitrix_clients ENABLE ROW LEVEL SECURITY; -- Authenticated users podem ver clientes +DROP POLICY IF EXISTS "Authenticated users can view clients" ON public.bitrix_clients; CREATE POLICY "Authenticated users can view clients" ON public.bitrix_clients FOR SELECT USING (auth.role() = 'authenticated'); -- Admins e managers gerenciam clientes +DROP POLICY IF EXISTS "Admins can manage clients" ON public.bitrix_clients; CREATE POLICY "Admins can manage clients" ON public.bitrix_clients FOR ALL USING (public.is_manager_or_admin()); @@ -288,11 +316,13 @@ CREATE POLICY "Admins can manage clients" ALTER TABLE public.mockup_generation_jobs ENABLE ROW LEVEL SECURITY; -- Users veem seus próprios jobs +DROP POLICY IF EXISTS "Users can view own mockup jobs" ON public.mockup_generation_jobs; CREATE POLICY "Users can view own mockup jobs" ON public.mockup_generation_jobs FOR SELECT USING (user_id = auth.uid() OR public.is_manager_or_admin()); -- Users criam seus próprios jobs +DROP POLICY IF EXISTS "Authenticated users can create mockup jobs" ON public.mockup_generation_jobs; CREATE POLICY "Authenticated users can create mockup jobs" ON public.mockup_generation_jobs FOR INSERT WITH CHECK (auth.role() = 'authenticated'); @@ -304,11 +334,13 @@ CREATE POLICY "Authenticated users can create mockup jobs" ALTER TABLE public.generated_mockups ENABLE ROW LEVEL SECURITY; -- Users veem seus próprios mockups +DROP POLICY IF EXISTS "Users can view own mockups" ON public.generated_mockups; CREATE POLICY "Users can view own mockups" ON public.generated_mockups FOR SELECT USING (user_id = auth.uid() OR public.is_manager_or_admin()); -- Sistema cria mockups +DROP POLICY IF EXISTS "System can create mockups" ON public.generated_mockups; CREATE POLICY "System can create mockups" ON public.generated_mockups FOR INSERT WITH CHECK (auth.role() = 'authenticated'); @@ -322,16 +354,19 @@ ALTER TABLE public.point_transactions ENABLE ROW LEVEL SECURITY; ALTER TABLE public.user_achievements ENABLE ROW LEVEL SECURITY; -- Users veem seus próprios pontos +DROP POLICY IF EXISTS "Users can view own points" ON public.user_points; CREATE POLICY "Users can view own points" ON public.user_points FOR SELECT USING (user_id = auth.uid() OR public.is_admin()); -- Users veem suas próprias transações +DROP POLICY IF EXISTS "Users can view own transactions" ON public.point_transactions; CREATE POLICY "Users can view own transactions" ON public.point_transactions FOR SELECT USING (user_id = auth.uid() OR public.is_admin()); -- Users veem seus próprios achievements +DROP POLICY IF EXISTS "Users can view own achievements" ON public.user_achievements; CREATE POLICY "Users can view own achievements" ON public.user_achievements FOR SELECT USING (user_id = auth.uid() OR public.is_admin()); @@ -339,6 +374,7 @@ CREATE POLICY "Users can view own achievements" -- Achievements públicos ALTER TABLE public.achievements ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Anyone can view achievements" ON public.achievements; CREATE POLICY "Anyone can view achievements" ON public.achievements FOR SELECT USING (is_active = true); @@ -346,6 +382,7 @@ CREATE POLICY "Anyone can view achievements" -- Rewards ALTER TABLE public.rewards ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Authenticated users can view rewards" ON public.rewards; CREATE POLICY "Authenticated users can view rewards" ON public.rewards FOR SELECT USING (is_active = true AND auth.role() = 'authenticated'); @@ -357,16 +394,19 @@ CREATE POLICY "Authenticated users can view rewards" ALTER TABLE public.notifications ENABLE ROW LEVEL SECURITY; -- Users veem apenas suas notificações +DROP POLICY IF EXISTS "Users can view own notifications" ON public.notifications; CREATE POLICY "Users can view own notifications" ON public.notifications FOR SELECT USING (user_id = auth.uid()); -- Users podem marcar como lidas +DROP POLICY IF EXISTS "Users can update own notifications" ON public.notifications; CREATE POLICY "Users can update own notifications" ON public.notifications FOR UPDATE USING (user_id = auth.uid()); -- Sistema pode criar notificações +DROP POLICY IF EXISTS "System can create notifications" ON public.notifications; CREATE POLICY "System can create notifications" ON public.notifications FOR INSERT WITH CHECK (auth.role() = 'authenticated'); @@ -380,27 +420,33 @@ ALTER TABLE public.product_views ENABLE ROW LEVEL SECURITY; ALTER TABLE public.search_queries ENABLE ROW LEVEL SECURITY; -- Qualquer um pode criar eventos de analytics +DROP POLICY IF EXISTS "Anyone can create analytics events" ON public.analytics_events; CREATE POLICY "Anyone can create analytics events" ON public.analytics_events FOR INSERT WITH CHECK (true); +DROP POLICY IF EXISTS "Anyone can create product views" ON public.product_views; CREATE POLICY "Anyone can create product views" ON public.product_views FOR INSERT WITH CHECK (true); +DROP POLICY IF EXISTS "Anyone can create search queries" ON public.search_queries; CREATE POLICY "Anyone can create search queries" ON public.search_queries FOR INSERT WITH CHECK (true); -- Apenas admins podem ver analytics +DROP POLICY IF EXISTS "Admins can view analytics" ON public.analytics_events; CREATE POLICY "Admins can view analytics" ON public.analytics_events FOR SELECT USING (public.is_admin()); +DROP POLICY IF EXISTS "Admins can view product views" ON public.product_views; CREATE POLICY "Admins can view product views" ON public.product_views FOR SELECT USING (public.is_admin()); +DROP POLICY IF EXISTS "Admins can view search queries" ON public.search_queries; CREATE POLICY "Admins can view search queries" ON public.search_queries FOR SELECT USING (public.is_admin()); @@ -413,11 +459,13 @@ ALTER TABLE public.user_favorites ENABLE ROW LEVEL SECURITY; ALTER TABLE public.product_comparisons ENABLE ROW LEVEL SECURITY; -- Users gerenciam seus próprios favoritos +DROP POLICY IF EXISTS "Users can manage own favorites" ON public.user_favorites; CREATE POLICY "Users can manage own favorites" ON public.user_favorites FOR ALL USING (user_id = auth.uid()); -- Users gerenciam suas próprias comparações +DROP POLICY IF EXISTS "Users can manage own comparisons" ON public.product_comparisons; CREATE POLICY "Users can manage own comparisons" ON public.product_comparisons FOR ALL USING (user_id = auth.uid()); @@ -432,18 +480,22 @@ ALTER TABLE public.audit_log ENABLE ROW LEVEL SECURITY; ALTER TABLE public.sync_jobs ENABLE ROW LEVEL SECURITY; -- Apenas admins +DROP POLICY IF EXISTS "Admins can manage feature flags" ON public.feature_flags; CREATE POLICY "Admins can manage feature flags" ON public.feature_flags FOR ALL USING (public.is_admin()); +DROP POLICY IF EXISTS "Admins can manage system settings" ON public.system_settings; CREATE POLICY "Admins can manage system settings" ON public.system_settings FOR ALL USING (public.is_admin()); +DROP POLICY IF EXISTS "Admins can view audit log" ON public.audit_log; CREATE POLICY "Admins can view audit log" ON public.audit_log FOR SELECT USING (public.is_admin()); +DROP POLICY IF EXISTS "Admins can view sync jobs" ON public.sync_jobs; CREATE POLICY "Admins can view sync jobs" ON public.sync_jobs FOR SELECT USING (public.is_admin()); @@ -455,11 +507,13 @@ CREATE POLICY "Admins can view sync jobs" ALTER TABLE public.personalization_techniques ENABLE ROW LEVEL SECURITY; -- Todos podem ver técnicas ativas +DROP POLICY IF EXISTS "Anyone can view active techniques" ON public.personalization_techniques; CREATE POLICY "Anyone can view active techniques" ON public.personalization_techniques FOR SELECT USING (is_active = true); -- Apenas admins editam +DROP POLICY IF EXISTS "Admins can manage techniques" ON public.personalization_techniques; CREATE POLICY "Admins can manage techniques" ON public.personalization_techniques FOR ALL USING (public.is_admin()); diff --git a/supabase/migrations/20251214183243_14916945-c09e-42a0-bdf1-8972c41f9210.sql b/supabase/migrations/20251214183243_14916945-c09e-42a0-bdf1-8972c41f9210.sql index 9605d93e7..9324c6393 100644 --- a/supabase/migrations/20251214183243_14916945-c09e-42a0-bdf1-8972c41f9210.sql +++ b/supabase/migrations/20251214183243_14916945-c09e-42a0-bdf1-8972c41f9210.sql @@ -1,8 +1,11 @@ -- Create app_role enum for user roles +DO $$ BEGIN CREATE TYPE public.app_role AS ENUM ('admin', 'vendedor'); +EXCEPTION WHEN duplicate_object THEN NULL; +END $$; -- Create profiles table for user information -CREATE TABLE public.profiles ( +CREATE TABLE IF NOT EXISTS public.profiles ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL UNIQUE REFERENCES auth.users(id) ON DELETE CASCADE, full_name TEXT, @@ -13,7 +16,7 @@ CREATE TABLE public.profiles ( ); -- Create user_roles table (separate from profiles for security) -CREATE TABLE public.user_roles ( +CREATE TABLE IF NOT EXISTS public.user_roles ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE, role app_role NOT NULL DEFAULT 'vendedor', @@ -56,35 +59,43 @@ AS $$ $$; -- Profiles RLS policies +DROP POLICY IF EXISTS "Users can view their own profile" ON public.profiles; CREATE POLICY "Users can view their own profile" ON public.profiles FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can update their own profile" ON public.profiles; CREATE POLICY "Users can update their own profile" ON public.profiles FOR UPDATE USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can insert their own profile" ON public.profiles; CREATE POLICY "Users can insert their own profile" ON public.profiles FOR INSERT WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Admins can view all profiles" ON public.profiles; CREATE POLICY "Admins can view all profiles" ON public.profiles FOR SELECT USING (public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Admins can update all profiles" ON public.profiles; CREATE POLICY "Admins can update all profiles" ON public.profiles FOR UPDATE USING (public.has_role(auth.uid(), 'admin')); -- User roles RLS policies +DROP POLICY IF EXISTS "Users can view their own role" ON public.user_roles; CREATE POLICY "Users can view their own role" ON public.user_roles FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Admins can view all roles" ON public.user_roles; CREATE POLICY "Admins can view all roles" ON public.user_roles FOR SELECT USING (public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Admins can manage roles" ON public.user_roles; CREATE POLICY "Admins can manage roles" ON public.user_roles FOR ALL USING (public.has_role(auth.uid(), 'admin')); @@ -110,6 +121,7 @@ END; $$; -- Trigger to create profile and assign role on signup +DROP TRIGGER IF EXISTS on_auth_user_created ON auth.users; CREATE TRIGGER on_auth_user_created AFTER INSERT ON auth.users FOR EACH ROW EXECUTE FUNCTION public.handle_new_user(); @@ -124,6 +136,7 @@ END; $$ LANGUAGE plpgsql SET search_path = public; -- Trigger for automatic timestamp updates +DROP TRIGGER IF EXISTS update_profiles_updated_at ON public.profiles; CREATE TRIGGER update_profiles_updated_at BEFORE UPDATE ON public.profiles FOR EACH ROW diff --git a/supabase/migrations/20251214184441_801b0aa8-e997-49c2-9e4d-ea0f4836a717.sql b/supabase/migrations/20251214184441_801b0aa8-e997-49c2-9e4d-ea0f4836a717.sql index 5f134d091..6d11616d2 100644 --- a/supabase/migrations/20251214184441_801b0aa8-e997-49c2-9e4d-ea0f4836a717.sql +++ b/supabase/migrations/20251214184441_801b0aa8-e997-49c2-9e4d-ea0f4836a717.sql @@ -3,6 +3,7 @@ INSERT INTO storage.buckets (id, name, public) VALUES ('avatars', 'avatars', true); -- Allow authenticated users to upload their own avatar +DROP POLICY IF EXISTS "Users can upload their own avatar" ON storage.objects; CREATE POLICY "Users can upload their own avatar" ON storage.objects FOR INSERT @@ -13,6 +14,7 @@ WITH CHECK ( ); -- Allow authenticated users to update their own avatar +DROP POLICY IF EXISTS "Users can update their own avatar" ON storage.objects; CREATE POLICY "Users can update their own avatar" ON storage.objects FOR UPDATE @@ -23,6 +25,7 @@ USING ( ); -- Allow authenticated users to delete their own avatar +DROP POLICY IF EXISTS "Users can delete their own avatar" ON storage.objects; CREATE POLICY "Users can delete their own avatar" ON storage.objects FOR DELETE @@ -33,6 +36,7 @@ USING ( ); -- Allow public read access to avatars +DROP POLICY IF EXISTS "Public can view avatars" ON storage.objects; CREATE POLICY "Public can view avatars" ON storage.objects FOR SELECT diff --git a/supabase/migrations/20251214185703_ccfe43ae-d38d-40bd-a327-56e2c378b26e.sql b/supabase/migrations/20251214185703_ccfe43ae-d38d-40bd-a327-56e2c378b26e.sql index f6d7b0424..e201afcbf 100644 --- a/supabase/migrations/20251214185703_ccfe43ae-d38d-40bd-a327-56e2c378b26e.sql +++ b/supabase/migrations/20251214185703_ccfe43ae-d38d-40bd-a327-56e2c378b26e.sql @@ -1,5 +1,5 @@ --- Create table for Bitrix24 clients -CREATE TABLE public.bitrix_clients ( +-- CREATE TABLE IF NOT EXISTS for Bitrix24 clients +CREATE TABLE IF NOT EXISTS public.bitrix_clients ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, bitrix_id TEXT NOT NULL UNIQUE, name TEXT NOT NULL, @@ -18,8 +18,8 @@ CREATE TABLE public.bitrix_clients ( updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); --- Create table for Bitrix24 deals (purchase history) -CREATE TABLE public.bitrix_deals ( +-- CREATE TABLE IF NOT EXISTS for Bitrix24 deals (purchase history) +CREATE TABLE IF NOT EXISTS public.bitrix_deals ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, bitrix_id TEXT NOT NULL UNIQUE, bitrix_client_id TEXT NOT NULL, @@ -33,8 +33,8 @@ CREATE TABLE public.bitrix_deals ( created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); --- Create table for sync history logs -CREATE TABLE public.bitrix_sync_logs ( +-- CREATE TABLE IF NOT EXISTS for sync history logs +CREATE TABLE IF NOT EXISTS public.bitrix_sync_logs ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, synced_by UUID REFERENCES auth.users(id), clients_synced INTEGER DEFAULT 0, @@ -45,10 +45,10 @@ CREATE TABLE public.bitrix_sync_logs ( completed_at TIMESTAMPTZ ); --- Create index for faster lookups -CREATE INDEX idx_bitrix_clients_bitrix_id ON public.bitrix_clients(bitrix_id); -CREATE INDEX idx_bitrix_deals_client_id ON public.bitrix_deals(bitrix_client_id); -CREATE INDEX idx_bitrix_sync_logs_synced_by ON public.bitrix_sync_logs(synced_by); +-- CREATE INDEX IF NOT EXISTS for faster lookups +CREATE INDEX IF NOT EXISTS idx_bitrix_clients_bitrix_id ON public.bitrix_clients(bitrix_id); +CREATE INDEX IF NOT EXISTS idx_bitrix_deals_client_id ON public.bitrix_deals(bitrix_client_id); +CREATE INDEX IF NOT EXISTS idx_bitrix_sync_logs_synced_by ON public.bitrix_sync_logs(synced_by); -- Enable RLS ALTER TABLE public.bitrix_clients ENABLE ROW LEVEL SECURITY; @@ -56,38 +56,45 @@ ALTER TABLE public.bitrix_deals ENABLE ROW LEVEL SECURITY; ALTER TABLE public.bitrix_sync_logs ENABLE ROW LEVEL SECURITY; -- RLS Policies - All authenticated users can read +DROP POLICY IF EXISTS "Authenticated users can view clients" ON public.bitrix_clients; CREATE POLICY "Authenticated users can view clients" ON public.bitrix_clients FOR SELECT TO authenticated USING (true); +DROP POLICY IF EXISTS "Authenticated users can view deals" ON public.bitrix_deals; CREATE POLICY "Authenticated users can view deals" ON public.bitrix_deals FOR SELECT TO authenticated USING (true); +DROP POLICY IF EXISTS "Authenticated users can view sync logs" ON public.bitrix_sync_logs; CREATE POLICY "Authenticated users can view sync logs" ON public.bitrix_sync_logs FOR SELECT TO authenticated USING (true); -- Only admins or service role can insert/update (via edge function) +DROP POLICY IF EXISTS "Service can manage clients" ON public.bitrix_clients; CREATE POLICY "Service can manage clients" ON public.bitrix_clients FOR ALL USING (true) WITH CHECK (true); +DROP POLICY IF EXISTS "Service can manage deals" ON public.bitrix_deals; CREATE POLICY "Service can manage deals" ON public.bitrix_deals FOR ALL USING (true) WITH CHECK (true); +DROP POLICY IF EXISTS "Service can manage sync logs" ON public.bitrix_sync_logs; CREATE POLICY "Service can manage sync logs" ON public.bitrix_sync_logs FOR ALL USING (true) WITH CHECK (true); -- Update trigger for clients +DROP TRIGGER IF EXISTS update_bitrix_clients_updated_at ON public.bitrix_clients; CREATE TRIGGER update_bitrix_clients_updated_at BEFORE UPDATE ON public.bitrix_clients FOR EACH ROW diff --git a/supabase/migrations/20251214194907_a5a0f44d-0504-411d-842a-cb07597b6ed5.sql b/supabase/migrations/20251214194907_a5a0f44d-0504-411d-842a-cb07597b6ed5.sql index 168bc6aca..4be98a84e 100644 --- a/supabase/migrations/20251214194907_a5a0f44d-0504-411d-842a-cb07597b6ed5.sql +++ b/supabase/migrations/20251214194907_a5a0f44d-0504-411d-842a-cb07597b6ed5.sql @@ -1,8 +1,11 @@ -- Create enum for quote status +DO $$ BEGIN CREATE TYPE public.quote_status AS ENUM ('draft', 'pending', 'sent', 'approved', 'rejected', 'expired'); +EXCEPTION WHEN duplicate_object THEN NULL; +END $$; -- Create personalization techniques table -CREATE TABLE public.personalization_techniques ( +CREATE TABLE IF NOT EXISTS public.personalization_techniques ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, name TEXT NOT NULL, description TEXT, @@ -17,7 +20,7 @@ CREATE TABLE public.personalization_techniques ( ); -- Create quotes table -CREATE TABLE public.quotes ( +CREATE TABLE IF NOT EXISTS public.quotes ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, quote_number TEXT NOT NULL UNIQUE, client_id UUID REFERENCES public.bitrix_clients(id) ON DELETE SET NULL, @@ -39,7 +42,7 @@ CREATE TABLE public.quotes ( ); -- Create quote items table -CREATE TABLE public.quote_items ( +CREATE TABLE IF NOT EXISTS public.quote_items ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, quote_id UUID NOT NULL REFERENCES public.quotes(id) ON DELETE CASCADE, product_id TEXT, @@ -58,7 +61,7 @@ CREATE TABLE public.quote_items ( ); -- Create quote item personalizations (link items to techniques) -CREATE TABLE public.quote_item_personalizations ( +CREATE TABLE IF NOT EXISTS public.quote_item_personalizations ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, quote_item_id UUID NOT NULL REFERENCES public.quote_items(id) ON DELETE CASCADE, technique_id UUID NOT NULL REFERENCES public.personalization_techniques(id) ON DELETE RESTRICT, @@ -72,7 +75,7 @@ CREATE TABLE public.quote_item_personalizations ( created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now() ); --- Create function to generate quote number +-- CREATE OR REPLACE function to generate quote number CREATE OR REPLACE FUNCTION public.generate_quote_number() RETURNS TRIGGER AS $$ BEGIN @@ -81,10 +84,11 @@ BEGIN END; $$ LANGUAGE plpgsql SET search_path = public; --- Create sequence for quote numbers +-- CREATE SEQUENCE IF NOT EXISTS for quote numbers CREATE SEQUENCE IF NOT EXISTS quote_number_seq START 1; -- Create trigger for auto quote number +DROP TRIGGER IF EXISTS set_quote_number ON public.quotes; CREATE TRIGGER set_quote_number BEFORE INSERT ON public.quotes FOR EACH ROW @@ -92,18 +96,21 @@ CREATE TRIGGER set_quote_number EXECUTE FUNCTION public.generate_quote_number(); -- Create trigger for updated_at on quotes +DROP TRIGGER IF EXISTS update_quotes_updated_at ON public.quotes; CREATE TRIGGER update_quotes_updated_at BEFORE UPDATE ON public.quotes FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); -- Create trigger for updated_at on quote_items +DROP TRIGGER IF EXISTS update_quote_items_updated_at ON public.quote_items; CREATE TRIGGER update_quote_items_updated_at BEFORE UPDATE ON public.quote_items FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); -- Create trigger for updated_at on personalization_techniques +DROP TRIGGER IF EXISTS update_personalization_techniques_updated_at ON public.personalization_techniques; CREATE TRIGGER update_personalization_techniques_updated_at BEFORE UPDATE ON public.personalization_techniques FOR EACH ROW @@ -116,11 +123,13 @@ ALTER TABLE public.quote_items ENABLE ROW LEVEL SECURITY; ALTER TABLE public.quote_item_personalizations ENABLE ROW LEVEL SECURITY; -- RLS Policies for personalization_techniques (read by all authenticated, managed by admins) +DROP POLICY IF EXISTS "Authenticated users can view techniques" ON public.personalization_techniques; CREATE POLICY "Authenticated users can view techniques" ON public.personalization_techniques FOR SELECT TO authenticated USING (true); +DROP POLICY IF EXISTS "Admins can manage techniques" ON public.personalization_techniques; CREATE POLICY "Admins can manage techniques" ON public.personalization_techniques FOR ALL TO authenticated @@ -128,27 +137,32 @@ CREATE POLICY "Admins can manage techniques" WITH CHECK (public.has_role(auth.uid(), 'admin')); -- RLS Policies for quotes +DROP POLICY IF EXISTS "Sellers can view their own quotes" ON public.quotes; CREATE POLICY "Sellers can view their own quotes" ON public.quotes FOR SELECT TO authenticated USING (seller_id = auth.uid() OR public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Sellers can create quotes" ON public.quotes; CREATE POLICY "Sellers can create quotes" ON public.quotes FOR INSERT TO authenticated WITH CHECK (seller_id = auth.uid()); +DROP POLICY IF EXISTS "Sellers can update their own quotes" ON public.quotes; CREATE POLICY "Sellers can update their own quotes" ON public.quotes FOR UPDATE TO authenticated USING (seller_id = auth.uid() OR public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Sellers can delete their draft quotes" ON public.quotes; CREATE POLICY "Sellers can delete their draft quotes" ON public.quotes FOR DELETE TO authenticated USING ((seller_id = auth.uid() AND status = 'draft') OR public.has_role(auth.uid(), 'admin')); -- RLS Policies for quote_items (inherit from quote access) +DROP POLICY IF EXISTS "Users can view items of accessible quotes" ON public.quote_items; CREATE POLICY "Users can view items of accessible quotes" ON public.quote_items FOR SELECT TO authenticated @@ -160,6 +174,7 @@ CREATE POLICY "Users can view items of accessible quotes" ) ); +DROP POLICY IF EXISTS "Users can manage items of their quotes" ON public.quote_items; CREATE POLICY "Users can manage items of their quotes" ON public.quote_items FOR ALL TO authenticated @@ -179,6 +194,7 @@ CREATE POLICY "Users can manage items of their quotes" ); -- RLS Policies for quote_item_personalizations +DROP POLICY IF EXISTS "Users can view personalizations of accessible items" ON public.quote_item_personalizations; CREATE POLICY "Users can view personalizations of accessible items" ON public.quote_item_personalizations FOR SELECT TO authenticated @@ -191,6 +207,7 @@ CREATE POLICY "Users can view personalizations of accessible items" ) ); +DROP POLICY IF EXISTS "Users can manage personalizations of their items" ON public.quote_item_personalizations; CREATE POLICY "Users can manage personalizations of their items" ON public.quote_item_personalizations FOR ALL TO authenticated @@ -212,10 +229,10 @@ CREATE POLICY "Users can manage personalizations of their items" ); -- Create indexes for performance -CREATE INDEX idx_quotes_client_id ON public.quotes(client_id); -CREATE INDEX idx_quotes_seller_id ON public.quotes(seller_id); -CREATE INDEX idx_quotes_status ON public.quotes(status); -CREATE INDEX idx_quotes_bitrix_deal_id ON public.quotes(bitrix_deal_id); -CREATE INDEX idx_quote_items_quote_id ON public.quote_items(quote_id); -CREATE INDEX idx_quote_item_personalizations_item_id ON public.quote_item_personalizations(quote_item_id); -CREATE INDEX idx_quote_item_personalizations_technique_id ON public.quote_item_personalizations(technique_id); \ No newline at end of file +CREATE INDEX IF NOT EXISTS idx_quotes_client_id ON public.quotes(client_id); +CREATE INDEX IF NOT EXISTS idx_quotes_seller_id ON public.quotes(seller_id); +CREATE INDEX IF NOT EXISTS idx_quotes_status ON public.quotes(status); +CREATE INDEX IF NOT EXISTS idx_quotes_bitrix_deal_id ON public.quotes(bitrix_deal_id); +CREATE INDEX IF NOT EXISTS idx_quote_items_quote_id ON public.quote_items(quote_id); +CREATE INDEX IF NOT EXISTS idx_quote_item_personalizations_item_id ON public.quote_item_personalizations(quote_item_id); +CREATE INDEX IF NOT EXISTS idx_quote_item_personalizations_technique_id ON public.quote_item_personalizations(technique_id); \ No newline at end of file diff --git a/supabase/migrations/20251214200524_1f519508-285c-4649-ba22-b40d67618e67.sql b/supabase/migrations/20251214200524_1f519508-285c-4649-ba22-b40d67618e67.sql index 2023d0301..16b473164 100644 --- a/supabase/migrations/20251214200524_1f519508-285c-4649-ba22-b40d67618e67.sql +++ b/supabase/migrations/20251214200524_1f519508-285c-4649-ba22-b40d67618e67.sql @@ -1,5 +1,5 @@ -- Create products table for synced products from external database -CREATE TABLE public.products ( +CREATE TABLE IF NOT EXISTS public.products ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, external_id TEXT UNIQUE, sku TEXT NOT NULL, @@ -33,7 +33,7 @@ CREATE TABLE public.products ( ); -- Create product sync logs table -CREATE TABLE public.product_sync_logs ( +CREATE TABLE IF NOT EXISTS public.product_sync_logs ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, status TEXT NOT NULL DEFAULT 'pending', products_received INTEGER DEFAULT 0, @@ -51,16 +51,19 @@ ALTER TABLE public.products ENABLE ROW LEVEL SECURITY; ALTER TABLE public.product_sync_logs ENABLE ROW LEVEL SECURITY; -- RLS Policies for products (readable by all authenticated, manageable by service/admins) +DROP POLICY IF EXISTS "Authenticated users can view products" ON public.products; CREATE POLICY "Authenticated users can view products" ON public.products FOR SELECT TO authenticated USING (is_active = true); +DROP POLICY IF EXISTS "Admins can view all products" ON public.products; CREATE POLICY "Admins can view all products" ON public.products FOR SELECT TO authenticated USING (public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Service can manage products" ON public.products; CREATE POLICY "Service can manage products" ON public.products FOR ALL TO service_role @@ -68,11 +71,13 @@ CREATE POLICY "Service can manage products" WITH CHECK (true); -- RLS Policies for sync logs +DROP POLICY IF EXISTS "Admins can view sync logs" ON public.product_sync_logs; CREATE POLICY "Admins can view sync logs" ON public.product_sync_logs FOR SELECT TO authenticated USING (public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Service can manage sync logs" ON public.product_sync_logs; CREATE POLICY "Service can manage sync logs" ON public.product_sync_logs FOR ALL TO service_role @@ -80,15 +85,16 @@ CREATE POLICY "Service can manage sync logs" WITH CHECK (true); -- Indexes for performance -CREATE INDEX idx_products_sku ON public.products(sku); -CREATE INDEX idx_products_external_id ON public.products(external_id); -CREATE INDEX idx_products_category_id ON public.products(category_id); -CREATE INDEX idx_products_supplier_id ON public.products(supplier_id); -CREATE INDEX idx_products_is_active ON public.products(is_active); -CREATE INDEX idx_products_stock_status ON public.products(stock_status); -CREATE INDEX idx_products_featured ON public.products(featured); +CREATE INDEX IF NOT EXISTS idx_products_sku ON public.products(sku); +CREATE INDEX IF NOT EXISTS idx_products_external_id ON public.products(external_id); +CREATE INDEX IF NOT EXISTS idx_products_category_id ON public.products(category_id); +CREATE INDEX IF NOT EXISTS idx_products_supplier_id ON public.products(supplier_id); +CREATE INDEX IF NOT EXISTS idx_products_is_active ON public.products(is_active); +CREATE INDEX IF NOT EXISTS idx_products_stock_status ON public.products(stock_status); +CREATE INDEX IF NOT EXISTS idx_products_featured ON public.products(featured); -- Trigger for updated_at +DROP TRIGGER IF EXISTS update_products_updated_at ON public.products; CREATE TRIGGER update_products_updated_at BEFORE UPDATE ON public.products FOR EACH ROW diff --git a/supabase/migrations/20251214201605_1110a792-a1c9-43b9-9832-4cd68610e0ab.sql b/supabase/migrations/20251214201605_1110a792-a1c9-43b9-9832-4cd68610e0ab.sql index 79ff5a838..1734604f4 100644 --- a/supabase/migrations/20251214201605_1110a792-a1c9-43b9-9832-4cd68610e0ab.sql +++ b/supabase/migrations/20251214201605_1110a792-a1c9-43b9-9832-4cd68610e0ab.sql @@ -1,5 +1,5 @@ -- Create personalization locations table -CREATE TABLE public.personalization_locations ( +CREATE TABLE IF NOT EXISTS public.personalization_locations ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, product_type TEXT NOT NULL, location_name TEXT NOT NULL, @@ -9,7 +9,7 @@ CREATE TABLE public.personalization_locations ( ); -- Create personalization sizes table -CREATE TABLE public.personalization_sizes ( +CREATE TABLE IF NOT EXISTS public.personalization_sizes ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, technique_id UUID REFERENCES public.personalization_techniques(id) ON DELETE CASCADE, technique_code TEXT, @@ -27,11 +27,13 @@ ALTER TABLE public.personalization_locations ENABLE ROW LEVEL SECURITY; ALTER TABLE public.personalization_sizes ENABLE ROW LEVEL SECURITY; -- RLS Policies for locations +DROP POLICY IF EXISTS "Authenticated users can view locations" ON public.personalization_locations; CREATE POLICY "Authenticated users can view locations" ON public.personalization_locations FOR SELECT TO authenticated USING (true); +DROP POLICY IF EXISTS "Admins can manage locations" ON public.personalization_locations; CREATE POLICY "Admins can manage locations" ON public.personalization_locations FOR ALL TO authenticated @@ -39,11 +41,13 @@ CREATE POLICY "Admins can manage locations" WITH CHECK (public.has_role(auth.uid(), 'admin')); -- RLS Policies for sizes +DROP POLICY IF EXISTS "Authenticated users can view sizes" ON public.personalization_sizes; CREATE POLICY "Authenticated users can view sizes" ON public.personalization_sizes FOR SELECT TO authenticated USING (true); +DROP POLICY IF EXISTS "Admins can manage sizes" ON public.personalization_sizes; CREATE POLICY "Admins can manage sizes" ON public.personalization_sizes FOR ALL TO authenticated @@ -51,6 +55,6 @@ CREATE POLICY "Admins can manage sizes" WITH CHECK (public.has_role(auth.uid(), 'admin')); -- Indexes -CREATE INDEX idx_personalization_locations_product_type ON public.personalization_locations(product_type); -CREATE INDEX idx_personalization_sizes_technique_id ON public.personalization_sizes(technique_id); -CREATE INDEX idx_personalization_sizes_technique_code ON public.personalization_sizes(technique_code); \ No newline at end of file +CREATE INDEX IF NOT EXISTS idx_personalization_locations_product_type ON public.personalization_locations(product_type); +CREATE INDEX IF NOT EXISTS idx_personalization_sizes_technique_id ON public.personalization_sizes(technique_id); +CREATE INDEX IF NOT EXISTS idx_personalization_sizes_technique_code ON public.personalization_sizes(technique_code); \ No newline at end of file diff --git a/supabase/migrations/20251214202150_2537b013-3d76-49df-b2a9-1b345cc14878.sql b/supabase/migrations/20251214202150_2537b013-3d76-49df-b2a9-1b345cc14878.sql index cd32bc501..4a8750a75 100644 --- a/supabase/migrations/20251214202150_2537b013-3d76-49df-b2a9-1b345cc14878.sql +++ b/supabase/migrations/20251214202150_2537b013-3d76-49df-b2a9-1b345cc14878.sql @@ -1,5 +1,5 @@ -- Tabela de componentes por produto -CREATE TABLE public.product_components ( +CREATE TABLE IF NOT EXISTS public.product_components ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, product_id UUID REFERENCES public.products(id) ON DELETE CASCADE NOT NULL, component_name TEXT NOT NULL, @@ -14,7 +14,7 @@ CREATE TABLE public.product_components ( ); -- Tabela de localizações por componente -CREATE TABLE public.product_component_locations ( +CREATE TABLE IF NOT EXISTS public.product_component_locations ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, component_id UUID REFERENCES public.product_components(id) ON DELETE CASCADE NOT NULL, location_name TEXT NOT NULL, @@ -30,7 +30,7 @@ CREATE TABLE public.product_component_locations ( ); -- Tabela de técnicas disponíveis por localização -CREATE TABLE public.product_component_location_techniques ( +CREATE TABLE IF NOT EXISTS public.product_component_location_techniques ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, component_location_id UUID REFERENCES public.product_component_locations(id) ON DELETE CASCADE NOT NULL, technique_id UUID REFERENCES public.personalization_techniques(id) ON DELETE CASCADE NOT NULL, @@ -48,11 +48,13 @@ ALTER TABLE public.product_component_locations ENABLE ROW LEVEL SECURITY; ALTER TABLE public.product_component_location_techniques ENABLE ROW LEVEL SECURITY; -- RLS Policies para product_components +DROP POLICY IF EXISTS "Authenticated users can view components" ON public.product_components; CREATE POLICY "Authenticated users can view components" ON public.product_components FOR SELECT TO authenticated USING (true); +DROP POLICY IF EXISTS "Admins can manage components" ON public.product_components; CREATE POLICY "Admins can manage components" ON public.product_components FOR ALL TO authenticated @@ -60,11 +62,13 @@ CREATE POLICY "Admins can manage components" WITH CHECK (public.has_role(auth.uid(), 'admin')); -- RLS Policies para product_component_locations +DROP POLICY IF EXISTS "Authenticated users can view component locations" ON public.product_component_locations; CREATE POLICY "Authenticated users can view component locations" ON public.product_component_locations FOR SELECT TO authenticated USING (true); +DROP POLICY IF EXISTS "Admins can manage component locations" ON public.product_component_locations; CREATE POLICY "Admins can manage component locations" ON public.product_component_locations FOR ALL TO authenticated @@ -72,11 +76,13 @@ CREATE POLICY "Admins can manage component locations" WITH CHECK (public.has_role(auth.uid(), 'admin')); -- RLS Policies para product_component_location_techniques +DROP POLICY IF EXISTS "Authenticated users can view location techniques" ON public.product_component_location_techniques; CREATE POLICY "Authenticated users can view location techniques" ON public.product_component_location_techniques FOR SELECT TO authenticated USING (true); +DROP POLICY IF EXISTS "Admins can manage location techniques" ON public.product_component_location_techniques; CREATE POLICY "Admins can manage location techniques" ON public.product_component_location_techniques FOR ALL TO authenticated @@ -84,12 +90,13 @@ CREATE POLICY "Admins can manage location techniques" WITH CHECK (public.has_role(auth.uid(), 'admin')); -- Indexes para performance -CREATE INDEX idx_product_components_product_id ON public.product_components(product_id); -CREATE INDEX idx_product_component_locations_component_id ON public.product_component_locations(component_id); -CREATE INDEX idx_product_component_location_techniques_location_id ON public.product_component_location_techniques(component_location_id); -CREATE INDEX idx_product_component_location_techniques_technique_id ON public.product_component_location_techniques(technique_id); +CREATE INDEX IF NOT EXISTS idx_product_components_product_id ON public.product_components(product_id); +CREATE INDEX IF NOT EXISTS idx_product_component_locations_component_id ON public.product_component_locations(component_id); +CREATE INDEX IF NOT EXISTS idx_product_component_location_techniques_location_id ON public.product_component_location_techniques(component_location_id); +CREATE INDEX IF NOT EXISTS idx_product_component_location_techniques_technique_id ON public.product_component_location_techniques(technique_id); -- Trigger para updated_at +DROP TRIGGER IF EXISTS update_product_components_updated_at ON public.product_components; CREATE TRIGGER update_product_components_updated_at BEFORE UPDATE ON public.product_components FOR EACH ROW diff --git a/supabase/migrations/20251214204856_994071f7-c3cd-4ff1-8ca4-e81d480f4b82.sql b/supabase/migrations/20251214204856_994071f7-c3cd-4ff1-8ca4-e81d480f4b82.sql index 0a4878a9e..d31adaa3f 100644 --- a/supabase/migrations/20251214204856_994071f7-c3cd-4ff1-8ca4-e81d480f4b82.sql +++ b/supabase/migrations/20251214204856_994071f7-c3cd-4ff1-8ca4-e81d480f4b82.sql @@ -20,11 +20,13 @@ CREATE TABLE IF NOT EXISTS public.product_groups ( ALTER TABLE public.product_groups ENABLE ROW LEVEL SECURITY; -- RLS policies for product_groups +DROP POLICY IF EXISTS "Authenticated users can view groups" ON public.product_groups; CREATE POLICY "Authenticated users can view groups" ON public.product_groups FOR SELECT USING (true); +DROP POLICY IF EXISTS "Admins can manage groups" ON public.product_groups; CREATE POLICY "Admins can manage groups" ON public.product_groups FOR ALL @@ -44,11 +46,13 @@ CREATE TABLE IF NOT EXISTS public.product_group_members ( ALTER TABLE public.product_group_members ENABLE ROW LEVEL SECURITY; -- RLS policies for product_group_members +DROP POLICY IF EXISTS "Authenticated users can view group members" ON public.product_group_members; CREATE POLICY "Authenticated users can view group members" ON public.product_group_members FOR SELECT USING (true); +DROP POLICY IF EXISTS "Admins can manage group members" ON public.product_group_members; CREATE POLICY "Admins can manage group members" ON public.product_group_members FOR ALL @@ -71,11 +75,13 @@ CREATE TABLE IF NOT EXISTS public.product_group_components ( -- Enable RLS on product_group_components ALTER TABLE public.product_group_components ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Authenticated users can view group components" ON public.product_group_components; CREATE POLICY "Authenticated users can view group components" ON public.product_group_components FOR SELECT USING (true); +DROP POLICY IF EXISTS "Admins can manage group components" ON public.product_group_components; CREATE POLICY "Admins can manage group components" ON public.product_group_components FOR ALL @@ -100,11 +106,13 @@ CREATE TABLE IF NOT EXISTS public.product_group_locations ( -- Enable RLS on product_group_locations ALTER TABLE public.product_group_locations ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Authenticated users can view group locations" ON public.product_group_locations; CREATE POLICY "Authenticated users can view group locations" ON public.product_group_locations FOR SELECT USING (true); +DROP POLICY IF EXISTS "Admins can manage group locations" ON public.product_group_locations; CREATE POLICY "Admins can manage group locations" ON public.product_group_locations FOR ALL @@ -126,11 +134,13 @@ CREATE TABLE IF NOT EXISTS public.product_group_location_techniques ( -- Enable RLS on product_group_location_techniques ALTER TABLE public.product_group_location_techniques ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Authenticated users can view group location techniques" ON public.product_group_location_techniques; CREATE POLICY "Authenticated users can view group location techniques" ON public.product_group_location_techniques FOR SELECT USING (true); +DROP POLICY IF EXISTS "Admins can manage group location techniques" ON public.product_group_location_techniques; CREATE POLICY "Admins can manage group location techniques" ON public.product_group_location_techniques FOR ALL @@ -138,6 +148,7 @@ USING (has_role(auth.uid(), 'admin'::app_role)) WITH CHECK (has_role(auth.uid(), 'admin'::app_role)); -- Add trigger for updated_at on product_groups +DROP TRIGGER IF EXISTS update_product_groups_updated_at ON public.product_groups; CREATE TRIGGER update_product_groups_updated_at BEFORE UPDATE ON public.product_groups FOR EACH ROW diff --git a/supabase/migrations/20251214205410_4d7cb4a6-db5f-4ace-8844-aff6f8993e51.sql b/supabase/migrations/20251214205410_4d7cb4a6-db5f-4ace-8844-aff6f8993e51.sql index 89b908321..9a8485f87 100644 --- a/supabase/migrations/20251214205410_4d7cb4a6-db5f-4ace-8844-aff6f8993e51.sql +++ b/supabase/migrations/20251214205410_4d7cb4a6-db5f-4ace-8844-aff6f8993e51.sql @@ -4,12 +4,14 @@ VALUES ('personalization-images', 'personalization-images', true) ON CONFLICT (id) DO NOTHING; -- Allow authenticated users to view images +DROP POLICY IF EXISTS "Anyone can view personalization images" ON storage.objects; CREATE POLICY "Anyone can view personalization images" ON storage.objects FOR SELECT USING (bucket_id = 'personalization-images'); -- Allow admins to upload images +DROP POLICY IF EXISTS "Admins can upload personalization images" ON storage.objects; CREATE POLICY "Admins can upload personalization images" ON storage.objects FOR INSERT @@ -19,6 +21,7 @@ WITH CHECK ( ); -- Allow admins to update images +DROP POLICY IF EXISTS "Admins can update personalization images" ON storage.objects; CREATE POLICY "Admins can update personalization images" ON storage.objects FOR UPDATE @@ -28,6 +31,7 @@ USING ( ); -- Allow admins to delete images +DROP POLICY IF EXISTS "Admins can delete personalization images" ON storage.objects; CREATE POLICY "Admins can delete personalization images" ON storage.objects FOR DELETE diff --git a/supabase/migrations/20251214212212_f25bfdd3-ddc8-4a06-896a-0be8733968ee.sql b/supabase/migrations/20251214212212_f25bfdd3-ddc8-4a06-896a-0be8733968ee.sql index 6de4c9aa9..d69ae14d7 100644 --- a/supabase/migrations/20251214212212_f25bfdd3-ddc8-4a06-896a-0be8733968ee.sql +++ b/supabase/migrations/20251214212212_f25bfdd3-ddc8-4a06-896a-0be8733968ee.sql @@ -1,5 +1,5 @@ --- Create table for saved personalization simulations -CREATE TABLE public.personalization_simulations ( +-- CREATE TABLE IF NOT EXISTS for saved personalization simulations +CREATE TABLE IF NOT EXISTS public.personalization_simulations ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, seller_id UUID NOT NULL, client_id UUID REFERENCES public.bitrix_clients(id) ON DELETE SET NULL, @@ -18,27 +18,32 @@ CREATE TABLE public.personalization_simulations ( ALTER TABLE public.personalization_simulations ENABLE ROW LEVEL SECURITY; -- RLS Policies +DROP POLICY IF EXISTS "Sellers can view their own simulations" ON public.personalization_simulations; CREATE POLICY "Sellers can view their own simulations" ON public.personalization_simulations FOR SELECT USING (seller_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Sellers can create their own simulations" ON public.personalization_simulations; CREATE POLICY "Sellers can create their own simulations" ON public.personalization_simulations FOR INSERT WITH CHECK (seller_id = auth.uid()); +DROP POLICY IF EXISTS "Sellers can update their own simulations" ON public.personalization_simulations; CREATE POLICY "Sellers can update their own simulations" ON public.personalization_simulations FOR UPDATE USING (seller_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Sellers can delete their own simulations" ON public.personalization_simulations; CREATE POLICY "Sellers can delete their own simulations" ON public.personalization_simulations FOR DELETE USING (seller_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)); -- Trigger for updated_at +DROP TRIGGER IF EXISTS update_personalization_simulations_updated_at ON public.personalization_simulations; CREATE TRIGGER update_personalization_simulations_updated_at BEFORE UPDATE ON public.personalization_simulations FOR EACH ROW diff --git a/supabase/migrations/20251215002227_ba71d2dc-e527-4f63-8c01-ca9b43f83daf.sql b/supabase/migrations/20251215002227_ba71d2dc-e527-4f63-8c01-ca9b43f83daf.sql index 7aca5f72d..19a9e4719 100644 --- a/supabase/migrations/20251215002227_ba71d2dc-e527-4f63-8c01-ca9b43f83daf.sql +++ b/supabase/migrations/20251215002227_ba71d2dc-e527-4f63-8c01-ca9b43f83daf.sql @@ -1,5 +1,5 @@ --- Create table for expert conversations -CREATE TABLE public.expert_conversations ( +-- CREATE TABLE IF NOT EXISTS for expert conversations +CREATE TABLE IF NOT EXISTS public.expert_conversations ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, seller_id UUID NOT NULL, client_id UUID REFERENCES public.bitrix_clients(id), @@ -8,8 +8,8 @@ CREATE TABLE public.expert_conversations ( updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now() ); --- Create table for expert messages -CREATE TABLE public.expert_messages ( +-- CREATE TABLE IF NOT EXISTS for expert messages +CREATE TABLE IF NOT EXISTS public.expert_messages ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, conversation_id UUID NOT NULL REFERENCES public.expert_conversations(id) ON DELETE CASCADE, role TEXT NOT NULL CHECK (role IN ('user', 'assistant')), @@ -22,23 +22,28 @@ ALTER TABLE public.expert_conversations ENABLE ROW LEVEL SECURITY; ALTER TABLE public.expert_messages ENABLE ROW LEVEL SECURITY; -- RLS policies for conversations +DROP POLICY IF EXISTS "Sellers can view their own conversations" ON public.expert_conversations; CREATE POLICY "Sellers can view their own conversations" ON public.expert_conversations FOR SELECT USING (seller_id = auth.uid() OR has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Sellers can create their own conversations" ON public.expert_conversations; CREATE POLICY "Sellers can create their own conversations" ON public.expert_conversations FOR INSERT WITH CHECK (seller_id = auth.uid()); +DROP POLICY IF EXISTS "Sellers can update their own conversations" ON public.expert_conversations; CREATE POLICY "Sellers can update their own conversations" ON public.expert_conversations FOR UPDATE USING (seller_id = auth.uid() OR has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Sellers can delete their own conversations" ON public.expert_conversations; CREATE POLICY "Sellers can delete their own conversations" ON public.expert_conversations FOR DELETE USING (seller_id = auth.uid() OR has_role(auth.uid(), 'admin')); -- RLS policies for messages +DROP POLICY IF EXISTS "Sellers can view messages of their conversations" ON public.expert_messages; CREATE POLICY "Sellers can view messages of their conversations" ON public.expert_messages FOR SELECT USING (EXISTS ( @@ -47,6 +52,7 @@ USING (EXISTS ( AND (c.seller_id = auth.uid() OR has_role(auth.uid(), 'admin')) )); +DROP POLICY IF EXISTS "Sellers can create messages in their conversations" ON public.expert_messages; CREATE POLICY "Sellers can create messages in their conversations" ON public.expert_messages FOR INSERT WITH CHECK (EXISTS ( @@ -56,10 +62,11 @@ WITH CHECK (EXISTS ( )); -- Index for performance -CREATE INDEX idx_expert_conversations_seller ON public.expert_conversations(seller_id); -CREATE INDEX idx_expert_messages_conversation ON public.expert_messages(conversation_id); +CREATE INDEX IF NOT EXISTS idx_expert_conversations_seller ON public.expert_conversations(seller_id); +CREATE INDEX IF NOT EXISTS idx_expert_messages_conversation ON public.expert_messages(conversation_id); -- Trigger to update conversation updated_at +DROP TRIGGER IF EXISTS update_expert_conversations_updated_at ON public.expert_conversations; CREATE TRIGGER update_expert_conversations_updated_at BEFORE UPDATE ON public.expert_conversations FOR EACH ROW diff --git a/supabase/migrations/20251215002803_1c29a752-89f0-406e-ba83-9332854de192.sql b/supabase/migrations/20251215002803_1c29a752-89f0-406e-ba83-9332854de192.sql index 52c0ebc61..2d07c771f 100644 --- a/supabase/migrations/20251215002803_1c29a752-89f0-406e-ba83-9332854de192.sql +++ b/supabase/migrations/20251215002803_1c29a752-89f0-406e-ba83-9332854de192.sql @@ -4,7 +4,7 @@ CREATE EXTENSION IF NOT EXISTS pg_trgm; -- Add search vector column to products ALTER TABLE public.products ADD COLUMN IF NOT EXISTS search_vector tsvector; --- Create function to generate search vector +-- CREATE OR REPLACE function to generate search vector CREATE OR REPLACE FUNCTION public.products_generate_search_vector() RETURNS trigger LANGUAGE plpgsql diff --git a/supabase/migrations/20251215011449_730d6884-f2e8-4fe0-96e6-b03c13694aa4.sql b/supabase/migrations/20251215011449_730d6884-f2e8-4fe0-96e6-b03c13694aa4.sql index 5511ea344..b2fc2626b 100644 --- a/supabase/migrations/20251215011449_730d6884-f2e8-4fe0-96e6-b03c13694aa4.sql +++ b/supabase/migrations/20251215011449_730d6884-f2e8-4fe0-96e6-b03c13694aa4.sql @@ -1,5 +1,5 @@ --- Create table for storing generated mockups -CREATE TABLE public.generated_mockups ( +-- CREATE TABLE IF NOT EXISTS for storing generated mockups +CREATE TABLE IF NOT EXISTS public.generated_mockups ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, seller_id UUID NOT NULL, client_id UUID REFERENCES public.bitrix_clients(id) ON DELETE SET NULL, @@ -17,27 +17,30 @@ CREATE TABLE public.generated_mockups ( created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now() ); --- Create index for faster queries -CREATE INDEX idx_generated_mockups_seller_id ON public.generated_mockups(seller_id); -CREATE INDEX idx_generated_mockups_client_id ON public.generated_mockups(client_id); -CREATE INDEX idx_generated_mockups_created_at ON public.generated_mockups(created_at DESC); +-- CREATE INDEX IF NOT EXISTS for faster queries +CREATE INDEX IF NOT EXISTS idx_generated_mockups_seller_id ON public.generated_mockups(seller_id); +CREATE INDEX IF NOT EXISTS idx_generated_mockups_client_id ON public.generated_mockups(client_id); +CREATE INDEX IF NOT EXISTS idx_generated_mockups_created_at ON public.generated_mockups(created_at DESC); -- Enable RLS ALTER TABLE public.generated_mockups ENABLE ROW LEVEL SECURITY; -- Sellers can view their own mockups +DROP POLICY IF EXISTS "Sellers can view their own mockups" ON public.generated_mockups; CREATE POLICY "Sellers can view their own mockups" ON public.generated_mockups FOR SELECT USING (seller_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)); -- Sellers can create their own mockups +DROP POLICY IF EXISTS "Sellers can create their own mockups" ON public.generated_mockups; CREATE POLICY "Sellers can create their own mockups" ON public.generated_mockups FOR INSERT WITH CHECK (seller_id = auth.uid()); -- Sellers can delete their own mockups +DROP POLICY IF EXISTS "Sellers can delete their own mockups" ON public.generated_mockups; CREATE POLICY "Sellers can delete their own mockups" ON public.generated_mockups FOR DELETE diff --git a/supabase/migrations/20251215113936_0e13449e-e4f8-4811-8902-d69704923f5c.sql b/supabase/migrations/20251215113936_0e13449e-e4f8-4811-8902-d69704923f5c.sql index 5fe51f81c..185cc0e0e 100644 --- a/supabase/migrations/20251215113936_0e13449e-e4f8-4811-8902-d69704923f5c.sql +++ b/supabase/migrations/20251215113936_0e13449e-e4f8-4811-8902-d69704923f5c.sql @@ -1,5 +1,5 @@ -- Tabela de gamificação do vendedor -CREATE TABLE public.seller_gamification ( +CREATE TABLE IF NOT EXISTS public.seller_gamification ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL UNIQUE REFERENCES auth.users(id) ON DELETE CASCADE, xp INTEGER NOT NULL DEFAULT 0, @@ -13,7 +13,7 @@ CREATE TABLE public.seller_gamification ( ); -- Tabela de conquistas disponíveis -CREATE TABLE public.achievements ( +CREATE TABLE IF NOT EXISTS public.achievements ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), code TEXT NOT NULL UNIQUE, name TEXT NOT NULL, @@ -29,7 +29,7 @@ CREATE TABLE public.achievements ( ); -- Tabela de conquistas do vendedor (junction) -CREATE TABLE public.seller_achievements ( +CREATE TABLE IF NOT EXISTS public.seller_achievements ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE, achievement_id UUID NOT NULL REFERENCES public.achievements(id) ON DELETE CASCADE, @@ -43,30 +43,38 @@ ALTER TABLE public.achievements ENABLE ROW LEVEL SECURITY; ALTER TABLE public.seller_achievements ENABLE ROW LEVEL SECURITY; -- RLS Policies for seller_gamification +DROP POLICY IF EXISTS "Users can view their own gamification" ON public.seller_gamification; CREATE POLICY "Users can view their own gamification" ON public.seller_gamification FOR SELECT USING (auth.uid() = user_id OR has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Users can update their own gamification" ON public.seller_gamification; CREATE POLICY "Users can update their own gamification" ON public.seller_gamification FOR UPDATE USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "System can insert gamification" ON public.seller_gamification; CREATE POLICY "System can insert gamification" ON public.seller_gamification FOR INSERT WITH CHECK (auth.uid() = user_id); -- RLS Policies for achievements +DROP POLICY IF EXISTS "Anyone can view achievements" ON public.achievements; CREATE POLICY "Anyone can view achievements" ON public.achievements FOR SELECT USING (is_active = true); +DROP POLICY IF EXISTS "Admins can manage achievements" ON public.achievements; CREATE POLICY "Admins can manage achievements" ON public.achievements FOR ALL USING (has_role(auth.uid(), 'admin')) WITH CHECK (has_role(auth.uid(), 'admin')); -- RLS Policies for seller_achievements +DROP POLICY IF EXISTS "Users can view their own achievements" ON public.seller_achievements; CREATE POLICY "Users can view their own achievements" ON public.seller_achievements FOR SELECT USING (auth.uid() = user_id OR has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Users can earn achievements" ON public.seller_achievements; CREATE POLICY "Users can earn achievements" ON public.seller_achievements FOR INSERT WITH CHECK (auth.uid() = user_id); -- Trigger to update updated_at +DROP TRIGGER IF EXISTS update_seller_gamification_updated_at ON public.seller_gamification; CREATE TRIGGER update_seller_gamification_updated_at BEFORE UPDATE ON public.seller_gamification FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); diff --git a/supabase/migrations/20251215164521_6de8b3bc-1a58-4a1c-bc1a-3dc254c0ba68.sql b/supabase/migrations/20251215164521_6de8b3bc-1a58-4a1c-bc1a-3dc254c0ba68.sql index 65be663d6..ca56048ed 100644 --- a/supabase/migrations/20251215164521_6de8b3bc-1a58-4a1c-bc1a-3dc254c0ba68.sql +++ b/supabase/migrations/20251215164521_6de8b3bc-1a58-4a1c-bc1a-3dc254c0ba68.sql @@ -1,5 +1,5 @@ --- Create table for product view analytics -CREATE TABLE public.product_views ( +-- CREATE TABLE IF NOT EXISTS for product view analytics +CREATE TABLE IF NOT EXISTS public.product_views ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, product_id UUID REFERENCES public.products(id) ON DELETE CASCADE, product_sku TEXT, @@ -9,8 +9,8 @@ CREATE TABLE public.product_views ( created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now() ); --- Create table for search analytics -CREATE TABLE public.search_analytics ( +-- CREATE TABLE IF NOT EXISTS for search analytics +CREATE TABLE IF NOT EXISTS public.search_analytics ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, search_term TEXT NOT NULL, results_count INTEGER DEFAULT 0, @@ -20,43 +20,49 @@ CREATE TABLE public.search_analytics ( ); -- Create indexes for performance -CREATE INDEX idx_product_views_product_id ON public.product_views(product_id); -CREATE INDEX idx_product_views_created_at ON public.product_views(created_at DESC); -CREATE INDEX idx_product_views_seller_id ON public.product_views(seller_id); -CREATE INDEX idx_search_analytics_created_at ON public.search_analytics(created_at DESC); -CREATE INDEX idx_search_analytics_search_term ON public.search_analytics(search_term); +CREATE INDEX IF NOT EXISTS idx_product_views_product_id ON public.product_views(product_id); +CREATE INDEX IF NOT EXISTS idx_product_views_created_at ON public.product_views(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_product_views_seller_id ON public.product_views(seller_id); +CREATE INDEX IF NOT EXISTS idx_search_analytics_created_at ON public.search_analytics(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_search_analytics_search_term ON public.search_analytics(search_term); -- Enable RLS ALTER TABLE public.product_views ENABLE ROW LEVEL SECURITY; ALTER TABLE public.search_analytics ENABLE ROW LEVEL SECURITY; -- RLS Policies for product_views +DROP POLICY IF EXISTS "Sellers can create their own views" ON public.product_views; CREATE POLICY "Sellers can create their own views" ON public.product_views FOR INSERT WITH CHECK (seller_id = auth.uid()); +DROP POLICY IF EXISTS "Admins can view all product views" ON public.product_views; CREATE POLICY "Admins can view all product views" ON public.product_views FOR SELECT USING (has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Sellers can view their own views" ON public.product_views; CREATE POLICY "Sellers can view their own views" ON public.product_views FOR SELECT USING (seller_id = auth.uid()); -- RLS Policies for search_analytics +DROP POLICY IF EXISTS "Sellers can create their own searches" ON public.search_analytics; CREATE POLICY "Sellers can create their own searches" ON public.search_analytics FOR INSERT WITH CHECK (seller_id = auth.uid()); +DROP POLICY IF EXISTS "Admins can view all searches" ON public.search_analytics; CREATE POLICY "Admins can view all searches" ON public.search_analytics FOR SELECT USING (has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Sellers can view their own searches" ON public.search_analytics; CREATE POLICY "Sellers can view their own searches" ON public.search_analytics FOR SELECT diff --git a/supabase/migrations/20251220110803_8253265f-3b2d-4dc8-af7a-6aff4aae5e72.sql b/supabase/migrations/20251220110803_8253265f-3b2d-4dc8-af7a-6aff4aae5e72.sql index 5ace746ee..e088e5e83 100644 --- a/supabase/migrations/20251220110803_8253265f-3b2d-4dc8-af7a-6aff4aae5e72.sql +++ b/supabase/migrations/20251220110803_8253265f-3b2d-4dc8-af7a-6aff4aae5e72.sql @@ -1,5 +1,5 @@ --- Create table for quote templates -CREATE TABLE public.quote_templates ( +-- CREATE TABLE IF NOT EXISTS for quote templates +CREATE TABLE IF NOT EXISTS public.quote_templates ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, seller_id UUID NOT NULL, name TEXT NOT NULL, @@ -22,27 +22,32 @@ CREATE TABLE public.quote_templates ( ALTER TABLE public.quote_templates ENABLE ROW LEVEL SECURITY; -- Create policies +DROP POLICY IF EXISTS "Sellers can view their own templates" ON public.quote_templates; CREATE POLICY "Sellers can view their own templates" ON public.quote_templates FOR SELECT USING (seller_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Sellers can create their own templates" ON public.quote_templates; CREATE POLICY "Sellers can create their own templates" ON public.quote_templates FOR INSERT WITH CHECK (seller_id = auth.uid()); +DROP POLICY IF EXISTS "Sellers can update their own templates" ON public.quote_templates; CREATE POLICY "Sellers can update their own templates" ON public.quote_templates FOR UPDATE USING (seller_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Sellers can delete their own templates" ON public.quote_templates; CREATE POLICY "Sellers can delete their own templates" ON public.quote_templates FOR DELETE USING (seller_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)); -- Create trigger for updated_at +DROP TRIGGER IF EXISTS update_quote_templates_updated_at ON public.quote_templates; CREATE TRIGGER update_quote_templates_updated_at BEFORE UPDATE ON public.quote_templates FOR EACH ROW diff --git a/supabase/migrations/20251220131225_6ad66331-ea04-4f49-89fe-80b0531fef66.sql b/supabase/migrations/20251220131225_6ad66331-ea04-4f49-89fe-80b0531fef66.sql index 013cbd71a..571d76fe1 100644 --- a/supabase/migrations/20251220131225_6ad66331-ea04-4f49-89fe-80b0531fef66.sql +++ b/supabase/migrations/20251220131225_6ad66331-ea04-4f49-89fe-80b0531fef66.sql @@ -1,5 +1,5 @@ --- Create table for quote change history -CREATE TABLE public.quote_history ( +-- CREATE TABLE IF NOT EXISTS for quote change history +CREATE TABLE IF NOT EXISTS public.quote_history ( id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, quote_id uuid NOT NULL REFERENCES public.quotes(id) ON DELETE CASCADE, user_id uuid NOT NULL, @@ -12,14 +12,15 @@ CREATE TABLE public.quote_history ( created_at timestamp with time zone NOT NULL DEFAULT now() ); --- Create index for faster queries -CREATE INDEX idx_quote_history_quote_id ON public.quote_history(quote_id); -CREATE INDEX idx_quote_history_created_at ON public.quote_history(created_at DESC); +-- CREATE INDEX IF NOT EXISTS for faster queries +CREATE INDEX IF NOT EXISTS idx_quote_history_quote_id ON public.quote_history(quote_id); +CREATE INDEX IF NOT EXISTS idx_quote_history_created_at ON public.quote_history(created_at DESC); -- Enable RLS ALTER TABLE public.quote_history ENABLE ROW LEVEL SECURITY; -- Policy: Users can view history of their own quotes +DROP POLICY IF EXISTS "Users can view history of their quotes" ON public.quote_history; CREATE POLICY "Users can view history of their quotes" ON public.quote_history FOR SELECT @@ -32,6 +33,7 @@ USING ( ); -- Policy: Users can create history for their own quotes +DROP POLICY IF EXISTS "Users can create history for their quotes" ON public.quote_history; CREATE POLICY "Users can create history for their quotes" ON public.quote_history FOR INSERT diff --git a/supabase/migrations/20251220131603_2a51652f-dd05-4607-9579-062611aa46e7.sql b/supabase/migrations/20251220131603_2a51652f-dd05-4607-9579-062611aa46e7.sql index 3e3024665..3d1aa4119 100644 --- a/supabase/migrations/20251220131603_2a51652f-dd05-4607-9579-062611aa46e7.sql +++ b/supabase/migrations/20251220131603_2a51652f-dd05-4607-9579-062611aa46e7.sql @@ -1,5 +1,5 @@ --- Create table for quote approval tokens -CREATE TABLE public.quote_approval_tokens ( +-- CREATE TABLE IF NOT EXISTS for quote approval tokens +CREATE TABLE IF NOT EXISTS public.quote_approval_tokens ( id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, quote_id uuid NOT NULL REFERENCES public.quotes(id) ON DELETE CASCADE, token text NOT NULL UNIQUE, @@ -9,14 +9,15 @@ CREATE TABLE public.quote_approval_tokens ( created_by uuid NOT NULL ); --- Create index for token lookup -CREATE INDEX idx_quote_approval_tokens_token ON public.quote_approval_tokens(token); -CREATE INDEX idx_quote_approval_tokens_quote_id ON public.quote_approval_tokens(quote_id); +-- CREATE INDEX IF NOT EXISTS for token lookup +CREATE INDEX IF NOT EXISTS idx_quote_approval_tokens_token ON public.quote_approval_tokens(token); +CREATE INDEX IF NOT EXISTS idx_quote_approval_tokens_quote_id ON public.quote_approval_tokens(quote_id); -- Enable RLS ALTER TABLE public.quote_approval_tokens ENABLE ROW LEVEL SECURITY; -- Policy: Users can view tokens for their own quotes +DROP POLICY IF EXISTS "Users can view tokens for their quotes" ON public.quote_approval_tokens; CREATE POLICY "Users can view tokens for their quotes" ON public.quote_approval_tokens FOR SELECT @@ -29,6 +30,7 @@ USING ( ); -- Policy: Users can create tokens for their own quotes +DROP POLICY IF EXISTS "Users can create tokens for their quotes" ON public.quote_approval_tokens; CREATE POLICY "Users can create tokens for their quotes" ON public.quote_approval_tokens FOR INSERT @@ -41,6 +43,7 @@ WITH CHECK ( ); -- Policy: Service role can manage all tokens (for edge function) +DROP POLICY IF EXISTS "Service can manage tokens" ON public.quote_approval_tokens; CREATE POLICY "Service can manage tokens" ON public.quote_approval_tokens FOR ALL diff --git a/supabase/migrations/20251220140213_3ea8f71f-d506-46a7-8f3b-ef6b5607a592.sql b/supabase/migrations/20251220140213_3ea8f71f-d506-46a7-8f3b-ef6b5607a592.sql index fa1f2aa44..a52da9fcd 100644 --- a/supabase/migrations/20251220140213_3ea8f71f-d506-46a7-8f3b-ef6b5607a592.sql +++ b/supabase/migrations/20251220140213_3ea8f71f-d506-46a7-8f3b-ef6b5607a592.sql @@ -1,5 +1,5 @@ -- Create notifications table -CREATE TABLE public.notifications ( +CREATE TABLE IF NOT EXISTS public.notifications ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID NOT NULL, type TEXT NOT NULL, -- 'quote_viewed', 'low_stock', 'goal_achieved', 'quote_approved', 'quote_rejected' @@ -14,33 +14,37 @@ CREATE TABLE public.notifications ( ALTER TABLE public.notifications ENABLE ROW LEVEL SECURITY; -- Users can view their own notifications +DROP POLICY IF EXISTS "Users can view their own notifications" ON public.notifications; CREATE POLICY "Users can view their own notifications" ON public.notifications FOR SELECT USING (auth.uid() = user_id); -- Users can update their own notifications (mark as read) +DROP POLICY IF EXISTS "Users can update their own notifications" ON public.notifications; CREATE POLICY "Users can update their own notifications" ON public.notifications FOR UPDATE USING (auth.uid() = user_id); -- System/service can create notifications +DROP POLICY IF EXISTS "Service can create notifications" ON public.notifications; CREATE POLICY "Service can create notifications" ON public.notifications FOR INSERT WITH CHECK (true); -- Users can delete their own notifications +DROP POLICY IF EXISTS "Users can delete their own notifications" ON public.notifications; CREATE POLICY "Users can delete their own notifications" ON public.notifications FOR DELETE USING (auth.uid() = user_id); --- Create index for faster queries -CREATE INDEX idx_notifications_user_id ON public.notifications(user_id); -CREATE INDEX idx_notifications_created_at ON public.notifications(created_at DESC); -CREATE INDEX idx_notifications_is_read ON public.notifications(user_id, is_read); +-- CREATE INDEX IF NOT EXISTS for faster queries +CREATE INDEX IF NOT EXISTS idx_notifications_user_id ON public.notifications(user_id); +CREATE INDEX IF NOT EXISTS idx_notifications_created_at ON public.notifications(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_notifications_is_read ON public.notifications(user_id, is_read); -- Enable realtime for notifications ALTER PUBLICATION supabase_realtime ADD TABLE public.notifications; \ No newline at end of file diff --git a/supabase/migrations/20251220141234_12ce9efd-dc19-41da-81d7-e7cd50562473.sql b/supabase/migrations/20251220141234_12ce9efd-dc19-41da-81d7-e7cd50562473.sql index cf4110e65..b576b0fa7 100644 --- a/supabase/migrations/20251220141234_12ce9efd-dc19-41da-81d7-e7cd50562473.sql +++ b/supabase/migrations/20251220141234_12ce9efd-dc19-41da-81d7-e7cd50562473.sql @@ -1,5 +1,6 @@ -- Create order status enum +DO $$ BEGIN CREATE TYPE public.order_status AS ENUM ( 'pending', 'confirmed', @@ -9,8 +10,11 @@ CREATE TYPE public.order_status AS ENUM ( 'delivered', 'cancelled' ); +EXCEPTION WHEN duplicate_object THEN NULL; +END $$; -- Create fulfillment status enum +DO $$ BEGIN CREATE TYPE public.fulfillment_status AS ENUM ( 'not_started', 'picking', @@ -18,9 +22,11 @@ CREATE TYPE public.fulfillment_status AS ENUM ( 'shipped', 'delivered' ); +EXCEPTION WHEN duplicate_object THEN NULL; +END $$; -- Create orders table -CREATE TABLE public.orders ( +CREATE TABLE IF NOT EXISTS public.orders ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, order_number TEXT NOT NULL UNIQUE, quote_id UUID REFERENCES public.quotes(id), @@ -52,7 +58,7 @@ CREATE TABLE public.orders ( ); -- Create order items table -CREATE TABLE public.order_items ( +CREATE TABLE IF NOT EXISTS public.order_items ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, order_id UUID NOT NULL REFERENCES public.orders(id) ON DELETE CASCADE, product_id TEXT, @@ -71,7 +77,7 @@ CREATE TABLE public.order_items ( ); -- Create order history table for tracking changes -CREATE TABLE public.order_history ( +CREATE TABLE IF NOT EXISTS public.order_history ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, order_id UUID NOT NULL REFERENCES public.orders(id) ON DELETE CASCADE, user_id UUID NOT NULL, @@ -83,10 +89,10 @@ CREATE TABLE public.order_history ( created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now() ); --- Create sequence for order numbers +-- CREATE SEQUENCE IF NOT EXISTS for order numbers CREATE SEQUENCE IF NOT EXISTS order_number_seq START 1; --- Create function to generate order number +-- CREATE OR REPLACE function to generate order number CREATE OR REPLACE FUNCTION public.generate_order_number() RETURNS TRIGGER AS $$ BEGIN @@ -96,12 +102,14 @@ END; $$ LANGUAGE plpgsql SET search_path = public; -- Create trigger for order number +DROP TRIGGER IF EXISTS set_order_number ON public.orders; CREATE TRIGGER set_order_number BEFORE INSERT ON public.orders FOR EACH ROW EXECUTE FUNCTION public.generate_order_number(); -- Create trigger for updated_at +DROP TRIGGER IF EXISTS update_orders_updated_at ON public.orders; CREATE TRIGGER update_orders_updated_at BEFORE UPDATE ON public.orders FOR EACH ROW @@ -113,23 +121,28 @@ ALTER TABLE public.order_items ENABLE ROW LEVEL SECURITY; ALTER TABLE public.order_history ENABLE ROW LEVEL SECURITY; -- RLS Policies for orders +DROP POLICY IF EXISTS "Sellers can view their own orders" ON public.orders; CREATE POLICY "Sellers can view their own orders" ON public.orders FOR SELECT USING (seller_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Sellers can create orders" ON public.orders; CREATE POLICY "Sellers can create orders" ON public.orders FOR INSERT WITH CHECK (seller_id = auth.uid()); +DROP POLICY IF EXISTS "Sellers can update their own orders" ON public.orders; CREATE POLICY "Sellers can update their own orders" ON public.orders FOR UPDATE USING (seller_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Admins can delete orders" ON public.orders; CREATE POLICY "Admins can delete orders" ON public.orders FOR DELETE USING (has_role(auth.uid(), 'admin'::app_role)); -- RLS Policies for order_items +DROP POLICY IF EXISTS "Users can view items of their orders" ON public.order_items; CREATE POLICY "Users can view items of their orders" ON public.order_items FOR SELECT USING (EXISTS ( @@ -138,6 +151,7 @@ CREATE POLICY "Users can view items of their orders" AND (o.seller_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)) )); +DROP POLICY IF EXISTS "Users can manage items of their orders" ON public.order_items; CREATE POLICY "Users can manage items of their orders" ON public.order_items FOR ALL USING (EXISTS ( @@ -152,6 +166,7 @@ CREATE POLICY "Users can manage items of their orders" )); -- RLS Policies for order_history +DROP POLICY IF EXISTS "Users can view history of their orders" ON public.order_history; CREATE POLICY "Users can view history of their orders" ON public.order_history FOR SELECT USING (EXISTS ( @@ -160,6 +175,7 @@ CREATE POLICY "Users can view history of their orders" AND (o.seller_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)) )); +DROP POLICY IF EXISTS "Users can create history for their orders" ON public.order_history; CREATE POLICY "Users can create history for their orders" ON public.order_history FOR INSERT WITH CHECK (EXISTS ( diff --git a/supabase/migrations/20251220181321_e148d318-752b-4c4a-8bb3-da2163faab3c.sql b/supabase/migrations/20251220181321_e148d318-752b-4c4a-8bb3-da2163faab3c.sql index 1b4c19114..59099f6d8 100644 --- a/supabase/migrations/20251220181321_e148d318-752b-4c4a-8bb3-da2163faab3c.sql +++ b/supabase/migrations/20251220181321_e148d318-752b-4c4a-8bb3-da2163faab3c.sql @@ -1,6 +1,6 @@ -- Create sales_goals table for tracking seller goals -CREATE TABLE public.sales_goals ( +CREATE TABLE IF NOT EXISTS public.sales_goals ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID NOT NULL, goal_type TEXT NOT NULL DEFAULT 'monthly', -- monthly, weekly, quarterly @@ -22,31 +22,36 @@ CREATE TABLE public.sales_goals ( ALTER TABLE public.sales_goals ENABLE ROW LEVEL SECURITY; -- Policies +DROP POLICY IF EXISTS "Users can view their own goals" ON public.sales_goals; CREATE POLICY "Users can view their own goals" ON public.sales_goals FOR SELECT USING (user_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Users can create their own goals" ON public.sales_goals; CREATE POLICY "Users can create their own goals" ON public.sales_goals FOR INSERT WITH CHECK (user_id = auth.uid()); +DROP POLICY IF EXISTS "Users can update their own goals" ON public.sales_goals; CREATE POLICY "Users can update their own goals" ON public.sales_goals FOR UPDATE USING (user_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Users can delete their own goals" ON public.sales_goals; CREATE POLICY "Users can delete their own goals" ON public.sales_goals FOR DELETE USING (user_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)); -- Trigger for updated_at +DROP TRIGGER IF EXISTS update_sales_goals_updated_at ON public.sales_goals; CREATE TRIGGER update_sales_goals_updated_at BEFORE UPDATE ON public.sales_goals FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); --- Create index for faster queries -CREATE INDEX idx_sales_goals_user_date ON public.sales_goals(user_id, start_date, end_date); +-- CREATE INDEX IF NOT EXISTS for faster queries +CREATE INDEX IF NOT EXISTS idx_sales_goals_user_date ON public.sales_goals(user_id, start_date, end_date); diff --git a/supabase/migrations/20251220181526_70f76277-b962-4a6f-a7b5-f977d86e86b2.sql b/supabase/migrations/20251220181526_70f76277-b962-4a6f-a7b5-f977d86e86b2.sql index 457e5eb52..92e5d7faa 100644 --- a/supabase/migrations/20251220181526_70f76277-b962-4a6f-a7b5-f977d86e86b2.sql +++ b/supabase/migrations/20251220181526_70f76277-b962-4a6f-a7b5-f977d86e86b2.sql @@ -1,6 +1,6 @@ -- Create follow_up_reminders table for tracking client follow-ups -CREATE TABLE public.follow_up_reminders ( +CREATE TABLE IF NOT EXISTS public.follow_up_reminders ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID NOT NULL, client_id UUID REFERENCES public.bitrix_clients(id) ON DELETE CASCADE, @@ -20,32 +20,37 @@ CREATE TABLE public.follow_up_reminders ( ALTER TABLE public.follow_up_reminders ENABLE ROW LEVEL SECURITY; -- Policies +DROP POLICY IF EXISTS "Users can view their own reminders" ON public.follow_up_reminders; CREATE POLICY "Users can view their own reminders" ON public.follow_up_reminders FOR SELECT USING (user_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Users can create their own reminders" ON public.follow_up_reminders; CREATE POLICY "Users can create their own reminders" ON public.follow_up_reminders FOR INSERT WITH CHECK (user_id = auth.uid()); +DROP POLICY IF EXISTS "Users can update their own reminders" ON public.follow_up_reminders; CREATE POLICY "Users can update their own reminders" ON public.follow_up_reminders FOR UPDATE USING (user_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Users can delete their own reminders" ON public.follow_up_reminders; CREATE POLICY "Users can delete their own reminders" ON public.follow_up_reminders FOR DELETE USING (user_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)); -- Trigger for updated_at +DROP TRIGGER IF EXISTS update_follow_up_reminders_updated_at ON public.follow_up_reminders; CREATE TRIGGER update_follow_up_reminders_updated_at BEFORE UPDATE ON public.follow_up_reminders FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); -- Index for faster queries -CREATE INDEX idx_follow_up_reminders_user_date ON public.follow_up_reminders(user_id, reminder_date); -CREATE INDEX idx_follow_up_reminders_client ON public.follow_up_reminders(client_id); +CREATE INDEX IF NOT EXISTS idx_follow_up_reminders_user_date ON public.follow_up_reminders(user_id, reminder_date); +CREATE INDEX IF NOT EXISTS idx_follow_up_reminders_client ON public.follow_up_reminders(client_id); diff --git a/supabase/migrations/20251227170236_52049167-ddfd-492a-847c-55c74c36321a.sql b/supabase/migrations/20251227170236_52049167-ddfd-492a-847c-55c74c36321a.sql index 454fce394..92d5d3612 100644 --- a/supabase/migrations/20251227170236_52049167-ddfd-492a-847c-55c74c36321a.sql +++ b/supabase/migrations/20251227170236_52049167-ddfd-492a-847c-55c74c36321a.sql @@ -1,5 +1,5 @@ -- Create rewards store table -CREATE TABLE public.store_rewards ( +CREATE TABLE IF NOT EXISTS public.store_rewards ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, code TEXT NOT NULL UNIQUE, name TEXT NOT NULL, @@ -16,7 +16,7 @@ CREATE TABLE public.store_rewards ( ); -- Create user purchased rewards table -CREATE TABLE public.user_rewards ( +CREATE TABLE IF NOT EXISTS public.user_rewards ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID NOT NULL, reward_id UUID NOT NULL REFERENCES public.store_rewards(id) ON DELETE CASCADE, @@ -30,19 +30,23 @@ ALTER TABLE public.store_rewards ENABLE ROW LEVEL SECURITY; ALTER TABLE public.user_rewards ENABLE ROW LEVEL SECURITY; -- Store rewards policies (read-only for authenticated users) +DROP POLICY IF EXISTS "Anyone authenticated can view active rewards" ON public.store_rewards; CREATE POLICY "Anyone authenticated can view active rewards" ON public.store_rewards FOR SELECT USING (auth.uid() IS NOT NULL AND is_active = true); -- User rewards policies +DROP POLICY IF EXISTS "Users can view their own rewards" ON public.user_rewards; CREATE POLICY "Users can view their own rewards" ON public.user_rewards FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can purchase rewards" ON public.user_rewards; CREATE POLICY "Users can purchase rewards" ON public.user_rewards FOR INSERT WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can update their own rewards" ON public.user_rewards; CREATE POLICY "Users can update their own rewards" ON public.user_rewards FOR UPDATE USING (auth.uid() = user_id); diff --git a/supabase/migrations/20251227175512_1e710604-28f2-4cc0-8b47-3c59cda3580e.sql b/supabase/migrations/20251227175512_1e710604-28f2-4cc0-8b47-3c59cda3580e.sql index 5dbe3fedd..d4023e194 100644 --- a/supabase/migrations/20251227175512_1e710604-28f2-4cc0-8b47-3c59cda3580e.sql +++ b/supabase/migrations/20251227175512_1e710604-28f2-4cc0-8b47-3c59cda3580e.sql @@ -1,5 +1,5 @@ --- Create table to track user onboarding progress -CREATE TABLE public.user_onboarding ( +-- CREATE TABLE IF NOT EXISTS to track user onboarding progress +CREATE TABLE IF NOT EXISTS public.user_onboarding ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID NOT NULL UNIQUE, has_completed_tour BOOLEAN DEFAULT false, @@ -15,19 +15,23 @@ CREATE TABLE public.user_onboarding ( ALTER TABLE public.user_onboarding ENABLE ROW LEVEL SECURITY; -- RLS Policies +DROP POLICY IF EXISTS "Users can view their own onboarding" ON public.user_onboarding; CREATE POLICY "Users can view their own onboarding" ON public.user_onboarding FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can create their own onboarding" ON public.user_onboarding; CREATE POLICY "Users can create their own onboarding" ON public.user_onboarding FOR INSERT WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can update their own onboarding" ON public.user_onboarding; CREATE POLICY "Users can update their own onboarding" ON public.user_onboarding FOR UPDATE USING (auth.uid() = user_id); -- Trigger for updated_at +DROP TRIGGER IF EXISTS update_user_onboarding_updated_at ON public.user_onboarding; CREATE TRIGGER update_user_onboarding_updated_at BEFORE UPDATE ON public.user_onboarding FOR EACH ROW diff --git a/supabase/migrations/20251227_audit_log_universal.sql b/supabase/migrations/20251227_audit_log_universal.sql index bcb0f02ca..c933b8b02 100644 --- a/supabase/migrations/20251227_audit_log_universal.sql +++ b/supabase/migrations/20251227_audit_log_universal.sql @@ -16,11 +16,11 @@ CREATE TABLE IF NOT EXISTS audit_log ( created_at TIMESTAMPTZ DEFAULT NOW() ); -CREATE INDEX idx_audit_log_table ON audit_log(table_name); -CREATE INDEX idx_audit_log_record ON audit_log(record_id); -CREATE INDEX idx_audit_log_user ON audit_log(user_id); -CREATE INDEX idx_audit_log_created ON audit_log(created_at DESC); -CREATE INDEX idx_audit_log_action ON audit_log(action); +CREATE INDEX IF NOT EXISTS idx_audit_log_table ON audit_log(table_name); +CREATE INDEX IF NOT EXISTS idx_audit_log_record ON audit_log(record_id); +CREATE INDEX IF NOT EXISTS idx_audit_log_user ON audit_log(user_id); +CREATE INDEX IF NOT EXISTS idx_audit_log_created ON audit_log(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_audit_log_action ON audit_log(action); -- 2. Função genérica de auditoria CREATE OR REPLACE FUNCTION audit_trigger_func() @@ -115,6 +115,7 @@ CREATE TRIGGER audit_sales_goals ALTER TABLE audit_log ENABLE ROW LEVEL SECURITY; -- Admins podem ver tudo +DROP POLICY IF EXISTS "Admins can view all audit logs" ON audit_log; CREATE POLICY "Admins can view all audit logs" ON audit_log FOR SELECT @@ -127,6 +128,7 @@ CREATE POLICY "Admins can view all audit logs" ); -- Users podem ver apenas seus próprios registros +DROP POLICY IF EXISTS "Users can view own audit logs" ON audit_log; CREATE POLICY "Users can view own audit logs" ON audit_log FOR SELECT diff --git a/supabase/migrations/20251227_product_price_history.sql b/supabase/migrations/20251227_product_price_history.sql index 3d7b908a6..bfc37cacf 100644 --- a/supabase/migrations/20251227_product_price_history.sql +++ b/supabase/migrations/20251227_product_price_history.sql @@ -7,8 +7,8 @@ CREATE TABLE IF NOT EXISTS product_price_history ( changed_at TIMESTAMPTZ DEFAULT NOW() ); -CREATE INDEX idx_price_history_product ON product_price_history(product_id); -CREATE INDEX idx_price_history_date ON product_price_history(changed_at DESC); +CREATE INDEX IF NOT EXISTS idx_price_history_product ON product_price_history(product_id); +CREATE INDEX IF NOT EXISTS idx_price_history_date ON product_price_history(changed_at DESC); CREATE OR REPLACE FUNCTION log_price_change() RETURNS TRIGGER AS $$ diff --git a/supabase/migrations/20251227_push_subscriptions.sql b/supabase/migrations/20251227_push_subscriptions.sql index a3267a048..fd0971d69 100644 --- a/supabase/migrations/20251227_push_subscriptions.sql +++ b/supabase/migrations/20251227_push_subscriptions.sql @@ -13,11 +13,12 @@ CREATE TABLE IF NOT EXISTS push_subscriptions ( is_active BOOLEAN DEFAULT TRUE ); -CREATE INDEX idx_push_subscriptions_user ON push_subscriptions(user_id); -CREATE INDEX idx_push_subscriptions_active ON push_subscriptions(is_active); +CREATE INDEX IF NOT EXISTS idx_push_subscriptions_user ON push_subscriptions(user_id); +CREATE INDEX IF NOT EXISTS idx_push_subscriptions_active ON push_subscriptions(is_active); ALTER TABLE push_subscriptions ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can manage own subscriptions" ON push_subscriptions; CREATE POLICY "Users can manage own subscriptions" ON push_subscriptions FOR ALL diff --git a/supabase/migrations/20251227_quote_comments.sql b/supabase/migrations/20251227_quote_comments.sql index 499c6ca87..d93ffae50 100644 --- a/supabase/migrations/20251227_quote_comments.sql +++ b/supabase/migrations/20251227_quote_comments.sql @@ -8,11 +8,12 @@ CREATE TABLE IF NOT EXISTS quote_comments ( updated_at TIMESTAMPTZ DEFAULT NOW() ); -CREATE INDEX idx_quote_comments_quote ON quote_comments(quote_id); -CREATE INDEX idx_quote_comments_created ON quote_comments(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_quote_comments_quote ON quote_comments(quote_id); +CREATE INDEX IF NOT EXISTS idx_quote_comments_created ON quote_comments(created_at DESC); ALTER TABLE quote_comments ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view comments on accessible quotes" ON accessible; CREATE POLICY "Users can view comments on accessible quotes" ON quote_comments FOR SELECT USING ( @@ -23,6 +24,7 @@ CREATE POLICY "Users can view comments on accessible quotes" ) ); +DROP POLICY IF EXISTS "Users can create comments" ON quote_comments; CREATE POLICY "Users can create comments" ON quote_comments FOR INSERT WITH CHECK (auth.uid() = user_id); diff --git a/supabase/migrations/20251227_sync_jobs.sql b/supabase/migrations/20251227_sync_jobs.sql index 75461fb00..f94ba6773 100644 --- a/supabase/migrations/20251227_sync_jobs.sql +++ b/supabase/migrations/20251227_sync_jobs.sql @@ -13,8 +13,9 @@ CREATE TABLE IF NOT EXISTS sync_jobs ( created_at TIMESTAMPTZ DEFAULT NOW() ); -CREATE INDEX idx_sync_jobs_status ON sync_jobs(status); -CREATE INDEX idx_sync_jobs_created ON sync_jobs(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_sync_jobs_status ON sync_jobs(status); +CREATE INDEX IF NOT EXISTS idx_sync_jobs_created ON sync_jobs(created_at DESC); ALTER TABLE sync_jobs ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view own jobs" ON sync_jobs; CREATE POLICY "Users can view own jobs" ON sync_jobs FOR SELECT USING (auth.uid() = created_by); diff --git a/supabase/migrations/20251227_user_filter_presets.sql b/supabase/migrations/20251227_user_filter_presets.sql index 0e50ce2c6..2b79d4802 100644 --- a/supabase/migrations/20251227_user_filter_presets.sql +++ b/supabase/migrations/20251227_user_filter_presets.sql @@ -8,11 +8,12 @@ CREATE TABLE IF NOT EXISTS user_filter_presets ( created_at TIMESTAMPTZ DEFAULT NOW() ); -CREATE INDEX idx_user_filters_user ON user_filter_presets(user_id); -CREATE INDEX idx_user_filters_context ON user_filter_presets(context); +CREATE INDEX IF NOT EXISTS idx_user_filters_user ON user_filter_presets(user_id); +CREATE INDEX IF NOT EXISTS idx_user_filters_context ON user_filter_presets(context); ALTER TABLE user_filter_presets ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users manage own filters" ON user_filter_presets; CREATE POLICY "Users manage own filters" ON user_filter_presets FOR ALL USING (auth.uid() = user_id); diff --git a/supabase/migrations/20251228_analytics_events.sql b/supabase/migrations/20251228_analytics_events.sql index a9563a1a0..fc9dd1624 100644 --- a/supabase/migrations/20251228_analytics_events.sql +++ b/supabase/migrations/20251228_analytics_events.sql @@ -2,18 +2,19 @@ -- Description: Analytics tracking -- Created: 2025-12-28 -CREATE TABLE analytics_events ( +CREATE TABLE IF NOT EXISTS analytics_events ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); -- Indexes -CREATE INDEX idx_analytics_events_created ON analytics_events(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_analytics_events_created ON analytics_events(created_at DESC); -- RLS ALTER TABLE analytics_events ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view analytics_events" ON analytics_events; CREATE POLICY "Users can view analytics_events" ON analytics_events FOR SELECT USING (true); diff --git a/supabase/migrations/20251228_audit_trail.sql b/supabase/migrations/20251228_audit_trail.sql index 8e70998b3..5f8303a0b 100644 --- a/supabase/migrations/20251228_audit_trail.sql +++ b/supabase/migrations/20251228_audit_trail.sql @@ -2,18 +2,19 @@ -- Description: Audit logging -- Created: 2025-12-28 -CREATE TABLE audit_trail ( +CREATE TABLE IF NOT EXISTS audit_trail ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); -- Indexes -CREATE INDEX idx_audit_trail_created ON audit_trail(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_audit_trail_created ON audit_trail(created_at DESC); -- RLS ALTER TABLE audit_trail ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view audit_trail" ON audit_trail; CREATE POLICY "Users can view audit_trail" ON audit_trail FOR SELECT USING (true); diff --git a/supabase/migrations/20251228_cache_entries.sql b/supabase/migrations/20251228_cache_entries.sql index d91e9c602..ea969441b 100644 --- a/supabase/migrations/20251228_cache_entries.sql +++ b/supabase/migrations/20251228_cache_entries.sql @@ -2,18 +2,19 @@ -- Description: Cache storage -- Created: 2025-12-28 -CREATE TABLE cache_entries ( +CREATE TABLE IF NOT EXISTS cache_entries ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); -- Indexes -CREATE INDEX idx_cache_entries_created ON cache_entries(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_cache_entries_created ON cache_entries(created_at DESC); -- RLS ALTER TABLE cache_entries ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view cache_entries" ON cache_entries; CREATE POLICY "Users can view cache_entries" ON cache_entries FOR SELECT USING (true); diff --git a/supabase/migrations/20251228_feature_flags.sql b/supabase/migrations/20251228_feature_flags.sql index 66edc3f9f..7e1bfeb0e 100644 --- a/supabase/migrations/20251228_feature_flags.sql +++ b/supabase/migrations/20251228_feature_flags.sql @@ -2,18 +2,19 @@ -- Description: Feature toggles -- Created: 2025-12-28 -CREATE TABLE feature_flags ( +CREATE TABLE IF NOT EXISTS feature_flags ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); -- Indexes -CREATE INDEX idx_feature_flags_created ON feature_flags(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_feature_flags_created ON feature_flags(created_at DESC); -- RLS ALTER TABLE feature_flags ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view feature_flags" ON feature_flags; CREATE POLICY "Users can view feature_flags" ON feature_flags FOR SELECT USING (true); diff --git a/supabase/migrations/20251228_optimization_logs.sql b/supabase/migrations/20251228_optimization_logs.sql index a5b1db08a..fd81ed522 100644 --- a/supabase/migrations/20251228_optimization_logs.sql +++ b/supabase/migrations/20251228_optimization_logs.sql @@ -2,18 +2,19 @@ -- Description: Performance logs -- Created: 2025-12-28 -CREATE TABLE optimization_logs ( +CREATE TABLE IF NOT EXISTS optimization_logs ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); -- Indexes -CREATE INDEX idx_optimization_logs_created ON optimization_logs(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_optimization_logs_created ON optimization_logs(created_at DESC); -- RLS ALTER TABLE optimization_logs ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view optimization_logs" ON optimization_logs; CREATE POLICY "Users can view optimization_logs" ON optimization_logs FOR SELECT USING (true); diff --git a/supabase/migrations/20251228_rate_limits.sql b/supabase/migrations/20251228_rate_limits.sql index c651c4b02..017df0068 100644 --- a/supabase/migrations/20251228_rate_limits.sql +++ b/supabase/migrations/20251228_rate_limits.sql @@ -2,18 +2,19 @@ -- Description: API rate limits -- Created: 2025-12-28 -CREATE TABLE rate_limits ( +CREATE TABLE IF NOT EXISTS rate_limits ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); -- Indexes -CREATE INDEX idx_rate_limits_created ON rate_limits(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_rate_limits_created ON rate_limits(created_at DESC); -- RLS ALTER TABLE rate_limits ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view rate_limits" ON rate_limits; CREATE POLICY "Users can view rate_limits" ON rate_limits FOR SELECT USING (true); diff --git a/supabase/migrations/20251228_redis_config.sql b/supabase/migrations/20251228_redis_config.sql index bbae1c90a..824ef660e 100644 --- a/supabase/migrations/20251228_redis_config.sql +++ b/supabase/migrations/20251228_redis_config.sql @@ -2,18 +2,19 @@ -- Description: Redis configuration -- Created: 2025-12-28 -CREATE TABLE redis_config ( +CREATE TABLE IF NOT EXISTS redis_config ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); -- Indexes -CREATE INDEX idx_redis_config_created ON redis_config(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_redis_config_created ON redis_config(created_at DESC); -- RLS ALTER TABLE redis_config ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view redis_config" ON redis_config; CREATE POLICY "Users can view redis_config" ON redis_config FOR SELECT USING (true); diff --git a/supabase/migrations/20251228_template_versions.sql b/supabase/migrations/20251228_template_versions.sql index 533ace7f6..e41af3532 100644 --- a/supabase/migrations/20251228_template_versions.sql +++ b/supabase/migrations/20251228_template_versions.sql @@ -2,18 +2,19 @@ -- Description: Template versioning -- Created: 2025-12-28 -CREATE TABLE template_versions ( +CREATE TABLE IF NOT EXISTS template_versions ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); -- Indexes -CREATE INDEX idx_template_versions_created ON template_versions(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_template_versions_created ON template_versions(created_at DESC); -- RLS ALTER TABLE template_versions ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view template_versions" ON template_versions; CREATE POLICY "Users can view template_versions" ON template_versions FOR SELECT USING (true); diff --git a/supabase/migrations/20251228_two_factor_secrets.sql b/supabase/migrations/20251228_two_factor_secrets.sql index ba9a44e1c..bb2b5d3a2 100644 --- a/supabase/migrations/20251228_two_factor_secrets.sql +++ b/supabase/migrations/20251228_two_factor_secrets.sql @@ -2,18 +2,19 @@ -- Description: 2FA secrets -- Created: 2025-12-28 -CREATE TABLE two_factor_secrets ( +CREATE TABLE IF NOT EXISTS two_factor_secrets ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); -- Indexes -CREATE INDEX idx_two_factor_secrets_created ON two_factor_secrets(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_two_factor_secrets_created ON two_factor_secrets(created_at DESC); -- RLS ALTER TABLE two_factor_secrets ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view two_factor_secrets" ON two_factor_secrets; CREATE POLICY "Users can view two_factor_secrets" ON two_factor_secrets FOR SELECT USING (true); diff --git a/supabase/migrations/20251228_websocket_sessions.sql b/supabase/migrations/20251228_websocket_sessions.sql index 973b6d4af..bebc5ee9f 100644 --- a/supabase/migrations/20251228_websocket_sessions.sql +++ b/supabase/migrations/20251228_websocket_sessions.sql @@ -2,18 +2,19 @@ -- Description: WebSocket sessions -- Created: 2025-12-28 -CREATE TABLE websocket_sessions ( +CREATE TABLE IF NOT EXISTS websocket_sessions ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW() ); -- Indexes -CREATE INDEX idx_websocket_sessions_created ON websocket_sessions(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_websocket_sessions_created ON websocket_sessions(created_at DESC); -- RLS ALTER TABLE websocket_sessions ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view websocket_sessions" ON websocket_sessions; CREATE POLICY "Users can view websocket_sessions" ON websocket_sessions FOR SELECT USING (true); diff --git a/supabase/migrations/20251231023800_2b909a8a-cd0f-484e-8abf-bc0656fe3b54.sql b/supabase/migrations/20251231023800_2b909a8a-cd0f-484e-8abf-bc0656fe3b54.sql index 1ddfa8830..cb124b771 100644 --- a/supabase/migrations/20251231023800_2b909a8a-cd0f-484e-8abf-bc0656fe3b54.sql +++ b/supabase/migrations/20251231023800_2b909a8a-cd0f-484e-8abf-bc0656fe3b54.sql @@ -24,7 +24,7 @@ BEGIN AND table_name = 'profiles' AND column_name = 'role_id' ) THEN - ALTER TABLE public.profiles ADD COLUMN role_id UUID REFERENCES public.roles(id); + ALTER TABLE public.profiles ADD COLUMN IF NOT EXISTS role_id UUID REFERENCES public.roles(id); END IF; END $$; @@ -37,11 +37,13 @@ WHERE role_id IS NULL; ALTER TABLE public.roles ENABLE ROW LEVEL SECURITY; -- Policies para roles +DROP POLICY IF EXISTS "Roles are viewable by authenticated users" ON public.roles; CREATE POLICY "Roles are viewable by authenticated users" ON public.roles FOR SELECT USING (auth.role() = 'authenticated'); +DROP POLICY IF EXISTS "Only admins can manage roles" ON public.roles; CREATE POLICY "Only admins can manage roles" ON public.roles FOR ALL diff --git a/supabase/migrations/20251231024259_526ec13a-dacb-4a65-a724-61688978e5fb.sql b/supabase/migrations/20251231024259_526ec13a-dacb-4a65-a724-61688978e5fb.sql index 1ab315eea..32011a6ac 100644 --- a/supabase/migrations/20251231024259_526ec13a-dacb-4a65-a724-61688978e5fb.sql +++ b/supabase/migrations/20251231024259_526ec13a-dacb-4a65-a724-61688978e5fb.sql @@ -17,12 +17,14 @@ ALTER TABLE public.password_reset_requests ENABLE ROW LEVEL SECURITY; -- Políticas RLS -- Qualquer pessoa pode criar uma solicitação (não autenticado) +DROP POLICY IF EXISTS "Anyone can create password reset request" ON public.password_reset_requests; CREATE POLICY "Anyone can create password reset request" ON public.password_reset_requests FOR INSERT WITH CHECK (true); -- Gestores e admins podem ver todas as solicitações +DROP POLICY IF EXISTS "Managers and admins can view all requests" ON public.password_reset_requests; CREATE POLICY "Managers and admins can view all requests" ON public.password_reset_requests FOR SELECT @@ -36,6 +38,7 @@ USING ( ); -- Gestores e admins podem atualizar (aprovar/rejeitar) +DROP POLICY IF EXISTS "Managers and admins can update requests" ON public.password_reset_requests; CREATE POLICY "Managers and admins can update requests" ON public.password_reset_requests FOR UPDATE diff --git a/supabase/migrations/20251231024837_c924e1c3-b77f-4076-9cdc-195effdf6ea2.sql b/supabase/migrations/20251231024837_c924e1c3-b77f-4076-9cdc-195effdf6ea2.sql index d851f8e4a..87d17602f 100644 --- a/supabase/migrations/20251231024837_c924e1c3-b77f-4076-9cdc-195effdf6ea2.sql +++ b/supabase/migrations/20251231024837_c924e1c3-b77f-4076-9cdc-195effdf6ea2.sql @@ -1,5 +1,5 @@ -- Tabela para armazenar configurações 2FA dos usuários -CREATE TABLE public.user_2fa_settings ( +CREATE TABLE IF NOT EXISTS public.user_2fa_settings ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID NOT NULL UNIQUE, totp_secret TEXT, @@ -11,7 +11,7 @@ CREATE TABLE public.user_2fa_settings ( ); -- Tabela para IPs permitidos por usuário -CREATE TABLE public.user_allowed_ips ( +CREATE TABLE IF NOT EXISTS public.user_allowed_ips ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID NOT NULL, ip_address TEXT NOT NULL, @@ -23,7 +23,7 @@ CREATE TABLE public.user_allowed_ips ( ); -- Tabela para logs de tentativas de login -CREATE TABLE public.login_attempts ( +CREATE TABLE IF NOT EXISTS public.login_attempts ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID, email TEXT NOT NULL, @@ -40,35 +40,42 @@ ALTER TABLE public.user_allowed_ips ENABLE ROW LEVEL SECURITY; ALTER TABLE public.login_attempts ENABLE ROW LEVEL SECURITY; -- Policies para user_2fa_settings +DROP POLICY IF EXISTS "Users can view their own 2FA settings" ON public.user_2fa_settings; CREATE POLICY "Users can view their own 2FA settings" ON public.user_2fa_settings FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can manage their own 2FA settings" ON public.user_2fa_settings; CREATE POLICY "Users can manage their own 2FA settings" ON public.user_2fa_settings FOR ALL USING (auth.uid() = user_id) WITH CHECK (auth.uid() = user_id); -- Policies para user_allowed_ips +DROP POLICY IF EXISTS "Users can view their own allowed IPs" ON public.user_allowed_ips; CREATE POLICY "Users can view their own allowed IPs" ON public.user_allowed_ips FOR SELECT USING (auth.uid() = user_id OR has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Users can manage their own allowed IPs" ON public.user_allowed_ips; CREATE POLICY "Users can manage their own allowed IPs" ON public.user_allowed_ips FOR ALL USING (auth.uid() = user_id OR has_role(auth.uid(), 'admin'::app_role)) WITH CHECK (auth.uid() = user_id OR has_role(auth.uid(), 'admin'::app_role)); -- Policies para login_attempts +DROP POLICY IF EXISTS "Users can view their own login attempts" ON public.login_attempts; CREATE POLICY "Users can view their own login attempts" ON public.login_attempts FOR SELECT USING (auth.uid() = user_id OR has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Service can create login attempts" ON public.login_attempts; CREATE POLICY "Service can create login attempts" ON public.login_attempts FOR INSERT WITH CHECK (true); -- Função para atualizar updated_at +DROP TRIGGER IF EXISTS update_user_2fa_settings_updated_at ON public.user_2fa_settings; CREATE TRIGGER update_user_2fa_settings_updated_at BEFORE UPDATE ON public.user_2fa_settings FOR EACH ROW diff --git a/supabase/migrations/20251231121324_9bfed8fc-56ff-45e4-8175-e1bd0bb0f72f.sql b/supabase/migrations/20251231121324_9bfed8fc-56ff-45e4-8175-e1bd0bb0f72f.sql index d3bbcb42c..4f3256d72 100644 --- a/supabase/migrations/20251231121324_9bfed8fc-56ff-45e4-8175-e1bd0bb0f72f.sql +++ b/supabase/migrations/20251231121324_9bfed8fc-56ff-45e4-8175-e1bd0bb0f72f.sql @@ -1,5 +1,5 @@ --- Create table to store known devices per user -CREATE TABLE public.user_known_devices ( +-- CREATE TABLE IF NOT EXISTS to store known devices per user +CREATE TABLE IF NOT EXISTS public.user_known_devices ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL, device_fingerprint TEXT NOT NULL, @@ -16,8 +16,8 @@ CREATE TABLE public.user_known_devices ( UNIQUE(user_id, device_fingerprint) ); --- Create table for device login notifications -CREATE TABLE public.device_login_notifications ( +-- CREATE TABLE IF NOT EXISTS for device login notifications +CREATE TABLE IF NOT EXISTS public.device_login_notifications ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL, device_id UUID REFERENCES public.user_known_devices(id) ON DELETE CASCADE, @@ -34,37 +34,43 @@ ALTER TABLE public.user_known_devices ENABLE ROW LEVEL SECURITY; ALTER TABLE public.device_login_notifications ENABLE ROW LEVEL SECURITY; -- RLS Policies for user_known_devices +DROP POLICY IF EXISTS "Users can view their own devices" ON public.user_known_devices; CREATE POLICY "Users can view their own devices" ON public.user_known_devices FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can insert their own devices" ON public.user_known_devices; CREATE POLICY "Users can insert their own devices" ON public.user_known_devices FOR INSERT WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can update their own devices" ON public.user_known_devices; CREATE POLICY "Users can update their own devices" ON public.user_known_devices FOR UPDATE USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can delete their own devices" ON public.user_known_devices; CREATE POLICY "Users can delete their own devices" ON public.user_known_devices FOR DELETE USING (auth.uid() = user_id); -- RLS Policies for device_login_notifications +DROP POLICY IF EXISTS "Users can view their own notifications" ON public.device_login_notifications; CREATE POLICY "Users can view their own notifications" ON public.device_login_notifications FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "System can insert notifications" ON public.device_login_notifications; CREATE POLICY "System can insert notifications" ON public.device_login_notifications FOR INSERT WITH CHECK (true); --- Create index for faster lookups -CREATE INDEX idx_user_known_devices_user_fingerprint ON public.user_known_devices(user_id, device_fingerprint); -CREATE INDEX idx_user_known_devices_user_ip ON public.user_known_devices(user_id, ip_address); \ No newline at end of file +-- CREATE INDEX IF NOT EXISTS for faster lookups +CREATE INDEX IF NOT EXISTS idx_user_known_devices_user_fingerprint ON public.user_known_devices(user_id, device_fingerprint); +CREATE INDEX IF NOT EXISTS idx_user_known_devices_user_ip ON public.user_known_devices(user_id, ip_address); \ No newline at end of file diff --git a/supabase/migrations/20251231124614_527fd53c-cfd4-4106-b454-fdc2ed3a708e.sql b/supabase/migrations/20251231124614_527fd53c-cfd4-4106-b454-fdc2ed3a708e.sql index 9e187c865..3f6403554 100644 --- a/supabase/migrations/20251231124614_527fd53c-cfd4-4106-b454-fdc2ed3a708e.sql +++ b/supabase/migrations/20251231124614_527fd53c-cfd4-4106-b454-fdc2ed3a708e.sql @@ -1,5 +1,5 @@ --- Create table to store WebAuthn/Passkey credentials -CREATE TABLE public.user_passkeys ( +-- CREATE TABLE IF NOT EXISTS to store WebAuthn/Passkey credentials +CREATE TABLE IF NOT EXISTS public.user_passkeys ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID NOT NULL, credential_id TEXT NOT NULL UNIQUE, @@ -15,26 +15,30 @@ CREATE TABLE public.user_passkeys ( ALTER TABLE public.user_passkeys ENABLE ROW LEVEL SECURITY; -- RLS policies +DROP POLICY IF EXISTS "Users can view their own passkeys" ON public.user_passkeys; CREATE POLICY "Users can view their own passkeys" ON public.user_passkeys FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can create their own passkeys" ON public.user_passkeys; CREATE POLICY "Users can create their own passkeys" ON public.user_passkeys FOR INSERT WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can update their own passkeys" ON public.user_passkeys; CREATE POLICY "Users can update their own passkeys" ON public.user_passkeys FOR UPDATE USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can delete their own passkeys" ON public.user_passkeys; CREATE POLICY "Users can delete their own passkeys" ON public.user_passkeys FOR DELETE USING (auth.uid() = user_id); -- Index for faster lookups -CREATE INDEX idx_user_passkeys_user_id ON public.user_passkeys(user_id); -CREATE INDEX idx_user_passkeys_credential_id ON public.user_passkeys(credential_id); \ No newline at end of file +CREATE INDEX IF NOT EXISTS idx_user_passkeys_user_id ON public.user_passkeys(user_id); +CREATE INDEX IF NOT EXISTS idx_user_passkeys_credential_id ON public.user_passkeys(credential_id); \ No newline at end of file diff --git a/supabase/migrations/20251231130817_8aeff4f3-66df-41e0-a380-c7ffe3c03f96.sql b/supabase/migrations/20251231130817_8aeff4f3-66df-41e0-a380-c7ffe3c03f96.sql index ad1268e16..28aa42d66 100644 --- a/supabase/migrations/20251231130817_8aeff4f3-66df-41e0-a380-c7ffe3c03f96.sql +++ b/supabase/migrations/20251231130817_8aeff4f3-66df-41e0-a380-c7ffe3c03f96.sql @@ -1,5 +1,5 @@ -- Tabela para configurações de bloqueio geográfico (países permitidos) -CREATE TABLE public.geo_allowed_countries ( +CREATE TABLE IF NOT EXISTS public.geo_allowed_countries ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, country_code CHAR(2) NOT NULL UNIQUE, country_name TEXT NOT NULL, @@ -12,11 +12,13 @@ CREATE TABLE public.geo_allowed_countries ( ALTER TABLE public.geo_allowed_countries ENABLE ROW LEVEL SECURITY; -- Políticas RLS +DROP POLICY IF EXISTS "Anyone can view allowed countries" ON public.geo_allowed_countries; CREATE POLICY "Anyone can view allowed countries" ON public.geo_allowed_countries FOR SELECT USING (true); +DROP POLICY IF EXISTS "Admins can manage allowed countries" ON public.geo_allowed_countries; CREATE POLICY "Admins can manage allowed countries" ON public.geo_allowed_countries FOR ALL @@ -24,7 +26,7 @@ USING (has_role(auth.uid(), 'admin'::app_role)) WITH CHECK (has_role(auth.uid(), 'admin'::app_role)); -- Tabela para configurações globais de segurança -CREATE TABLE public.security_settings ( +CREATE TABLE IF NOT EXISTS public.security_settings ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, setting_key TEXT NOT NULL UNIQUE, setting_value JSONB NOT NULL DEFAULT '{}'::jsonb, @@ -37,11 +39,13 @@ CREATE TABLE public.security_settings ( ALTER TABLE public.security_settings ENABLE ROW LEVEL SECURITY; -- Políticas RLS +DROP POLICY IF EXISTS "Anyone can view security settings" ON public.security_settings; CREATE POLICY "Anyone can view security settings" ON public.security_settings FOR SELECT USING (true); +DROP POLICY IF EXISTS "Admins can manage security settings" ON public.security_settings; CREATE POLICY "Admins can manage security settings" ON public.security_settings FOR ALL diff --git a/supabase/migrations/20260107013155_66a04f90-a966-424c-a356-15f40b5f08b7.sql b/supabase/migrations/20260107013155_66a04f90-a966-424c-a356-15f40b5f08b7.sql index d2d248334..a46715410 100644 --- a/supabase/migrations/20260107013155_66a04f90-a966-424c-a356-15f40b5f08b7.sql +++ b/supabase/migrations/20260107013155_66a04f90-a966-424c-a356-15f40b5f08b7.sql @@ -1,5 +1,5 @@ -- Tabela para rascunhos de mockup (auto-save híbrido) -CREATE TABLE public.mockup_drafts ( +CREATE TABLE IF NOT EXISTS public.mockup_drafts ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID NOT NULL, draft_key VARCHAR(50) NOT NULL DEFAULT 'default', @@ -20,31 +20,36 @@ CREATE TABLE public.mockup_drafts ( ALTER TABLE public.mockup_drafts ENABLE ROW LEVEL SECURITY; -- RLS policies - cada usuário só vê/edita seus próprios rascunhos +DROP POLICY IF EXISTS "Users can view their own mockup drafts" ON public.mockup_drafts; CREATE POLICY "Users can view their own mockup drafts" ON public.mockup_drafts FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can create their own mockup drafts" ON public.mockup_drafts; CREATE POLICY "Users can create their own mockup drafts" ON public.mockup_drafts FOR INSERT WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can update their own mockup drafts" ON public.mockup_drafts; CREATE POLICY "Users can update their own mockup drafts" ON public.mockup_drafts FOR UPDATE USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can delete their own mockup drafts" ON public.mockup_drafts; CREATE POLICY "Users can delete their own mockup drafts" ON public.mockup_drafts FOR DELETE USING (auth.uid() = user_id); -- Trigger para updated_at +DROP TRIGGER IF EXISTS update_mockup_drafts_updated_at ON public.mockup_drafts; CREATE TRIGGER update_mockup_drafts_updated_at BEFORE UPDATE ON public.mockup_drafts FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); -- Índice para busca rápida -CREATE INDEX idx_mockup_drafts_user ON public.mockup_drafts(user_id, draft_key); \ No newline at end of file +CREATE INDEX IF NOT EXISTS idx_mockup_drafts_user ON public.mockup_drafts(user_id, draft_key); \ No newline at end of file diff --git a/supabase/migrations/20260107141013_b8f1929c-c9b6-4372-8f04-d059889cf708.sql b/supabase/migrations/20260107141013_b8f1929c-c9b6-4372-8f04-d059889cf708.sql index 7a09eeb3a..7e452cb92 100644 --- a/supabase/migrations/20260107141013_b8f1929c-c9b6-4372-8f04-d059889cf708.sql +++ b/supabase/migrations/20260107141013_b8f1929c-c9b6-4372-8f04-d059889cf708.sql @@ -8,6 +8,7 @@ CREATE POLICY "Users can view their own onboarding" ON public.user_onboarding FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can manage their own onboarding" ON public.user_onboarding; CREATE POLICY "Users can manage their own onboarding" ON public.user_onboarding FOR ALL USING (auth.uid() = user_id) diff --git a/supabase/migrations/20260108014732_22444765-aa2c-47b2-afb4-f942541d622d.sql b/supabase/migrations/20260108014732_22444765-aa2c-47b2-afb4-f942541d622d.sql index e33efcd25..725881257 100644 --- a/supabase/migrations/20260108014732_22444765-aa2c-47b2-afb4-f942541d622d.sql +++ b/supabase/migrations/20260108014732_22444765-aa2c-47b2-afb4-f942541d622d.sql @@ -4,7 +4,7 @@ -- ============================================= -- 1. TABELA PRINCIPAL: EMPRESAS (CLIENTES) -CREATE TABLE public.companies ( +CREATE TABLE IF NOT EXISTS public.companies ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, -- Dados Cadastrais @@ -71,7 +71,7 @@ CREATE TABLE public.companies ( ); -- 2. TABELA: CONTATOS DA EMPRESA -CREATE TABLE public.company_contacts ( +CREATE TABLE IF NOT EXISTS public.company_contacts ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, company_id UUID NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE, @@ -112,7 +112,7 @@ CREATE TABLE public.company_contacts ( ); -- 3. TABELA: TELEFONES DOS CONTATOS -CREATE TABLE public.contact_phones ( +CREATE TABLE IF NOT EXISTS public.contact_phones ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, contact_id UUID NOT NULL REFERENCES public.company_contacts(id) ON DELETE CASCADE, @@ -125,7 +125,7 @@ CREATE TABLE public.contact_phones ( ); -- 4. TABELA: EMAILS DOS CONTATOS -CREATE TABLE public.contact_emails ( +CREATE TABLE IF NOT EXISTS public.contact_emails ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, contact_id UUID NOT NULL REFERENCES public.company_contacts(id) ON DELETE CASCADE, @@ -137,7 +137,7 @@ CREATE TABLE public.contact_emails ( ); -- 5. TABELA: ENDEREÇOS DE ENTREGA (múltiplos por empresa) -CREATE TABLE public.company_addresses ( +CREATE TABLE IF NOT EXISTS public.company_addresses ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, company_id UUID NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE, @@ -165,21 +165,21 @@ CREATE TABLE public.company_addresses ( -- ============================================= -- ÍNDICES PARA PERFORMANCE -- ============================================= -CREATE INDEX idx_companies_cnpj ON public.companies(cnpj); -CREATE INDEX idx_companies_nome_fantasia ON public.companies(nome_fantasia); -CREATE INDEX idx_companies_razao_social ON public.companies(razao_social); -CREATE INDEX idx_companies_status ON public.companies(status); -CREATE INDEX idx_companies_ramo ON public.companies(ramo); -CREATE INDEX idx_companies_responsavel ON public.companies(responsavel_id); -CREATE INDEX idx_companies_bitrix ON public.companies(bitrix_id); +CREATE INDEX IF NOT EXISTS idx_companies_cnpj ON public.companies(cnpj); +CREATE INDEX IF NOT EXISTS idx_companies_nome_fantasia ON public.companies(nome_fantasia); +CREATE INDEX IF NOT EXISTS idx_companies_razao_social ON public.companies(razao_social); +CREATE INDEX IF NOT EXISTS idx_companies_status ON public.companies(status); +CREATE INDEX IF NOT EXISTS idx_companies_ramo ON public.companies(ramo); +CREATE INDEX IF NOT EXISTS idx_companies_responsavel ON public.companies(responsavel_id); +CREATE INDEX IF NOT EXISTS idx_companies_bitrix ON public.companies(bitrix_id); -CREATE INDEX idx_contacts_company ON public.company_contacts(company_id); -CREATE INDEX idx_contacts_nome ON public.company_contacts(nome); -CREATE INDEX idx_contacts_principal ON public.company_contacts(company_id, is_principal) WHERE is_principal = true; +CREATE INDEX IF NOT EXISTS idx_contacts_company ON public.company_contacts(company_id); +CREATE INDEX IF NOT EXISTS idx_contacts_nome ON public.company_contacts(nome); +CREATE INDEX IF NOT EXISTS idx_contacts_principal ON public.company_contacts(company_id, is_principal) WHERE is_principal = true; -CREATE INDEX idx_phones_contact ON public.contact_phones(contact_id); -CREATE INDEX idx_emails_contact ON public.contact_emails(contact_id); -CREATE INDEX idx_addresses_company ON public.company_addresses(company_id); +CREATE INDEX IF NOT EXISTS idx_phones_contact ON public.contact_phones(contact_id); +CREATE INDEX IF NOT EXISTS idx_emails_contact ON public.contact_emails(contact_id); +CREATE INDEX IF NOT EXISTS idx_addresses_company ON public.company_addresses(company_id); -- ============================================= -- RLS POLICIES @@ -191,58 +191,70 @@ ALTER TABLE public.contact_emails ENABLE ROW LEVEL SECURITY; ALTER TABLE public.company_addresses ENABLE ROW LEVEL SECURITY; -- Companies: Usuários autenticados podem ver, admins podem gerenciar +DROP POLICY IF EXISTS "Authenticated users can view companies" ON public.companies; CREATE POLICY "Authenticated users can view companies" ON public.companies FOR SELECT USING (true); +DROP POLICY IF EXISTS "Admins can manage companies" ON public.companies; CREATE POLICY "Admins can manage companies" ON public.companies FOR ALL USING (has_role(auth.uid(), 'admin'::app_role)) WITH CHECK (has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Sellers can create companies" ON public.companies; CREATE POLICY "Sellers can create companies" ON public.companies FOR INSERT WITH CHECK (auth.uid() IS NOT NULL); +DROP POLICY IF EXISTS "Sellers can update companies" ON public.companies; CREATE POLICY "Sellers can update companies" ON public.companies FOR UPDATE USING (auth.uid() IS NOT NULL); -- Contacts: Herda da empresa +DROP POLICY IF EXISTS "Authenticated users can view contacts" ON public.company_contacts; CREATE POLICY "Authenticated users can view contacts" ON public.company_contacts FOR SELECT USING (true); +DROP POLICY IF EXISTS "Authenticated users can manage contacts" ON public.company_contacts; CREATE POLICY "Authenticated users can manage contacts" ON public.company_contacts FOR ALL USING (auth.uid() IS NOT NULL) WITH CHECK (auth.uid() IS NOT NULL); -- Phones: Herda do contato +DROP POLICY IF EXISTS "Authenticated users can view phones" ON public.contact_phones; CREATE POLICY "Authenticated users can view phones" ON public.contact_phones FOR SELECT USING (true); +DROP POLICY IF EXISTS "Authenticated users can manage phones" ON public.contact_phones; CREATE POLICY "Authenticated users can manage phones" ON public.contact_phones FOR ALL USING (auth.uid() IS NOT NULL) WITH CHECK (auth.uid() IS NOT NULL); -- Emails: Herda do contato +DROP POLICY IF EXISTS "Authenticated users can view emails" ON public.contact_emails; CREATE POLICY "Authenticated users can view emails" ON public.contact_emails FOR SELECT USING (true); +DROP POLICY IF EXISTS "Authenticated users can manage emails" ON public.contact_emails; CREATE POLICY "Authenticated users can manage emails" ON public.contact_emails FOR ALL USING (auth.uid() IS NOT NULL) WITH CHECK (auth.uid() IS NOT NULL); -- Addresses: Herda da empresa +DROP POLICY IF EXISTS "Authenticated users can view addresses" ON public.company_addresses; CREATE POLICY "Authenticated users can view addresses" ON public.company_addresses FOR SELECT USING (true); +DROP POLICY IF EXISTS "Authenticated users can manage addresses" ON public.company_addresses; CREATE POLICY "Authenticated users can manage addresses" ON public.company_addresses FOR ALL USING (auth.uid() IS NOT NULL) @@ -251,16 +263,19 @@ CREATE POLICY "Authenticated users can manage addresses" -- ============================================= -- TRIGGERS PARA UPDATED_AT -- ============================================= +DROP TRIGGER IF EXISTS update_companies_updated_at ON public.companies; CREATE TRIGGER update_companies_updated_at BEFORE UPDATE ON public.companies FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); +DROP TRIGGER IF EXISTS update_company_contacts_updated_at ON public.company_contacts; CREATE TRIGGER update_company_contacts_updated_at BEFORE UPDATE ON public.company_contacts FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); +DROP TRIGGER IF EXISTS update_company_addresses_updated_at ON public.company_addresses; CREATE TRIGGER update_company_addresses_updated_at BEFORE UPDATE ON public.company_addresses FOR EACH ROW diff --git a/supabase/migrations/20260108173818_1d94da3e-0e58-473c-a297-989205f387a8.sql b/supabase/migrations/20260108173818_1d94da3e-0e58-473c-a297-989205f387a8.sql index ccb3ba171..b076e5162 100644 --- a/supabase/migrations/20260108173818_1d94da3e-0e58-473c-a297-989205f387a8.sql +++ b/supabase/migrations/20260108173818_1d94da3e-0e58-473c-a297-989205f387a8.sql @@ -1,5 +1,5 @@ -- Criar tabela para armazenar emojis/ícones das categorias -CREATE TABLE public.category_icons ( +CREATE TABLE IF NOT EXISTS public.category_icons ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, category_name TEXT NOT NULL UNIQUE, icon TEXT NOT NULL DEFAULT '📦', @@ -13,12 +13,14 @@ CREATE TABLE public.category_icons ( ALTER TABLE public.category_icons ENABLE ROW LEVEL SECURITY; -- Policy: Anyone can view category icons +DROP POLICY IF EXISTS "Anyone can view category icons" ON public.category_icons; CREATE POLICY "Anyone can view category icons" ON public.category_icons FOR SELECT USING (true); -- Policy: Admins can manage category icons +DROP POLICY IF EXISTS "Admins can manage category icons" ON public.category_icons; CREATE POLICY "Admins can manage category icons" ON public.category_icons FOR ALL @@ -67,6 +69,7 @@ INSERT INTO public.category_icons (category_name, icon) VALUES ON CONFLICT (category_name) DO UPDATE SET icon = EXCLUDED.icon; -- Trigger para atualizar updated_at +DROP TRIGGER IF EXISTS update_category_icons_updated_at ON public.category_icons; CREATE TRIGGER update_category_icons_updated_at BEFORE UPDATE ON public.category_icons FOR EACH ROW diff --git a/supabase/migrations/20260109125132_c8eb2ca4-378d-455c-b380-0f1b3b55efd6.sql b/supabase/migrations/20260109125132_c8eb2ca4-378d-455c-b380-0f1b3b55efd6.sql index d7ceab628..df5d31b61 100644 --- a/supabase/migrations/20260109125132_c8eb2ca4-378d-455c-b380-0f1b3b55efd6.sql +++ b/supabase/migrations/20260109125132_c8eb2ca4-378d-455c-b380-0f1b3b55efd6.sql @@ -4,7 +4,7 @@ -- ===================================================== -- 1. GRUPOS DE COR (Nível Master - para filtros) -CREATE TABLE public.color_groups ( +CREATE TABLE IF NOT EXISTS public.color_groups ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), name VARCHAR(100) NOT NULL, slug VARCHAR(100) NOT NULL UNIQUE, @@ -17,7 +17,7 @@ CREATE TABLE public.color_groups ( ); -- 2. VARIAÇÕES DE COR (Tons específicos) -CREATE TABLE public.color_variations ( +CREATE TABLE IF NOT EXISTS public.color_variations ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), group_id UUID NOT NULL REFERENCES color_groups(id) ON DELETE CASCADE, name VARCHAR(100) NOT NULL, @@ -32,7 +32,7 @@ CREATE TABLE public.color_variations ( ); -- 3. NUANCES/ACABAMENTOS (independente de cor) -CREATE TABLE public.color_nuances ( +CREATE TABLE IF NOT EXISTS public.color_nuances ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), name VARCHAR(100) NOT NULL, slug VARCHAR(100) NOT NULL UNIQUE, @@ -44,10 +44,10 @@ CREATE TABLE public.color_nuances ( ); -- Índices para performance -CREATE INDEX idx_color_variations_group ON color_variations(group_id); -CREATE INDEX idx_color_groups_active ON color_groups(is_active) WHERE is_active = true; -CREATE INDEX idx_color_variations_active ON color_variations(is_active) WHERE is_active = true; -CREATE INDEX idx_color_nuances_active ON color_nuances(is_active) WHERE is_active = true; +CREATE INDEX IF NOT EXISTS idx_color_variations_group ON color_variations(group_id); +CREATE INDEX IF NOT EXISTS idx_color_groups_active ON color_groups(is_active) WHERE is_active = true; +CREATE INDEX IF NOT EXISTS idx_color_variations_active ON color_variations(is_active) WHERE is_active = true; +CREATE INDEX IF NOT EXISTS idx_color_nuances_active ON color_nuances(is_active) WHERE is_active = true; -- RLS - Todos podem visualizar, apenas admins gerenciam ALTER TABLE color_groups ENABLE ROW LEVEL SECURITY; @@ -55,19 +55,25 @@ ALTER TABLE color_variations ENABLE ROW LEVEL SECURITY; ALTER TABLE color_nuances ENABLE ROW LEVEL SECURITY; -- Políticas de leitura (todos autenticados) +DROP POLICY IF EXISTS "Anyone can view color groups" ON color_groups; CREATE POLICY "Anyone can view color groups" ON color_groups FOR SELECT USING (true); +DROP POLICY IF EXISTS "Anyone can view color variations" ON color_variations; CREATE POLICY "Anyone can view color variations" ON color_variations FOR SELECT USING (true); +DROP POLICY IF EXISTS "Anyone can view color nuances" ON color_nuances; CREATE POLICY "Anyone can view color nuances" ON color_nuances FOR SELECT USING (true); -- Políticas de escrita (apenas admins) +DROP POLICY IF EXISTS "Admins can manage color groups" ON color_groups; CREATE POLICY "Admins can manage color groups" ON color_groups FOR ALL USING (has_role(auth.uid(), 'admin'::app_role)) WITH CHECK (has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Admins can manage color variations" ON color_variations; CREATE POLICY "Admins can manage color variations" ON color_variations FOR ALL USING (has_role(auth.uid(), 'admin'::app_role)) WITH CHECK (has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Admins can manage color nuances" ON color_nuances; CREATE POLICY "Admins can manage color nuances" ON color_nuances FOR ALL USING (has_role(auth.uid(), 'admin'::app_role)) WITH CHECK (has_role(auth.uid(), 'admin'::app_role)); diff --git a/supabase/migrations/20260109154430_b2728cb8-f45f-418c-932f-56d27e5e3a44.sql b/supabase/migrations/20260109154430_b2728cb8-f45f-418c-932f-56d27e5e3a44.sql index 38d44387c..a028246fd 100644 --- a/supabase/migrations/20260109154430_b2728cb8-f45f-418c-932f-56d27e5e3a44.sql +++ b/supabase/migrations/20260109154430_b2728cb8-f45f-418c-932f-56d27e5e3a44.sql @@ -25,13 +25,16 @@ CREATE INDEX IF NOT EXISTS idx_novelties_highlighted ON product_novelties(is_hig ALTER TABLE public.product_novelties ENABLE ROW LEVEL SECURITY; -- Políticas RLS +DROP POLICY IF EXISTS "Anyone can view novelties" ON product_novelties; CREATE POLICY "Anyone can view novelties" ON product_novelties FOR SELECT USING (true); +DROP POLICY IF EXISTS "Admins can manage novelties" ON product_novelties; CREATE POLICY "Admins can manage novelties" ON product_novelties FOR ALL USING (has_role(auth.uid(), 'admin')) WITH CHECK (has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Service can manage novelties" ON product_novelties; CREATE POLICY "Service can manage novelties" ON product_novelties FOR ALL USING (true) WITH CHECK (true); @@ -209,6 +212,7 @@ END; $$; -- Trigger para updated_at +DROP TRIGGER IF EXISTS update_product_novelties_updated_at ON product_novelties; CREATE TRIGGER update_product_novelties_updated_at BEFORE UPDATE ON product_novelties FOR EACH ROW diff --git a/supabase/migrations/20260109202835_4a232f3b-350c-4aa9-ab9e-91f038c72716.sql b/supabase/migrations/20260109202835_4a232f3b-350c-4aa9-ab9e-91f038c72716.sql index ebeefe1a0..4efe5a0d5 100644 --- a/supabase/migrations/20260109202835_4a232f3b-350c-4aa9-ab9e-91f038c72716.sql +++ b/supabase/migrations/20260109202835_4a232f3b-350c-4aa9-ab9e-91f038c72716.sql @@ -1,5 +1,5 @@ -- Tabela de Auditoria para rastrear todas as alterações -CREATE TABLE public.audit_log ( +CREATE TABLE IF NOT EXISTS public.audit_log ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID, action TEXT NOT NULL, @@ -13,27 +13,30 @@ CREATE TABLE public.audit_log ( ); -- Índices para performance nas consultas -CREATE INDEX idx_audit_log_entity ON public.audit_log(entity_type, entity_id); -CREATE INDEX idx_audit_log_user ON public.audit_log(user_id); -CREATE INDEX idx_audit_log_created ON public.audit_log(created_at DESC); -CREATE INDEX idx_audit_log_action ON public.audit_log(action); +CREATE INDEX IF NOT EXISTS idx_audit_log_entity ON public.audit_log(entity_type, entity_id); +CREATE INDEX IF NOT EXISTS idx_audit_log_user ON public.audit_log(user_id); +CREATE INDEX IF NOT EXISTS idx_audit_log_created ON public.audit_log(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_audit_log_action ON public.audit_log(action); -- Enable RLS ALTER TABLE public.audit_log ENABLE ROW LEVEL SECURITY; -- Usuários autenticados podem inserir logs +DROP POLICY IF EXISTS "Authenticated users can insert audit logs" ON public.audit_log; CREATE POLICY "Authenticated users can insert audit logs" ON public.audit_log FOR INSERT WITH CHECK (auth.uid() IS NOT NULL); -- Admin pode ver todos os logs (usando app_role correto) +DROP POLICY IF EXISTS "Admin can view all audit logs" ON public.audit_log; CREATE POLICY "Admin can view all audit logs" ON public.audit_log FOR SELECT USING (has_role(auth.uid(), 'admin'::app_role)); -- Usuários podem ver logs das próprias ações +DROP POLICY IF EXISTS "Users can view their own audit logs" ON public.audit_log; CREATE POLICY "Users can view their own audit logs" ON public.audit_log FOR SELECT diff --git a/supabase/migrations/20260109210025_03cd391c-5ccc-4995-a775-3a820e35dddb.sql b/supabase/migrations/20260109210025_03cd391c-5ccc-4995-a775-3a820e35dddb.sql index d74c07034..fd0ee0258 100644 --- a/supabase/migrations/20260109210025_03cd391c-5ccc-4995-a775-3a820e35dddb.sql +++ b/supabase/migrations/20260109210025_03cd391c-5ccc-4995-a775-3a820e35dddb.sql @@ -7,6 +7,7 @@ ALTER TABLE public.roles ENABLE ROW LEVEL SECURITY; DROP POLICY IF EXISTS "Only admins can manage roles" ON public.roles; -- Admins can manage roles (no self-referencing subqueries) +DROP POLICY IF EXISTS "Admins can manage roles" ON public.roles; CREATE POLICY "Admins can manage roles" ON public.roles FOR ALL diff --git a/supabase/migrations/20260110114755_53a55baf-98ce-41dc-890b-d5ad92035ed1.sql b/supabase/migrations/20260110114755_53a55baf-98ce-41dc-890b-d5ad92035ed1.sql index 67e85be68..030a765dd 100644 --- a/supabase/migrations/20260110114755_53a55baf-98ce-41dc-890b-d5ad92035ed1.sql +++ b/supabase/migrations/20260110114755_53a55baf-98ce-41dc-890b-d5ad92035ed1.sql @@ -8,6 +8,7 @@ DROP POLICY IF EXISTS "Managers and admins can update requests" ON public.passwo -- Recreate policies using has_role() for admin check only -- Since 'manager' is not in app_role enum, we just check for admin +DROP POLICY IF EXISTS "Managers and admins can view all requests" ON public.password_reset_requests; CREATE POLICY "Managers and admins can view all requests" ON public.password_reset_requests FOR SELECT @@ -15,6 +16,7 @@ USING ( has_role(auth.uid(), 'admin'::app_role) ); +DROP POLICY IF EXISTS "Managers and admins can update requests" ON public.password_reset_requests; CREATE POLICY "Managers and admins can update requests" ON public.password_reset_requests FOR UPDATE diff --git a/supabase/migrations/20260110114839_48fa4504-ae04-470a-9359-70e65814a682.sql b/supabase/migrations/20260110114839_48fa4504-ae04-470a-9359-70e65814a682.sql index 8239549ed..a3498336e 100644 --- a/supabase/migrations/20260110114839_48fa4504-ae04-470a-9359-70e65814a682.sql +++ b/supabase/migrations/20260110114839_48fa4504-ae04-470a-9359-70e65814a682.sql @@ -9,6 +9,7 @@ USING ( has_role(auth.uid(), 'admin'::app_role) OR has_role(auth.uid(), 'manager'::app_role) ); +DROP POLICY IF EXISTS "Managers and admins can update requests" ON public.password_reset_requests; CREATE POLICY "Managers and admins can update requests" ON public.password_reset_requests FOR UPDATE diff --git a/supabase/migrations/20260201155941_b988554d-1888-42e4-badc-ae2300cabd1c.sql b/supabase/migrations/20260201155941_b988554d-1888-42e4-badc-ae2300cabd1c.sql index d4a51733a..4636b1f53 100644 --- a/supabase/migrations/20260201155941_b988554d-1888-42e4-badc-ae2300cabd1c.sql +++ b/supabase/migrations/20260201155941_b988554d-1888-42e4-badc-ae2300cabd1c.sql @@ -3,7 +3,7 @@ -- Previsão de reposição de estoque por variação/cor -- ============================================ -CREATE TABLE public.future_stock_entries ( +CREATE TABLE IF NOT EXISTS public.future_stock_entries ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, -- Referência ao produto (ID do banco externo Promobrind) @@ -46,15 +46,16 @@ CREATE TABLE public.future_stock_entries ( ); -- Índices para performance -CREATE INDEX idx_future_stock_product_id ON public.future_stock_entries(product_id); -CREATE INDEX idx_future_stock_expected_date ON public.future_stock_entries(expected_date); -CREATE INDEX idx_future_stock_status ON public.future_stock_entries(status); -CREATE INDEX idx_future_stock_color ON public.future_stock_entries(color_name); +CREATE INDEX IF NOT EXISTS idx_future_stock_product_id ON public.future_stock_entries(product_id); +CREATE INDEX IF NOT EXISTS idx_future_stock_expected_date ON public.future_stock_entries(expected_date); +CREATE INDEX IF NOT EXISTS idx_future_stock_status ON public.future_stock_entries(status); +CREATE INDEX IF NOT EXISTS idx_future_stock_color ON public.future_stock_entries(color_name); -- Enable RLS ALTER TABLE public.future_stock_entries ENABLE ROW LEVEL SECURITY; -- Políticas RLS - todos usuários autenticados podem ver +DROP POLICY IF EXISTS "Authenticated users can view future stock" ON public.future_stock_entries; CREATE POLICY "Authenticated users can view future stock" ON public.future_stock_entries FOR SELECT @@ -62,6 +63,7 @@ TO authenticated USING (true); -- Apenas gerentes e admins podem gerenciar +DROP POLICY IF EXISTS "Managers can manage future stock" ON public.future_stock_entries; CREATE POLICY "Managers can manage future stock" ON public.future_stock_entries FOR ALL @@ -82,6 +84,7 @@ WITH CHECK ( ); -- Vendedores podem inserir +DROP POLICY IF EXISTS "Sellers can insert future stock" ON public.future_stock_entries; CREATE POLICY "Sellers can insert future stock" ON public.future_stock_entries FOR INSERT @@ -95,6 +98,7 @@ WITH CHECK ( ); -- Trigger para updated_at +DROP TRIGGER IF EXISTS update_future_stock_entries_updated_at ON public.future_stock_entries; CREATE TRIGGER update_future_stock_entries_updated_at BEFORE UPDATE ON public.future_stock_entries FOR EACH ROW diff --git a/supabase/migrations/20260208141021_e00ee7e7-b3de-48ee-a167-1d5676607369.sql b/supabase/migrations/20260208141021_e00ee7e7-b3de-48ee-a167-1d5676607369.sql index c87d7eb44..08e0ea23e 100644 --- a/supabase/migrations/20260208141021_e00ee7e7-b3de-48ee-a167-1d5676607369.sql +++ b/supabase/migrations/20260208141021_e00ee7e7-b3de-48ee-a167-1d5676607369.sql @@ -4,6 +4,7 @@ VALUES ('art-files', 'art-files', true) ON CONFLICT (id) DO NOTHING; -- Allow authenticated users to upload art files +DROP POLICY IF EXISTS "Authenticated users can upload art files" ON storage.objects; CREATE POLICY "Authenticated users can upload art files" ON storage.objects FOR INSERT @@ -11,6 +12,7 @@ TO authenticated WITH CHECK (bucket_id = 'art-files' AND auth.uid()::text = (storage.foldername(name))[1]); -- Allow authenticated users to view their own art files +DROP POLICY IF EXISTS "Users can view their own art files" ON storage.objects; CREATE POLICY "Users can view their own art files" ON storage.objects FOR SELECT @@ -18,6 +20,7 @@ TO authenticated USING (bucket_id = 'art-files' AND auth.uid()::text = (storage.foldername(name))[1]); -- Allow public read access for art files (needed for preview/download links) +DROP POLICY IF EXISTS "Public read access for art files" ON storage.objects; CREATE POLICY "Public read access for art files" ON storage.objects FOR SELECT @@ -25,14 +28,15 @@ TO anon USING (bucket_id = 'art-files'); -- Allow users to delete their own art files +DROP POLICY IF EXISTS "Users can delete their own art files" ON storage.objects; CREATE POLICY "Users can delete their own art files" ON storage.objects FOR DELETE TO authenticated USING (bucket_id = 'art-files' AND auth.uid()::text = (storage.foldername(name))[1]); --- Create table to track art file attachments linked to mockup jobs -CREATE TABLE public.art_file_attachments ( +-- CREATE TABLE IF NOT EXISTS to track art file attachments linked to mockup jobs +CREATE TABLE IF NOT EXISTS public.art_file_attachments ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID NOT NULL, product_id TEXT, @@ -49,16 +53,19 @@ CREATE TABLE public.art_file_attachments ( ALTER TABLE public.art_file_attachments ENABLE ROW LEVEL SECURITY; -- RLS policies +DROP POLICY IF EXISTS "Users can view their own art files" ON public.art_file_attachments; CREATE POLICY "Users can view their own art files" ON public.art_file_attachments FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can insert their own art files" ON public.art_file_attachments; CREATE POLICY "Users can insert their own art files" ON public.art_file_attachments FOR INSERT WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can delete their own art files" ON public.art_file_attachments; CREATE POLICY "Users can delete their own art files" ON public.art_file_attachments FOR DELETE diff --git a/supabase/migrations/20260213150148_e751cb5d-5451-473b-9d86-ef8530b19cc3.sql b/supabase/migrations/20260213150148_e751cb5d-5451-473b-9d86-ef8530b19cc3.sql index 9f386477a..3f6db2491 100644 --- a/supabase/migrations/20260213150148_e751cb5d-5451-473b-9d86-ef8530b19cc3.sql +++ b/supabase/migrations/20260213150148_e751cb5d-5451-473b-9d86-ef8530b19cc3.sql @@ -1,7 +1,8 @@ -- Drop the restrictive delete policy -DROP POLICY "Sellers can delete their draft quotes" ON public.quotes; +DROP POLICY IF EXISTS "Sellers can delete their draft quotes" ON public.quotes; -- Create a new policy allowing sellers to delete their own quotes (any status) and admins to delete any +DROP POLICY IF EXISTS "Sellers can delete their own quotes" ON public.quotes; CREATE POLICY "Sellers can delete their own quotes" ON public.quotes FOR DELETE diff --git a/supabase/migrations/20260214005421_b5727086-f390-4df4-99c3-77343477b962.sql b/supabase/migrations/20260214005421_b5727086-f390-4df4-99c3-77343477b962.sql index 9363d90ff..db40b23f8 100644 --- a/supabase/migrations/20260214005421_b5727086-f390-4df4-99c3-77343477b962.sql +++ b/supabase/migrations/20260214005421_b5727086-f390-4df4-99c3-77343477b962.sql @@ -1,6 +1,6 @@ --- Create table for simulator wizard drafts -CREATE TABLE public.simulator_wizard_drafts ( +-- CREATE TABLE IF NOT EXISTS for simulator wizard drafts +CREATE TABLE IF NOT EXISTS public.simulator_wizard_drafts ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID NOT NULL, title TEXT NOT NULL DEFAULT 'Rascunho', @@ -16,23 +16,28 @@ CREATE TABLE public.simulator_wizard_drafts ( ALTER TABLE public.simulator_wizard_drafts ENABLE ROW LEVEL SECURITY; -- RLS Policies +DROP POLICY IF EXISTS "Users can view their own drafts" ON public.simulator_wizard_drafts; CREATE POLICY "Users can view their own drafts" ON public.simulator_wizard_drafts FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can create their own drafts" ON public.simulator_wizard_drafts; CREATE POLICY "Users can create their own drafts" ON public.simulator_wizard_drafts FOR INSERT WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can update their own drafts" ON public.simulator_wizard_drafts; CREATE POLICY "Users can update their own drafts" ON public.simulator_wizard_drafts FOR UPDATE USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can delete their own drafts" ON public.simulator_wizard_drafts; CREATE POLICY "Users can delete their own drafts" ON public.simulator_wizard_drafts FOR DELETE USING (auth.uid() = user_id); -- Trigger for updated_at +DROP TRIGGER IF EXISTS update_simulator_wizard_drafts_updated_at ON public.simulator_wizard_drafts; CREATE TRIGGER update_simulator_wizard_drafts_updated_at BEFORE UPDATE ON public.simulator_wizard_drafts FOR EACH ROW diff --git a/supabase/migrations/20260214152115_900b7a1c-3aa4-48e7-afc1-5e44ea411a12.sql b/supabase/migrations/20260214152115_900b7a1c-3aa4-48e7-afc1-5e44ea411a12.sql index ad0ce2391..3bd77dfda 100644 --- a/supabase/migrations/20260214152115_900b7a1c-3aa4-48e7-afc1-5e44ea411a12.sql +++ b/supabase/migrations/20260214152115_900b7a1c-3aa4-48e7-afc1-5e44ea411a12.sql @@ -1,6 +1,6 @@ -- Carrinhos de vendedor (máx 3 por vendedor) -CREATE TABLE public.seller_carts ( +CREATE TABLE IF NOT EXISTS public.seller_carts ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, seller_id UUID NOT NULL, company_id TEXT NOT NULL, -- ID da empresa no CRM externo @@ -12,7 +12,7 @@ CREATE TABLE public.seller_carts ( ); -- Itens do carrinho -CREATE TABLE public.seller_cart_items ( +CREATE TABLE IF NOT EXISTS public.seller_cart_items ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, cart_id UUID NOT NULL REFERENCES public.seller_carts(id) ON DELETE CASCADE, product_id TEXT NOT NULL, @@ -30,28 +30,32 @@ CREATE TABLE public.seller_cart_items ( ); -- Indexes -CREATE INDEX idx_seller_carts_seller ON public.seller_carts(seller_id); -CREATE INDEX idx_seller_cart_items_cart ON public.seller_cart_items(cart_id); +CREATE INDEX IF NOT EXISTS idx_seller_carts_seller ON public.seller_carts(seller_id); +CREATE INDEX IF NOT EXISTS idx_seller_cart_items_cart ON public.seller_cart_items(cart_id); -- RLS ALTER TABLE public.seller_carts ENABLE ROW LEVEL SECURITY; ALTER TABLE public.seller_cart_items ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Sellers manage own carts" ON public.seller_carts; CREATE POLICY "Sellers manage own carts" ON public.seller_carts FOR ALL USING (auth.uid() = seller_id) WITH CHECK (auth.uid() = seller_id); +DROP POLICY IF EXISTS "Sellers manage own cart items" ON public.seller_cart_items; CREATE POLICY "Sellers manage own cart items" ON public.seller_cart_items FOR ALL USING (cart_id IN (SELECT id FROM public.seller_carts WHERE seller_id = auth.uid())) WITH CHECK (cart_id IN (SELECT id FROM public.seller_carts WHERE seller_id = auth.uid())); -- Trigger para updated_at +DROP TRIGGER IF EXISTS update_seller_carts_updated_at ON public.seller_carts; CREATE TRIGGER update_seller_carts_updated_at BEFORE UPDATE ON public.seller_carts FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); +DROP TRIGGER IF EXISTS update_seller_cart_items_updated_at ON public.seller_cart_items; CREATE TRIGGER update_seller_cart_items_updated_at BEFORE UPDATE ON public.seller_cart_items FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); @@ -67,6 +71,7 @@ BEGIN END; $$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = public; +DROP TRIGGER IF EXISTS enforce_seller_cart_limit ON public.seller_carts; CREATE TRIGGER enforce_seller_cart_limit BEFORE INSERT ON public.seller_carts FOR EACH ROW EXECUTE FUNCTION public.check_seller_cart_limit(); diff --git a/supabase/migrations/20260215185444_ea76adfb-8692-4601-8e52-4d38d56d90f2.sql b/supabase/migrations/20260215185444_ea76adfb-8692-4601-8e52-4d38d56d90f2.sql index 664d4b868..bebec017f 100644 --- a/supabase/migrations/20260215185444_ea76adfb-8692-4601-8e52-4d38d56d90f2.sql +++ b/supabase/migrations/20260215185444_ea76adfb-8692-4601-8e52-4d38d56d90f2.sql @@ -5,11 +5,13 @@ VALUES ('mockup-assets', 'mockup-assets', true) ON CONFLICT (id) DO NOTHING; -- Anyone can view mockup assets (public bucket) +DROP POLICY IF EXISTS "Anyone can view mockup assets" ON storage.objects; CREATE POLICY "Anyone can view mockup assets" ON storage.objects FOR SELECT USING (bucket_id = 'mockup-assets'); -- Authenticated users can upload to their own folder +DROP POLICY IF EXISTS "Users can upload their own mockup assets" ON storage.objects; CREATE POLICY "Users can upload their own mockup assets" ON storage.objects FOR INSERT WITH CHECK ( @@ -18,6 +20,7 @@ WITH CHECK ( ); -- Users can update their own assets +DROP POLICY IF EXISTS "Users can update their own mockup assets" ON storage.objects; CREATE POLICY "Users can update their own mockup assets" ON storage.objects FOR UPDATE USING ( @@ -26,6 +29,7 @@ USING ( ); -- Users can delete their own assets +DROP POLICY IF EXISTS "Users can delete their own mockup assets" ON storage.objects; CREATE POLICY "Users can delete their own mockup assets" ON storage.objects FOR DELETE USING ( diff --git a/supabase/migrations/20260216110718_f0a3e9e7-0ae7-4a15-9fea-5e5f50d0940d.sql b/supabase/migrations/20260216110718_f0a3e9e7-0ae7-4a15-9fea-5e5f50d0940d.sql index 0f6cd154b..7e2b92562 100644 --- a/supabase/migrations/20260216110718_f0a3e9e7-0ae7-4a15-9fea-5e5f50d0940d.sql +++ b/supabase/migrations/20260216110718_f0a3e9e7-0ae7-4a15-9fea-5e5f50d0940d.sql @@ -1,6 +1,6 @@ -- Tabela para persistir imagens publicitárias geradas pelo Magic Up -CREATE TABLE public.magic_up_generations ( +CREATE TABLE IF NOT EXISTS public.magic_up_generations ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID NOT NULL, product_name TEXT NOT NULL, @@ -25,22 +25,26 @@ CREATE TABLE public.magic_up_generations ( ALTER TABLE public.magic_up_generations ENABLE ROW LEVEL SECURITY; -- Users can only see their own generations +DROP POLICY IF EXISTS "Users can view own generations" ON public.magic_up_generations; CREATE POLICY "Users can view own generations" ON public.magic_up_generations FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can insert own generations" ON public.magic_up_generations; CREATE POLICY "Users can insert own generations" ON public.magic_up_generations FOR INSERT WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can update own generations" ON public.magic_up_generations; CREATE POLICY "Users can update own generations" ON public.magic_up_generations FOR UPDATE USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can delete own generations" ON public.magic_up_generations; CREATE POLICY "Users can delete own generations" ON public.magic_up_generations FOR DELETE USING (auth.uid() = user_id); -- Index for listing by user -CREATE INDEX idx_magic_up_generations_user ON public.magic_up_generations(user_id, created_at DESC); -CREATE INDEX idx_magic_up_generations_favorite ON public.magic_up_generations(user_id, is_favorite) WHERE is_favorite = true; +CREATE INDEX IF NOT EXISTS idx_magic_up_generations_user ON public.magic_up_generations(user_id, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_magic_up_generations_favorite ON public.magic_up_generations(user_id, is_favorite) WHERE is_favorite = true; diff --git a/supabase/migrations/20260216125012_7b8dd710-0052-45ad-958d-c05507520f35.sql b/supabase/migrations/20260216125012_7b8dd710-0052-45ad-958d-c05507520f35.sql index 034f30136..dcf3a9a46 100644 --- a/supabase/migrations/20260216125012_7b8dd710-0052-45ad-958d-c05507520f35.sql +++ b/supabase/migrations/20260216125012_7b8dd710-0052-45ad-958d-c05507520f35.sql @@ -1,6 +1,6 @@ -- Create mockup_templates table for synced custom templates -CREATE TABLE public.mockup_templates ( +CREATE TABLE IF NOT EXISTS public.mockup_templates ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID NOT NULL, name TEXT NOT NULL, @@ -13,23 +13,28 @@ CREATE TABLE public.mockup_templates ( ALTER TABLE public.mockup_templates ENABLE ROW LEVEL SECURITY; -- Users can only manage their own templates +DROP POLICY IF EXISTS "Users can view own templates" ON public.mockup_templates; CREATE POLICY "Users can view own templates" ON public.mockup_templates FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can create own templates" ON public.mockup_templates; CREATE POLICY "Users can create own templates" ON public.mockup_templates FOR INSERT WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can update own templates" ON public.mockup_templates; CREATE POLICY "Users can update own templates" ON public.mockup_templates FOR UPDATE USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can delete own templates" ON public.mockup_templates; CREATE POLICY "Users can delete own templates" ON public.mockup_templates FOR DELETE USING (auth.uid() = user_id); -- Trigger for updated_at +DROP TRIGGER IF EXISTS update_mockup_templates_updated_at ON public.mockup_templates; CREATE TRIGGER update_mockup_templates_updated_at BEFORE UPDATE ON public.mockup_templates FOR EACH ROW @@ -37,4 +42,4 @@ CREATE TRIGGER update_mockup_templates_updated_at -- Add annotations column to generated_mockups ALTER TABLE public.generated_mockups - ADD COLUMN annotations JSONB DEFAULT '[]'::jsonb; + ADD COLUMN IF NOT EXISTS annotations JSONB DEFAULT '[]'::jsonb; diff --git a/supabase/migrations/20260219024635_10fc2f51-2d00-4f89-9ef8-66aac365a39c.sql b/supabase/migrations/20260219024635_10fc2f51-2d00-4f89-9ef8-66aac365a39c.sql index 81950b60a..b79007e51 100644 --- a/supabase/migrations/20260219024635_10fc2f51-2d00-4f89-9ef8-66aac365a39c.sql +++ b/supabase/migrations/20260219024635_10fc2f51-2d00-4f89-9ef8-66aac365a39c.sql @@ -1,17 +1,20 @@ -- Allow authenticated users to upload PDFs to art-files bucket (quotes folder) +DROP POLICY IF EXISTS "Authenticated users can upload to art-files" ON storage.objects; CREATE POLICY "Authenticated users can upload to art-files" ON storage.objects FOR INSERT TO authenticated WITH CHECK (bucket_id = 'art-files'); +DROP POLICY IF EXISTS "Authenticated users can update art-files" ON storage.objects; CREATE POLICY "Authenticated users can update art-files" ON storage.objects FOR UPDATE TO authenticated USING (bucket_id = 'art-files'); +DROP POLICY IF EXISTS "Authenticated users can read art-files" ON storage.objects; CREATE POLICY "Authenticated users can read art-files" ON storage.objects FOR SELECT diff --git a/supabase/migrations/20260219133353_4495e564-cec8-44b1-a590-1fb18ca8c91d.sql b/supabase/migrations/20260219133353_4495e564-cec8-44b1-a590-1fb18ca8c91d.sql index 265a5b275..ef55441b8 100644 --- a/supabase/migrations/20260219133353_4495e564-cec8-44b1-a590-1fb18ca8c91d.sql +++ b/supabase/migrations/20260219133353_4495e564-cec8-44b1-a590-1fb18ca8c91d.sql @@ -47,6 +47,7 @@ END; $$ LANGUAGE plpgsql SET search_path = public; -- Re-create the trigger +DROP TRIGGER IF EXISTS set_quote_number ON public.quotes; CREATE TRIGGER set_quote_number BEFORE INSERT ON public.quotes FOR EACH ROW @@ -57,6 +58,7 @@ CREATE TRIGGER set_quote_number ALTER TABLE public.quote_number_counters ENABLE ROW LEVEL SECURITY; -- Only allow the trigger function to access it (service role) +DROP POLICY IF EXISTS "service_role_only" ON public.quote_number_counters; CREATE POLICY "service_role_only" ON public.quote_number_counters USING (false) WITH CHECK (false); diff --git a/supabase/migrations/20260220001443_54c4d527-34ff-47cb-b192-8821dee4b9ae.sql b/supabase/migrations/20260220001443_54c4d527-34ff-47cb-b192-8821dee4b9ae.sql index 0992f38bb..f5ebdf1d6 100644 --- a/supabase/migrations/20260220001443_54c4d527-34ff-47cb-b192-8821dee4b9ae.sql +++ b/supabase/migrations/20260220001443_54c4d527-34ff-47cb-b192-8821dee4b9ae.sql @@ -1,6 +1,6 @@ -- Tabela de IPs permitidos (whitelist) -CREATE TABLE public.ip_whitelist ( +CREATE TABLE IF NOT EXISTS public.ip_whitelist ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, ip_address TEXT NOT NULL, label TEXT, -- ex: "Escritório SP", "Home Office João" @@ -12,7 +12,7 @@ CREATE TABLE public.ip_whitelist ( ); -- Tabela de cidades permitidas (whitelist) -CREATE TABLE public.city_whitelist ( +CREATE TABLE IF NOT EXISTS public.city_whitelist ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, city_name TEXT NOT NULL, state TEXT, -- ex: "SP", "RJ" @@ -25,7 +25,7 @@ CREATE TABLE public.city_whitelist ( ); -- Log de acessos bloqueados -CREATE TABLE public.access_blocked_log ( +CREATE TABLE IF NOT EXISTS public.access_blocked_log ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID REFERENCES auth.users(id), email TEXT, @@ -39,7 +39,7 @@ CREATE TABLE public.access_blocked_log ( ); -- Configuração global de segurança de acesso -CREATE TABLE public.access_security_settings ( +CREATE TABLE IF NOT EXISTS public.access_security_settings ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, ip_whitelist_enabled BOOLEAN NOT NULL DEFAULT false, city_whitelist_enabled BOOLEAN NOT NULL DEFAULT false, @@ -61,31 +61,39 @@ ALTER TABLE public.access_blocked_log ENABLE ROW LEVEL SECURITY; ALTER TABLE public.access_security_settings ENABLE ROW LEVEL SECURITY; -- Policies: Apenas admin/manager podem gerenciar +DROP POLICY IF EXISTS "Admin can manage ip_whitelist" ON public.ip_whitelist; CREATE POLICY "Admin can manage ip_whitelist" ON public.ip_whitelist FOR ALL USING (public.can_manage(auth.uid())); +DROP POLICY IF EXISTS "Admin can manage city_whitelist" ON public.city_whitelist; CREATE POLICY "Admin can manage city_whitelist" ON public.city_whitelist FOR ALL USING (public.can_manage(auth.uid())); +DROP POLICY IF EXISTS "Admin can view access_blocked_log" ON public.access_blocked_log; CREATE POLICY "Admin can view access_blocked_log" ON public.access_blocked_log FOR SELECT USING (public.can_manage(auth.uid())); +DROP POLICY IF EXISTS "Admin can manage access_security_settings" ON public.access_security_settings; CREATE POLICY "Admin can manage access_security_settings" ON public.access_security_settings FOR ALL USING (public.can_manage(auth.uid())); -- Service role precisa inserir logs (via edge function) +DROP POLICY IF EXISTS "Service can insert blocked logs" ON public.access_blocked_log; CREATE POLICY "Service can insert blocked logs" ON public.access_blocked_log FOR INSERT WITH CHECK (true); -- Triggers de updated_at +DROP TRIGGER IF EXISTS update_ip_whitelist_updated_at ON public.ip_whitelist; CREATE TRIGGER update_ip_whitelist_updated_at BEFORE UPDATE ON public.ip_whitelist FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); +DROP TRIGGER IF EXISTS update_city_whitelist_updated_at ON public.city_whitelist; CREATE TRIGGER update_city_whitelist_updated_at BEFORE UPDATE ON public.city_whitelist FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); +DROP TRIGGER IF EXISTS update_access_security_settings_updated_at ON public.access_security_settings; CREATE TRIGGER update_access_security_settings_updated_at BEFORE UPDATE ON public.access_security_settings FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); diff --git a/supabase/migrations/20260220174735_fba5ec23-9f56-4c65-b98d-34e66017521d.sql b/supabase/migrations/20260220174735_fba5ec23-9f56-4c65-b98d-34e66017521d.sql index a119d75aa..84c80e01e 100644 --- a/supabase/migrations/20260220174735_fba5ec23-9f56-4c65-b98d-34e66017521d.sql +++ b/supabase/migrations/20260220174735_fba5ec23-9f56-4c65-b98d-34e66017521d.sql @@ -8,21 +8,25 @@ VALUES ('signatures', 'signatures', true) ON CONFLICT (id) DO NOTHING; -- RLS: anyone can view signatures (needed for PDF generation) +DROP POLICY IF EXISTS "Signatures are publicly accessible" ON storage.objects; CREATE POLICY "Signatures are publicly accessible" ON storage.objects FOR SELECT USING (bucket_id = 'signatures'); -- RLS: users can upload their own signature +DROP POLICY IF EXISTS "Users can upload their own signature" ON storage.objects; CREATE POLICY "Users can upload their own signature" ON storage.objects FOR INSERT WITH CHECK (bucket_id = 'signatures' AND auth.uid()::text = (storage.foldername(name))[1]); -- RLS: users can update their own signature +DROP POLICY IF EXISTS "Users can update their own signature" ON storage.objects; CREATE POLICY "Users can update their own signature" ON storage.objects FOR UPDATE USING (bucket_id = 'signatures' AND auth.uid()::text = (storage.foldername(name))[1]); -- RLS: users can delete their own signature +DROP POLICY IF EXISTS "Users can delete their own signature" ON storage.objects; CREATE POLICY "Users can delete their own signature" ON storage.objects FOR DELETE USING (bucket_id = 'signatures' AND auth.uid()::text = (storage.foldername(name))[1]); diff --git a/supabase/migrations/20260222134246_025e1c16-1f11-4704-a8ea-1c66dd98796a.sql b/supabase/migrations/20260222134246_025e1c16-1f11-4704-a8ea-1c66dd98796a.sql index 89b5cb89b..0adfe8b40 100644 --- a/supabase/migrations/20260222134246_025e1c16-1f11-4704-a8ea-1c66dd98796a.sql +++ b/supabase/migrations/20260222134246_025e1c16-1f11-4704-a8ea-1c66dd98796a.sql @@ -1,6 +1,6 @@ -- Tabela para gerenciar prompts de mockup -CREATE TABLE public.mockup_prompt_configs ( +CREATE TABLE IF NOT EXISTS public.mockup_prompt_configs ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, config_key TEXT NOT NULL UNIQUE, -- 'main_prompt', 'technique_', etc. label TEXT NOT NULL, -- Nome amigável @@ -16,7 +16,7 @@ CREATE TABLE public.mockup_prompt_configs ( ); -- Histórico de versões -CREATE TABLE public.mockup_prompt_history ( +CREATE TABLE IF NOT EXISTS public.mockup_prompt_history ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, config_id UUID NOT NULL REFERENCES public.mockup_prompt_configs(id) ON DELETE CASCADE, version INTEGER NOT NULL, @@ -32,24 +32,29 @@ ALTER TABLE public.mockup_prompt_configs ENABLE ROW LEVEL SECURITY; ALTER TABLE public.mockup_prompt_history ENABLE ROW LEVEL SECURITY; -- Policies: only admin/manager can manage +DROP POLICY IF EXISTS "Admins can manage prompt configs" ON public.mockup_prompt_configs; CREATE POLICY "Admins can manage prompt configs" ON public.mockup_prompt_configs FOR ALL USING (public.can_manage(auth.uid())); +DROP POLICY IF EXISTS "Admins can manage prompt history" ON public.mockup_prompt_history; CREATE POLICY "Admins can manage prompt history" ON public.mockup_prompt_history FOR ALL USING (public.can_manage(auth.uid())); -- Sellers can read active configs (edge function needs this) +DROP POLICY IF EXISTS "Authenticated users can read active configs" ON public.mockup_prompt_configs; CREATE POLICY "Authenticated users can read active configs" ON public.mockup_prompt_configs FOR SELECT USING (auth.uid() IS NOT NULL AND is_active = true); +DROP POLICY IF EXISTS "Authenticated users can read history" ON public.mockup_prompt_history; CREATE POLICY "Authenticated users can read history" ON public.mockup_prompt_history FOR SELECT USING (auth.uid() IS NOT NULL); -- Trigger updated_at +DROP TRIGGER IF EXISTS update_mockup_prompt_configs_updated_at ON public.mockup_prompt_configs; CREATE TRIGGER update_mockup_prompt_configs_updated_at BEFORE UPDATE ON public.mockup_prompt_configs FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); diff --git a/supabase/migrations/20260222203852_03bbb884-bf53-4f9b-8a57-1b8cd606c558.sql b/supabase/migrations/20260222203852_03bbb884-bf53-4f9b-8a57-1b8cd606c558.sql index 41efa74f4..e4a77a361 100644 --- a/supabase/migrations/20260222203852_03bbb884-bf53-4f9b-8a57-1b8cd606c558.sql +++ b/supabase/migrations/20260222203852_03bbb884-bf53-4f9b-8a57-1b8cd606c558.sql @@ -5,6 +5,7 @@ DROP POLICY IF EXISTS "Users can update their own avatar" ON storage.objects; DROP POLICY IF EXISTS "Users can delete their own avatar" ON storage.objects; -- Recreate policies: users can manage their own + admins can manage any +DROP POLICY IF EXISTS "Users or admins can upload avatars" ON storage.objects; CREATE POLICY "Users or admins can upload avatars" ON storage.objects FOR INSERT WITH CHECK ( @@ -14,6 +15,7 @@ WITH CHECK ( ) ); +DROP POLICY IF EXISTS "Users or admins can update avatars" ON storage.objects; CREATE POLICY "Users or admins can update avatars" ON storage.objects FOR UPDATE USING ( @@ -23,6 +25,7 @@ USING ( ) ); +DROP POLICY IF EXISTS "Users or admins can delete avatars" ON storage.objects; CREATE POLICY "Users or admins can delete avatars" ON storage.objects FOR DELETE USING ( diff --git a/supabase/migrations/20260226200633_e02b5e2d-c127-43a6-9ea8-07da1bc67d13.sql b/supabase/migrations/20260226200633_e02b5e2d-c127-43a6-9ea8-07da1bc67d13.sql index 0ab0dc0a3..48acd4d14 100644 --- a/supabase/migrations/20260226200633_e02b5e2d-c127-43a6-9ea8-07da1bc67d13.sql +++ b/supabase/migrations/20260226200633_e02b5e2d-c127-43a6-9ea8-07da1bc67d13.sql @@ -1,6 +1,6 @@ -- Cart templates table for reusable cart configurations -CREATE TABLE public.cart_templates ( +CREATE TABLE IF NOT EXISTS public.cart_templates ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID NOT NULL, name TEXT NOT NULL, @@ -12,14 +12,18 @@ CREATE TABLE public.cart_templates ( ALTER TABLE public.cart_templates ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view their own cart templates" ON public.cart_templates; CREATE POLICY "Users can view their own cart templates" ON public.cart_templates FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can create their own cart templates" ON public.cart_templates; CREATE POLICY "Users can create their own cart templates" ON public.cart_templates FOR INSERT WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can update their own cart templates" ON public.cart_templates; CREATE POLICY "Users can update their own cart templates" ON public.cart_templates FOR UPDATE USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can delete their own cart templates" ON public.cart_templates; CREATE POLICY "Users can delete their own cart templates" ON public.cart_templates FOR DELETE USING (auth.uid() = user_id); diff --git a/supabase/migrations/20260301150840_2d75bd5f-1418-4618-a678-2c226c72ddc9.sql b/supabase/migrations/20260301150840_2d75bd5f-1418-4618-a678-2c226c72ddc9.sql index db0d77c68..5210066fd 100644 --- a/supabase/migrations/20260301150840_2d75bd5f-1418-4618-a678-2c226c72ddc9.sql +++ b/supabase/migrations/20260301150840_2d75bd5f-1418-4618-a678-2c226c72ddc9.sql @@ -1,5 +1,6 @@ -- Add UPDATE policy for generated_mockups so layout capture can update layout_url +DROP POLICY IF EXISTS "Sellers can update their own mockups" ON public.generated_mockups; CREATE POLICY "Sellers can update their own mockups" ON public.generated_mockups FOR UPDATE diff --git a/supabase/migrations/20260304004120_5ce3d07d-0560-4175-93f4-9307b6247652.sql b/supabase/migrations/20260304004120_5ce3d07d-0560-4175-93f4-9307b6247652.sql index 99e70f05d..71832c532 100644 --- a/supabase/migrations/20260304004120_5ce3d07d-0560-4175-93f4-9307b6247652.sql +++ b/supabase/migrations/20260304004120_5ce3d07d-0560-4175-93f4-9307b6247652.sql @@ -1,9 +1,12 @@ -- Create app_role enum +DO $$ BEGIN CREATE TYPE public.app_role AS ENUM ('admin', 'manager', 'vendedor'); +EXCEPTION WHEN duplicate_object THEN NULL; +END $$; -- Create profiles table -CREATE TABLE public.profiles ( +CREATE TABLE IF NOT EXISTS public.profiles ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE NOT NULL UNIQUE, email TEXT, @@ -20,7 +23,7 @@ CREATE TABLE public.profiles ( ); -- Create user_roles table -CREATE TABLE public.user_roles ( +CREATE TABLE IF NOT EXISTS public.user_roles ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE NOT NULL, role app_role NOT NULL DEFAULT 'vendedor', @@ -46,27 +49,32 @@ AS $$ $$; -- RLS policies for profiles +DROP POLICY IF EXISTS "Users can view own profile" ON public.profiles; CREATE POLICY "Users can view own profile" ON public.profiles FOR SELECT TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "Users can update own profile" ON public.profiles; CREATE POLICY "Users can update own profile" ON public.profiles FOR UPDATE TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "Admins can view all profiles" ON public.profiles; CREATE POLICY "Admins can view all profiles" ON public.profiles FOR SELECT TO authenticated USING (public.has_role(auth.uid(), 'admin')); -- RLS policies for user_roles +DROP POLICY IF EXISTS "Users can view own role" ON public.user_roles; CREATE POLICY "Users can view own role" ON public.user_roles FOR SELECT TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "Admins can manage roles" ON public.user_roles; CREATE POLICY "Admins can manage roles" ON public.user_roles FOR ALL TO authenticated @@ -94,6 +102,7 @@ BEGIN END; $$; +DROP TRIGGER IF EXISTS on_auth_user_created ON auth.users; CREATE TRIGGER on_auth_user_created AFTER INSERT ON auth.users FOR EACH ROW diff --git a/supabase/migrations/20260304014416_bbad6fe9-94ed-41cb-9ca2-0aba506fdab9.sql b/supabase/migrations/20260304014416_bbad6fe9-94ed-41cb-9ca2-0aba506fdab9.sql index bb1e551f2..2786636aa 100644 --- a/supabase/migrations/20260304014416_bbad6fe9-94ed-41cb-9ca2-0aba506fdab9.sql +++ b/supabase/migrations/20260304014416_bbad6fe9-94ed-41cb-9ca2-0aba506fdab9.sql @@ -1,6 +1,6 @@ -- 1) user_onboarding -CREATE TABLE public.user_onboarding ( +CREATE TABLE IF NOT EXISTS public.user_onboarding ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE, has_completed_tour boolean NOT NULL DEFAULT false, @@ -13,12 +13,15 @@ CREATE TABLE public.user_onboarding ( UNIQUE(user_id) ); ALTER TABLE public.user_onboarding ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view own onboarding" ON public.user_onboarding; CREATE POLICY "Users can view own onboarding" ON public.user_onboarding FOR SELECT USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "Users can insert own onboarding" ON public.user_onboarding; CREATE POLICY "Users can insert own onboarding" ON public.user_onboarding FOR INSERT WITH CHECK (user_id = auth.uid()); +DROP POLICY IF EXISTS "Users can update own onboarding" ON public.user_onboarding; CREATE POLICY "Users can update own onboarding" ON public.user_onboarding FOR UPDATE USING (user_id = auth.uid()); -- 2) expert_conversations -CREATE TABLE public.expert_conversations ( +CREATE TABLE IF NOT EXISTS public.expert_conversations ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), seller_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE, client_id text, @@ -27,10 +30,11 @@ CREATE TABLE public.expert_conversations ( updated_at timestamptz NOT NULL DEFAULT now() ); ALTER TABLE public.expert_conversations ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can manage own conversations" ON public.expert_conversations; CREATE POLICY "Users can manage own conversations" ON public.expert_conversations FOR ALL USING (seller_id = auth.uid()); -- 3) expert_messages -CREATE TABLE public.expert_messages ( +CREATE TABLE IF NOT EXISTS public.expert_messages ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), conversation_id uuid NOT NULL REFERENCES public.expert_conversations(id) ON DELETE CASCADE, role text NOT NULL DEFAULT 'user', @@ -38,11 +42,12 @@ CREATE TABLE public.expert_messages ( created_at timestamptz NOT NULL DEFAULT now() ); ALTER TABLE public.expert_messages ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can manage own messages" ON public.expert_messages; CREATE POLICY "Users can manage own messages" ON public.expert_messages FOR ALL USING (EXISTS (SELECT 1 FROM public.expert_conversations c WHERE c.id = conversation_id AND c.seller_id = auth.uid())); -- 4) seller_carts -CREATE TABLE public.seller_carts ( +CREATE TABLE IF NOT EXISTS public.seller_carts ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), seller_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE, company_id text NOT NULL, @@ -55,10 +60,11 @@ CREATE TABLE public.seller_carts ( updated_at timestamptz NOT NULL DEFAULT now() ); ALTER TABLE public.seller_carts ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can manage own carts" ON public.seller_carts; CREATE POLICY "Users can manage own carts" ON public.seller_carts FOR ALL USING (seller_id = auth.uid()); -- 5) seller_cart_items -CREATE TABLE public.seller_cart_items ( +CREATE TABLE IF NOT EXISTS public.seller_cart_items ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), cart_id uuid NOT NULL REFERENCES public.seller_carts(id) ON DELETE CASCADE, product_id text NOT NULL, @@ -75,5 +81,6 @@ CREATE TABLE public.seller_cart_items ( updated_at timestamptz NOT NULL DEFAULT now() ); ALTER TABLE public.seller_cart_items ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can manage own cart items" ON public.seller_cart_items; CREATE POLICY "Users can manage own cart items" ON public.seller_cart_items FOR ALL USING (EXISTS (SELECT 1 FROM public.seller_carts c WHERE c.id = cart_id AND c.seller_id = auth.uid())); diff --git a/supabase/migrations/20260304014707_95817329-52c7-48ca-960b-90a29516b4cb.sql b/supabase/migrations/20260304014707_95817329-52c7-48ca-960b-90a29516b4cb.sql index cc8ee39d7..bd3ce4a2b 100644 --- a/supabase/migrations/20260304014707_95817329-52c7-48ca-960b-90a29516b4cb.sql +++ b/supabase/migrations/20260304014707_95817329-52c7-48ca-960b-90a29516b4cb.sql @@ -1,6 +1,6 @@ -- mockup_drafts table for auto-save functionality -CREATE TABLE public.mockup_drafts ( +CREATE TABLE IF NOT EXISTS public.mockup_drafts ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE, draft_key text NOT NULL DEFAULT 'default', @@ -17,10 +17,11 @@ CREATE TABLE public.mockup_drafts ( UNIQUE(user_id, draft_key) ); ALTER TABLE public.mockup_drafts ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can manage own drafts" ON public.mockup_drafts; CREATE POLICY "Users can manage own drafts" ON public.mockup_drafts FOR ALL USING (user_id = auth.uid()); -- magic_up_generations table -CREATE TABLE public.magic_up_generations ( +CREATE TABLE IF NOT EXISTS public.magic_up_generations ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE, product_name text, @@ -32,4 +33,5 @@ CREATE TABLE public.magic_up_generations ( created_at timestamptz NOT NULL DEFAULT now() ); ALTER TABLE public.magic_up_generations ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can manage own generations" ON public.magic_up_generations; CREATE POLICY "Users can manage own generations" ON public.magic_up_generations FOR ALL USING (user_id = auth.uid()); diff --git a/supabase/migrations/20260305220938_80f39c81-955b-4452-bbeb-4d133bd3009f.sql b/supabase/migrations/20260305220938_80f39c81-955b-4452-bbeb-4d133bd3009f.sql index f2381708d..a34ae962a 100644 --- a/supabase/migrations/20260305220938_80f39c81-955b-4452-bbeb-4d133bd3009f.sql +++ b/supabase/migrations/20260305220938_80f39c81-955b-4452-bbeb-4d133bd3009f.sql @@ -1,6 +1,6 @@ -- 1. category_icons -CREATE TABLE public.category_icons ( +CREATE TABLE IF NOT EXISTS public.category_icons ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), category_name text NOT NULL, icon text NOT NULL, @@ -10,10 +10,11 @@ CREATE TABLE public.category_icons ( updated_at timestamptz NOT NULL DEFAULT now() ); ALTER TABLE public.category_icons ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Anyone can read category icons" ON public.category_icons; CREATE POLICY "Anyone can read category icons" ON public.category_icons FOR SELECT USING (true); -- 2. product_views (analytics) -CREATE TABLE public.product_views ( +CREATE TABLE IF NOT EXISTS public.product_views ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), product_id text, product_sku text, @@ -23,12 +24,15 @@ CREATE TABLE public.product_views ( created_at timestamptz NOT NULL DEFAULT now() ); ALTER TABLE public.product_views ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can insert own views" ON public.product_views; CREATE POLICY "Users can insert own views" ON public.product_views FOR INSERT TO authenticated WITH CHECK (seller_id = auth.uid()); +DROP POLICY IF EXISTS "Users can read own views" ON public.product_views; CREATE POLICY "Users can read own views" ON public.product_views FOR SELECT TO authenticated USING (seller_id = auth.uid()); +DROP POLICY IF EXISTS "Admins can read all views" ON public.product_views; CREATE POLICY "Admins can read all views" ON public.product_views FOR SELECT TO authenticated USING (public.has_role(auth.uid(), 'admin')); -- 3. product_groups -CREATE TABLE public.product_groups ( +CREATE TABLE IF NOT EXISTS public.product_groups ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), group_code text NOT NULL, group_name text NOT NULL, @@ -38,11 +42,13 @@ CREATE TABLE public.product_groups ( updated_at timestamptz NOT NULL DEFAULT now() ); ALTER TABLE public.product_groups ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Authenticated users can read groups" ON public.product_groups; CREATE POLICY "Authenticated users can read groups" ON public.product_groups FOR SELECT TO authenticated USING (true); +DROP POLICY IF EXISTS "Admins can manage groups" ON public.product_groups; CREATE POLICY "Admins can manage groups" ON public.product_groups FOR ALL TO authenticated USING (public.has_role(auth.uid(), 'admin')); -- 4. product_group_members -CREATE TABLE public.product_group_members ( +CREATE TABLE IF NOT EXISTS public.product_group_members ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), product_group_id uuid REFERENCES public.product_groups(id) ON DELETE CASCADE NOT NULL, product_id text NOT NULL, @@ -51,11 +57,13 @@ CREATE TABLE public.product_group_members ( updated_at timestamptz NOT NULL DEFAULT now() ); ALTER TABLE public.product_group_members ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Authenticated users can read members" ON public.product_group_members; CREATE POLICY "Authenticated users can read members" ON public.product_group_members FOR SELECT TO authenticated USING (true); +DROP POLICY IF EXISTS "Admins can manage members" ON public.product_group_members; CREATE POLICY "Admins can manage members" ON public.product_group_members FOR ALL TO authenticated USING (public.has_role(auth.uid(), 'admin')); -- 5. product_components -CREATE TABLE public.product_components ( +CREATE TABLE IF NOT EXISTS public.product_components ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), product_id text NOT NULL, component_code text NOT NULL, @@ -67,11 +75,13 @@ CREATE TABLE public.product_components ( updated_at timestamptz NOT NULL DEFAULT now() ); ALTER TABLE public.product_components ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Authenticated users can read components" ON public.product_components; CREATE POLICY "Authenticated users can read components" ON public.product_components FOR SELECT TO authenticated USING (true); +DROP POLICY IF EXISTS "Admins can manage components" ON public.product_components; CREATE POLICY "Admins can manage components" ON public.product_components FOR ALL TO authenticated USING (public.has_role(auth.uid(), 'admin')); -- 6. order_items (for recommendations/analytics) -CREATE TABLE public.order_items ( +CREATE TABLE IF NOT EXISTS public.order_items ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), order_id text, product_id text, @@ -83,5 +93,7 @@ CREATE TABLE public.order_items ( created_at timestamptz NOT NULL DEFAULT now() ); ALTER TABLE public.order_items ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Authenticated users can read order items" ON public.order_items; CREATE POLICY "Authenticated users can read order items" ON public.order_items FOR SELECT TO authenticated USING (true); +DROP POLICY IF EXISTS "Admins can manage order items" ON public.order_items; CREATE POLICY "Admins can manage order items" ON public.order_items FOR ALL TO authenticated USING (public.has_role(auth.uid(), 'admin')); diff --git a/supabase/migrations/20260306011448_0a463f8c-2ba5-48b1-8ff4-dd057684f422.sql b/supabase/migrations/20260306011448_0a463f8c-2ba5-48b1-8ff4-dd057684f422.sql index 257f00408..3a7155ae5 100644 --- a/supabase/migrations/20260306011448_0a463f8c-2ba5-48b1-8ff4-dd057684f422.sql +++ b/supabase/migrations/20260306011448_0a463f8c-2ba5-48b1-8ff4-dd057684f422.sql @@ -1,4 +1,4 @@ -CREATE TABLE public.simulator_wizard_drafts ( +CREATE TABLE IF NOT EXISTS public.simulator_wizard_drafts ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), user_id uuid NOT NULL, title text NOT NULL DEFAULT 'Rascunho', @@ -12,18 +12,21 @@ CREATE TABLE public.simulator_wizard_drafts ( ALTER TABLE public.simulator_wizard_drafts ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view own drafts" ON public.simulator_wizard_drafts; CREATE POLICY "Users can view own drafts" ON public.simulator_wizard_drafts FOR SELECT TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "Users can insert own drafts" ON public.simulator_wizard_drafts; CREATE POLICY "Users can insert own drafts" ON public.simulator_wizard_drafts FOR INSERT TO authenticated WITH CHECK (user_id = auth.uid()); +DROP POLICY IF EXISTS "Users can update own drafts" ON public.simulator_wizard_drafts; CREATE POLICY "Users can update own drafts" ON public.simulator_wizard_drafts FOR UPDATE @@ -31,6 +34,7 @@ CREATE POLICY "Users can update own drafts" USING (user_id = auth.uid()) WITH CHECK (user_id = auth.uid()); +DROP POLICY IF EXISTS "Users can delete own drafts" ON public.simulator_wizard_drafts; CREATE POLICY "Users can delete own drafts" ON public.simulator_wizard_drafts FOR DELETE diff --git a/supabase/migrations/20260306013723_8ea96e6d-f69b-4bc3-80bc-109377e45a2d.sql b/supabase/migrations/20260306013723_8ea96e6d-f69b-4bc3-80bc-109377e45a2d.sql index 0b449b00b..609961f27 100644 --- a/supabase/migrations/20260306013723_8ea96e6d-f69b-4bc3-80bc-109377e45a2d.sql +++ b/supabase/migrations/20260306013723_8ea96e6d-f69b-4bc3-80bc-109377e45a2d.sql @@ -8,11 +8,13 @@ CREATE POLICY "Users can view own profile" TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "Admins can view all profiles" ON public.profiles; CREATE POLICY "Admins can view all profiles" ON public.profiles FOR SELECT TO authenticated USING (public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Users can update own profile" ON public.profiles; CREATE POLICY "Users can update own profile" ON public.profiles FOR UPDATE TO authenticated @@ -39,11 +41,13 @@ CREATE POLICY "Users can view own views" TO authenticated USING (seller_id = auth.uid()); +DROP POLICY IF EXISTS "Admins can read all views" ON public.product_views; CREATE POLICY "Admins can read all views" ON public.product_views FOR SELECT TO authenticated USING (public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Users can insert own views" ON public.product_views; CREATE POLICY "Users can insert own views" ON public.product_views FOR INSERT TO authenticated @@ -80,6 +84,7 @@ CREATE POLICY "Users can view own role" TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "Admins can manage roles" ON public.user_roles; CREATE POLICY "Admins can manage roles" ON public.user_roles FOR ALL TO authenticated diff --git a/supabase/migrations/20260312111512_765a8982-1fb1-4329-9172-8840c819d56d.sql b/supabase/migrations/20260312111512_765a8982-1fb1-4329-9172-8840c819d56d.sql index 7400714b8..dcdf80e96 100644 --- a/supabase/migrations/20260312111512_765a8982-1fb1-4329-9172-8840c819d56d.sql +++ b/supabase/migrations/20260312111512_765a8982-1fb1-4329-9172-8840c819d56d.sql @@ -55,11 +55,13 @@ CREATE POLICY "Users can view own onboarding" TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "Users can insert own onboarding" ON public.user_onboarding; CREATE POLICY "Users can insert own onboarding" ON public.user_onboarding FOR INSERT TO authenticated WITH CHECK (user_id = auth.uid()); +DROP POLICY IF EXISTS "Users can update own onboarding" ON public.user_onboarding; CREATE POLICY "Users can update own onboarding" ON public.user_onboarding FOR UPDATE TO authenticated diff --git a/supabase/migrations/20260312113744_add_supplier_availability_status_to_vss.sql b/supabase/migrations/20260312113744_add_supplier_availability_status_to_vss.sql new file mode 100644 index 000000000..c0ba69451 --- /dev/null +++ b/supabase/migrations/20260312113744_add_supplier_availability_status_to_vss.sql @@ -0,0 +1,2 @@ +-- Migration 20260312113744 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312113752_add_xbz_disponivel_field_mapping.sql b/supabase/migrations/20260312113752_add_xbz_disponivel_field_mapping.sql new file mode 100644 index 000000000..5d28cbcf9 --- /dev/null +++ b/supabase/migrations/20260312113752_add_xbz_disponivel_field_mapping.sql @@ -0,0 +1,2 @@ +-- Migration 20260312113752 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312115104_add_supplier_ipi_rate_to_vss.sql b/supabase/migrations/20260312115104_add_supplier_ipi_rate_to_vss.sql new file mode 100644 index 000000000..028cfd08e --- /dev/null +++ b/supabase/migrations/20260312115104_add_supplier_ipi_rate_to_vss.sql @@ -0,0 +1,2 @@ +-- Migration 20260312115104 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312115112_add_xbz_ipi_taxa_field_mapping.sql b/supabase/migrations/20260312115112_add_xbz_ipi_taxa_field_mapping.sql new file mode 100644 index 000000000..6e45fb957 --- /dev/null +++ b/supabase/migrations/20260312115112_add_xbz_ipi_taxa_field_mapping.sql @@ -0,0 +1,2 @@ +-- Migration 20260312115112 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312115440_59674716-1e1e-4e17-a178-d1c88a7a277f.sql b/supabase/migrations/20260312115440_59674716-1e1e-4e17-a178-d1c88a7a277f.sql index 2f953af37..55c4fdacf 100644 --- a/supabase/migrations/20260312115440_59674716-1e1e-4e17-a178-d1c88a7a277f.sql +++ b/supabase/migrations/20260312115440_59674716-1e1e-4e17-a178-d1c88a7a277f.sql @@ -1,5 +1,5 @@ -CREATE TABLE public.generated_mockups ( +CREATE TABLE IF NOT EXISTS public.generated_mockups ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), seller_id uuid NOT NULL, client_id text, @@ -24,6 +24,7 @@ CREATE TABLE public.generated_mockups ( ALTER TABLE public.generated_mockups ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can manage own mockups" ON public.generated_mockups; CREATE POLICY "Users can manage own mockups" ON public.generated_mockups FOR ALL diff --git a/supabase/migrations/20260312115728_add_xbz_multiplos_field_mapping.sql b/supabase/migrations/20260312115728_add_xbz_multiplos_field_mapping.sql new file mode 100644 index 000000000..8dcbc3ad4 --- /dev/null +++ b/supabase/migrations/20260312115728_add_xbz_multiplos_field_mapping.sql @@ -0,0 +1,2 @@ +-- Migration 20260312115728 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312122603_add_5_missing_xbz_supplier_colors.sql b/supabase/migrations/20260312122603_add_5_missing_xbz_supplier_colors.sql new file mode 100644 index 000000000..a87df389f --- /dev/null +++ b/supabase/migrations/20260312122603_add_5_missing_xbz_supplier_colors.sql @@ -0,0 +1,2 @@ +-- Migration 20260312122603 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312122858_add_natural_internal_code_and_4_color_variations.sql b/supabase/migrations/20260312122858_add_natural_internal_code_and_4_color_variations.sql new file mode 100644 index 000000000..0be3e8cc0 --- /dev/null +++ b/supabase/migrations/20260312122858_add_natural_internal_code_and_4_color_variations.sql @@ -0,0 +1,2 @@ +-- Migration 20260312122858 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312123036_add_5_xbz_color_equivalences.sql b/supabase/migrations/20260312123036_add_5_xbz_color_equivalences.sql new file mode 100644 index 000000000..0bbcd6eb2 --- /dev/null +++ b/supabase/migrations/20260312123036_add_5_xbz_color_equivalences.sql @@ -0,0 +1,2 @@ +-- Migration 20260312123036 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312130031_fix_spot_color_equivalences_cleanup.sql b/supabase/migrations/20260312130031_fix_spot_color_equivalences_cleanup.sql new file mode 100644 index 000000000..527ddfb78 --- /dev/null +++ b/supabase/migrations/20260312130031_fix_spot_color_equivalences_cleanup.sql @@ -0,0 +1,2 @@ +-- Migration 20260312130031 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312130055_fix_spot_154_azul_aqua_to_azul_piscina.sql b/supabase/migrations/20260312130055_fix_spot_154_azul_aqua_to_azul_piscina.sql new file mode 100644 index 000000000..cb99d0564 --- /dev/null +++ b/supabase/migrations/20260312130055_fix_spot_154_azul_aqua_to_azul_piscina.sql @@ -0,0 +1,2 @@ +-- Migration 20260312130055 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312130246_fix_543_xbz_variants_set_color_id.sql b/supabase/migrations/20260312130246_fix_543_xbz_variants_set_color_id.sql new file mode 100644 index 000000000..2cb02f140 --- /dev/null +++ b/supabase/migrations/20260312130246_fix_543_xbz_variants_set_color_id.sql @@ -0,0 +1,2 @@ +-- Migration 20260312130246 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312131220_fix_gap2_set_color_group_id.sql b/supabase/migrations/20260312131220_fix_gap2_set_color_group_id.sql new file mode 100644 index 000000000..7e48b8c73 --- /dev/null +++ b/supabase/migrations/20260312131220_fix_gap2_set_color_group_id.sql @@ -0,0 +1,2 @@ +-- Migration 20260312131220 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312131244_fix_gap1_xbz_color_equivalences_sync.sql b/supabase/migrations/20260312131244_fix_gap1_xbz_color_equivalences_sync.sql new file mode 100644 index 000000000..209d303a9 --- /dev/null +++ b/supabase/migrations/20260312131244_fix_gap1_xbz_color_equivalences_sync.sql @@ -0,0 +1,2 @@ +-- Migration 20260312131244 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312133004_fix_8_xbz_color_equivalences_decisions.sql b/supabase/migrations/20260312133004_fix_8_xbz_color_equivalences_decisions.sql new file mode 100644 index 000000000..96d99688c --- /dev/null +++ b/supabase/migrations/20260312133004_fix_8_xbz_color_equivalences_decisions.sql @@ -0,0 +1,2 @@ +-- Migration 20260312133004 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312133036_fix_verify_4_and_all_api_color_ids.sql b/supabase/migrations/20260312133036_fix_verify_4_and_all_api_color_ids.sql new file mode 100644 index 000000000..4fc237f00 --- /dev/null +++ b/supabase/migrations/20260312133036_fix_verify_4_and_all_api_color_ids.sql @@ -0,0 +1,2 @@ +-- Migration 20260312133036 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312133134_fix_xbz_variants_8_color_corrections.sql b/supabase/migrations/20260312133134_fix_xbz_variants_8_color_corrections.sql new file mode 100644 index 000000000..d32e6f7f5 --- /dev/null +++ b/supabase/migrations/20260312133134_fix_xbz_variants_8_color_corrections.sql @@ -0,0 +1,2 @@ +-- Migration 20260312133134 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312133241_fix_4_remaining_azul_generic_xbz.sql b/supabase/migrations/20260312133241_fix_4_remaining_azul_generic_xbz.sql new file mode 100644 index 000000000..2e37f3718 --- /dev/null +++ b/supabase/migrations/20260312133241_fix_4_remaining_azul_generic_xbz.sql @@ -0,0 +1,2 @@ +-- Migration 20260312133241 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312150310_fix_azul_claro_to_piscina_and_update_hex.sql b/supabase/migrations/20260312150310_fix_azul_claro_to_piscina_and_update_hex.sql new file mode 100644 index 000000000..f609692fb --- /dev/null +++ b/supabase/migrations/20260312150310_fix_azul_claro_to_piscina_and_update_hex.sql @@ -0,0 +1,2 @@ +-- Migration 20260312150310 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312150622_create_fume_variation_and_3_new_xbz_colors.sql b/supabase/migrations/20260312150622_create_fume_variation_and_3_new_xbz_colors.sql new file mode 100644 index 000000000..d88a19187 --- /dev/null +++ b/supabase/migrations/20260312150622_create_fume_variation_and_3_new_xbz_colors.sql @@ -0,0 +1,2 @@ +-- Migration 20260312150622 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312150727_fix_equivs_create_3_new_update_hex_xbz_v2.sql b/supabase/migrations/20260312150727_fix_equivs_create_3_new_update_hex_xbz_v2.sql new file mode 100644 index 000000000..86827493b --- /dev/null +++ b/supabase/migrations/20260312150727_fix_equivs_create_3_new_update_hex_xbz_v2.sql @@ -0,0 +1,2 @@ +-- Migration 20260312150727 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312150749_fix_136_inox_variants_to_prata_acetinado.sql b/supabase/migrations/20260312150749_fix_136_inox_variants_to_prata_acetinado.sql new file mode 100644 index 000000000..951a6ec34 --- /dev/null +++ b/supabase/migrations/20260312150749_fix_136_inox_variants_to_prata_acetinado.sql @@ -0,0 +1,2 @@ +-- Migration 20260312150749 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312151950_create_color_analysis_staging.sql b/supabase/migrations/20260312151950_create_color_analysis_staging.sql new file mode 100644 index 000000000..ce6bea732 --- /dev/null +++ b/supabase/migrations/20260312151950_create_color_analysis_staging.sql @@ -0,0 +1,2 @@ +-- Migration 20260312151950 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260312152359_create_fn_get_unprocessed_color_variants.sql b/supabase/migrations/20260312152359_create_fn_get_unprocessed_color_variants.sql new file mode 100644 index 000000000..f926902de --- /dev/null +++ b/supabase/migrations/20260312152359_create_fn_get_unprocessed_color_variants.sql @@ -0,0 +1,2 @@ +-- Migration 20260312152359 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260313162233_drop_supplier_product_code_column.sql b/supabase/migrations/20260313162233_drop_supplier_product_code_column.sql new file mode 100644 index 000000000..634d8e686 --- /dev/null +++ b/supabase/migrations/20260313162233_drop_supplier_product_code_column.sql @@ -0,0 +1,2 @@ +-- Migration 20260313162233 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260313173534_create_asia_api_staging.sql b/supabase/migrations/20260313173534_create_asia_api_staging.sql new file mode 100644 index 000000000..849531a3f --- /dev/null +++ b/supabase/migrations/20260313173534_create_asia_api_staging.sql @@ -0,0 +1,2 @@ +-- Migration 20260313173534 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260313185228_fn_parse_asia_properties_and_normalize_dimensions.sql b/supabase/migrations/20260313185228_fn_parse_asia_properties_and_normalize_dimensions.sql new file mode 100644 index 000000000..d3877dc71 --- /dev/null +++ b/supabase/migrations/20260313185228_fn_parse_asia_properties_and_normalize_dimensions.sql @@ -0,0 +1,2 @@ +-- Migration 20260313185228 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260313190221_fix_fn_parse_asia_properties_gram_bugs.sql b/supabase/migrations/20260313190221_fix_fn_parse_asia_properties_gram_bugs.sql new file mode 100644 index 000000000..46a5f95a3 --- /dev/null +++ b/supabase/migrations/20260313190221_fix_fn_parse_asia_properties_gram_bugs.sql @@ -0,0 +1,2 @@ +-- Migration 20260313190221 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260313190347_fix_fn_parse_asia_v3_regex_posix.sql b/supabase/migrations/20260313190347_fix_fn_parse_asia_v3_regex_posix.sql new file mode 100644 index 000000000..5706bdf4f --- /dev/null +++ b/supabase/migrations/20260313190347_fix_fn_parse_asia_v3_regex_posix.sql @@ -0,0 +1,2 @@ +-- Migration 20260313190347 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260313193251_fix_capacity_functions_word_boundary_multivalue.sql b/supabase/migrations/20260313193251_fix_capacity_functions_word_boundary_multivalue.sql new file mode 100644 index 000000000..104739862 --- /dev/null +++ b/supabase/migrations/20260313193251_fix_capacity_functions_word_boundary_multivalue.sql @@ -0,0 +1,2 @@ +-- Migration 20260313193251 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260314133410_b4a5983b-76fc-4419-b422-a590dc0fa2ed.sql b/supabase/migrations/20260314133410_b4a5983b-76fc-4419-b422-a590dc0fa2ed.sql index 54b413fff..46fca94fd 100644 --- a/supabase/migrations/20260314133410_b4a5983b-76fc-4419-b422-a590dc0fa2ed.sql +++ b/supabase/migrations/20260314133410_b4a5983b-76fc-4419-b422-a590dc0fa2ed.sql @@ -1,6 +1,6 @@ -- Tabela para persistir queries lentas detectadas pela telemetria -CREATE TABLE public.query_telemetry ( +CREATE TABLE IF NOT EXISTS public.query_telemetry ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), operation text NOT NULL, table_name text, @@ -17,12 +17,13 @@ CREATE TABLE public.query_telemetry ( ); -- Index para queries recentes e por severidade -CREATE INDEX idx_query_telemetry_created ON public.query_telemetry (created_at DESC); -CREATE INDEX idx_query_telemetry_severity ON public.query_telemetry (severity, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_query_telemetry_created ON public.query_telemetry (created_at DESC); +CREATE INDEX IF NOT EXISTS idx_query_telemetry_severity ON public.query_telemetry (severity, created_at DESC); -- RLS: somente admins podem ler ALTER TABLE public.query_telemetry ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins can read telemetry" ON public.query_telemetry; CREATE POLICY "Admins can read telemetry" ON public.query_telemetry FOR SELECT diff --git a/supabase/migrations/20260314134333_11002479-89e7-4706-a703-aec28f773745.sql b/supabase/migrations/20260314134333_11002479-89e7-4706-a703-aec28f773745.sql index 3a881fda0..1ea6ca9d1 100644 --- a/supabase/migrations/20260314134333_11002479-89e7-4706-a703-aec28f773745.sql +++ b/supabase/migrations/20260314134333_11002479-89e7-4706-a703-aec28f773745.sql @@ -1,9 +1,11 @@ +DROP POLICY IF EXISTS "Admins can delete telemetry" ON public.query_telemetry; CREATE POLICY "Admins can delete telemetry" ON public.query_telemetry FOR DELETE TO authenticated USING (has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Service can insert telemetry" ON public.query_telemetry; CREATE POLICY "Service can insert telemetry" ON public.query_telemetry FOR INSERT TO authenticated diff --git a/supabase/migrations/20260314153953_create_kit_component_print_areas.sql b/supabase/migrations/20260314153953_create_kit_component_print_areas.sql new file mode 100644 index 000000000..9e138d955 --- /dev/null +++ b/supabase/migrations/20260314153953_create_kit_component_print_areas.sql @@ -0,0 +1,2 @@ +-- Migration 20260314153953 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260314172451_d2aeca58-41a5-487e-b0b5-7e43481ccf13.sql b/supabase/migrations/20260314172451_d2aeca58-41a5-487e-b0b5-7e43481ccf13.sql index 0c0bf1def..661544272 100644 --- a/supabase/migrations/20260314172451_d2aeca58-41a5-487e-b0b5-7e43481ccf13.sql +++ b/supabase/migrations/20260314172451_d2aeca58-41a5-487e-b0b5-7e43481ccf13.sql @@ -15,6 +15,7 @@ BEGIN AND tablename = 'objects' AND policyname = 'Public can view personalization images' ) THEN + DROP POLICY IF EXISTS "Public can view personalization images" ON storage.objects; CREATE POLICY "Public can view personalization images" ON storage.objects FOR SELECT @@ -34,6 +35,7 @@ BEGIN AND tablename = 'objects' AND policyname = 'Authenticated users can upload personalization images' ) THEN + DROP POLICY IF EXISTS "Authenticated users can upload personalization images" ON storage.objects; CREATE POLICY "Authenticated users can upload personalization images" ON storage.objects FOR INSERT @@ -53,6 +55,7 @@ BEGIN AND tablename = 'objects' AND policyname = 'Authenticated users can update own personalization images' ) THEN + DROP POLICY IF EXISTS "Authenticated users can update own personalization images" ON storage.objects; CREATE POLICY "Authenticated users can update own personalization images" ON storage.objects FOR UPDATE @@ -73,6 +76,7 @@ BEGIN AND tablename = 'objects' AND policyname = 'Authenticated users can delete own personalization images' ) THEN + DROP POLICY IF EXISTS "Authenticated users can delete own personalization images" ON storage.objects; CREATE POLICY "Authenticated users can delete own personalization images" ON storage.objects FOR DELETE diff --git a/supabase/migrations/20260314175106_78748479-ede7-49b7-a0b8-ec8a30da9de8.sql b/supabase/migrations/20260314175106_78748479-ede7-49b7-a0b8-ec8a30da9de8.sql index 074e1c744..c07bd2558 100644 --- a/supabase/migrations/20260314175106_78748479-ede7-49b7-a0b8-ec8a30da9de8.sql +++ b/supabase/migrations/20260314175106_78748479-ede7-49b7-a0b8-ec8a30da9de8.sql @@ -12,10 +12,12 @@ CREATE TABLE IF NOT EXISTS public.video_variant_links ( ALTER TABLE public.video_variant_links ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Authenticated users can read video variant links" ON public.video_variant_links; CREATE POLICY "Authenticated users can read video variant links" ON public.video_variant_links FOR SELECT TO authenticated USING (true); +DROP POLICY IF EXISTS "Admins can manage video variant links" ON public.video_variant_links; CREATE POLICY "Admins can manage video variant links" ON public.video_variant_links FOR ALL TO authenticated USING (has_role(auth.uid(), 'admin')) diff --git a/supabase/migrations/20260314190936_d626b027-21eb-4b1c-8f38-d896ba8f9810.sql b/supabase/migrations/20260314190936_d626b027-21eb-4b1c-8f38-d896ba8f9810.sql index 50fafca45..3fcdbfc72 100644 --- a/supabase/migrations/20260314190936_d626b027-21eb-4b1c-8f38-d896ba8f9810.sql +++ b/supabase/migrations/20260314190936_d626b027-21eb-4b1c-8f38-d896ba8f9810.sql @@ -10,6 +10,7 @@ VALUES ( ); -- Allow authenticated users to upload videos +DROP POLICY IF EXISTS "Authenticated users can upload videos" ON storage.objects; CREATE POLICY "Authenticated users can upload videos" ON storage.objects FOR INSERT @@ -17,6 +18,7 @@ TO authenticated WITH CHECK (bucket_id = 'product-videos'); -- Allow public read access to videos +DROP POLICY IF EXISTS "Public can view product videos" ON storage.objects; CREATE POLICY "Public can view product videos" ON storage.objects FOR SELECT @@ -24,6 +26,7 @@ TO public USING (bucket_id = 'product-videos'); -- Allow authenticated users to delete their uploads +DROP POLICY IF EXISTS "Authenticated users can delete videos" ON storage.objects; CREATE POLICY "Authenticated users can delete videos" ON storage.objects FOR DELETE diff --git a/supabase/migrations/20260316222148_fix_process_supplier_product_weight_column.sql b/supabase/migrations/20260316222148_fix_process_supplier_product_weight_column.sql new file mode 100644 index 000000000..fc24d6885 --- /dev/null +++ b/supabase/migrations/20260316222148_fix_process_supplier_product_weight_column.sql @@ -0,0 +1,2 @@ +-- Migration 20260316222148 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260316222235_fix_process_supplier_product_materials_jsonb.sql b/supabase/migrations/20260316222235_fix_process_supplier_product_materials_jsonb.sql new file mode 100644 index 000000000..1fc29ea34 --- /dev/null +++ b/supabase/migrations/20260316222235_fix_process_supplier_product_materials_jsonb.sql @@ -0,0 +1,2 @@ +-- Migration 20260316222235 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260316222647_fix_process_supplier_product_variant_conflict.sql b/supabase/migrations/20260316222647_fix_process_supplier_product_variant_conflict.sql new file mode 100644 index 000000000..dcbea769c --- /dev/null +++ b/supabase/migrations/20260316222647_fix_process_supplier_product_variant_conflict.sql @@ -0,0 +1,2 @@ +-- Migration 20260316222647 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260316222727_fix_process_supplier_product_variant_required_fields.sql b/supabase/migrations/20260316222727_fix_process_supplier_product_variant_required_fields.sql new file mode 100644 index 000000000..02b725150 --- /dev/null +++ b/supabase/migrations/20260316222727_fix_process_supplier_product_variant_required_fields.sql @@ -0,0 +1,2 @@ +-- Migration 20260316222727 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260317020422_d1251352-3a98-4279-8340-0394b71f2f21.sql b/supabase/migrations/20260317020422_d1251352-3a98-4279-8340-0394b71f2f21.sql index e8ba08ac1..79840121c 100644 --- a/supabase/migrations/20260317020422_d1251352-3a98-4279-8340-0394b71f2f21.sql +++ b/supabase/migrations/20260317020422_d1251352-3a98-4279-8340-0394b71f2f21.sql @@ -1,4 +1,4 @@ -CREATE TABLE public.cart_templates ( +CREATE TABLE IF NOT EXISTS public.cart_templates ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE, name text NOT NULL, @@ -10,6 +10,7 @@ CREATE TABLE public.cart_templates ( ALTER TABLE public.cart_templates ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can manage own templates" ON public.cart_templates; CREATE POLICY "Users can manage own templates" ON public.cart_templates FOR ALL diff --git a/supabase/migrations/20260317140334_f776e3da-1f10-452b-baaa-2529d92fe0a5.sql b/supabase/migrations/20260317140334_f776e3da-1f10-452b-baaa-2529d92fe0a5.sql index 4166a8d40..544e08bf6 100644 --- a/supabase/migrations/20260317140334_f776e3da-1f10-452b-baaa-2529d92fe0a5.sql +++ b/supabase/migrations/20260317140334_f776e3da-1f10-452b-baaa-2529d92fe0a5.sql @@ -4,23 +4,27 @@ VALUES ('supplier-logos', 'supplier-logos', true) ON CONFLICT (id) DO NOTHING; -- Allow authenticated users to upload to supplier-logos +DROP POLICY IF EXISTS "Authenticated users can upload supplier logos" ON storage.objects; CREATE POLICY "Authenticated users can upload supplier logos" ON storage.objects FOR INSERT TO authenticated WITH CHECK (bucket_id = 'supplier-logos'); -- Allow public read access +DROP POLICY IF EXISTS "Public read access for supplier logos" ON storage.objects; CREATE POLICY "Public read access for supplier logos" ON storage.objects FOR SELECT TO public USING (bucket_id = 'supplier-logos'); -- Allow authenticated users to update/delete their uploads +DROP POLICY IF EXISTS "Authenticated users can manage supplier logos" ON storage.objects; CREATE POLICY "Authenticated users can manage supplier logos" ON storage.objects FOR DELETE TO authenticated USING (bucket_id = 'supplier-logos'); +DROP POLICY IF EXISTS "Authenticated users can update supplier logos" ON storage.objects; CREATE POLICY "Authenticated users can update supplier logos" ON storage.objects FOR UPDATE TO authenticated diff --git a/supabase/migrations/20260317155554_ba3ad0d9-b31e-425a-9808-f271eeeece06.sql b/supabase/migrations/20260317155554_ba3ad0d9-b31e-425a-9808-f271eeeece06.sql index 6277dc3ef..0b31c0270 100644 --- a/supabase/migrations/20260317155554_ba3ad0d9-b31e-425a-9808-f271eeeece06.sql +++ b/supabase/migrations/20260317155554_ba3ad0d9-b31e-425a-9808-f271eeeece06.sql @@ -30,12 +30,14 @@ $$; DROP TRIGGER IF EXISTS prevent_profile_role_change_trigger ON public.profiles; -- Create the trigger +DROP TRIGGER IF EXISTS prevent_profile_role_change_trigger ON public.profiles; CREATE TRIGGER prevent_profile_role_change_trigger BEFORE UPDATE ON public.profiles FOR EACH ROW EXECUTE FUNCTION public.prevent_profile_role_change(); -- Recreate the UPDATE policy (same as before, trigger handles column protection) +DROP POLICY IF EXISTS "Users can update own profile" ON public.profiles; CREATE POLICY "Users can update own profile" ON public.profiles FOR UPDATE diff --git a/supabase/migrations/20260317194959_773dfabc-50d4-4d78-b9aa-14841212b934.sql b/supabase/migrations/20260317194959_773dfabc-50d4-4d78-b9aa-14841212b934.sql index f32ec9ce8..3b9384fc1 100644 --- a/supabase/migrations/20260317194959_773dfabc-50d4-4d78-b9aa-14841212b934.sql +++ b/supabase/migrations/20260317194959_773dfabc-50d4-4d78-b9aa-14841212b934.sql @@ -1,9 +1,12 @@ -- Create org_role enum +DO $$ BEGIN CREATE TYPE public.org_role AS ENUM ('owner', 'admin', 'member'); +EXCEPTION WHEN duplicate_object THEN NULL; +END $$; -- Organizations table -CREATE TABLE public.organizations ( +CREATE TABLE IF NOT EXISTS public.organizations ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), name text NOT NULL, slug text NOT NULL UNIQUE, @@ -16,7 +19,7 @@ CREATE TABLE public.organizations ( ); -- Organization members table -CREATE TABLE public.organization_members ( +CREATE TABLE IF NOT EXISTS public.organization_members ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), organization_id uuid NOT NULL REFERENCES public.organizations(id) ON DELETE CASCADE, user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE, @@ -72,24 +75,29 @@ AS $$ $$; -- RLS Policies for organizations +DROP POLICY IF EXISTS "Members can view their organizations" ON public.organizations; CREATE POLICY "Members can view their organizations" ON public.organizations FOR SELECT TO authenticated USING (id IN (SELECT public.get_user_org_ids(auth.uid()))); +DROP POLICY IF EXISTS "Owners can update their organization" ON public.organizations; CREATE POLICY "Owners can update their organization" ON public.organizations FOR UPDATE TO authenticated USING (public.has_org_role(auth.uid(), id, 'owner')) WITH CHECK (public.has_org_role(auth.uid(), id, 'owner')); +DROP POLICY IF EXISTS "Authenticated users can create organizations" ON public.organizations; CREATE POLICY "Authenticated users can create organizations" ON public.organizations FOR INSERT TO authenticated WITH CHECK (true); -- RLS Policies for organization_members +DROP POLICY IF EXISTS "Members can view org members" ON public.organization_members; CREATE POLICY "Members can view org members" ON public.organization_members FOR SELECT TO authenticated USING (organization_id IN (SELECT public.get_user_org_ids(auth.uid()))); +DROP POLICY IF EXISTS "Org admins/owners can insert members" ON public.organization_members; CREATE POLICY "Org admins/owners can insert members" ON public.organization_members FOR INSERT TO authenticated WITH CHECK ( @@ -98,11 +106,13 @@ CREATE POLICY "Org admins/owners can insert members" OR NOT EXISTS (SELECT 1 FROM public.organization_members WHERE organization_id = organization_members.organization_id) ); +DROP POLICY IF EXISTS "Org owners can update members" ON public.organization_members; CREATE POLICY "Org owners can update members" ON public.organization_members FOR UPDATE TO authenticated USING (public.has_org_role(auth.uid(), organization_id, 'owner')) WITH CHECK (public.has_org_role(auth.uid(), organization_id, 'owner')); +DROP POLICY IF EXISTS "Org owners can delete members" ON public.organization_members; CREATE POLICY "Org owners can delete members" ON public.organization_members FOR DELETE TO authenticated USING ( @@ -111,6 +121,6 @@ CREATE POLICY "Org owners can delete members" ); -- Indexes -CREATE INDEX idx_org_members_user_id ON public.organization_members(user_id); -CREATE INDEX idx_org_members_org_id ON public.organization_members(organization_id); -CREATE INDEX idx_organizations_slug ON public.organizations(slug); +CREATE INDEX IF NOT EXISTS idx_org_members_user_id ON public.organization_members(user_id); +CREATE INDEX IF NOT EXISTS idx_org_members_org_id ON public.organization_members(organization_id); +CREATE INDEX IF NOT EXISTS idx_organizations_slug ON public.organizations(slug); diff --git a/supabase/migrations/20260317195011_5ea4d303-7fb3-416a-8dd9-2beebe4f6112.sql b/supabase/migrations/20260317195011_5ea4d303-7fb3-416a-8dd9-2beebe4f6112.sql index 7135316f4..78ac355f5 100644 --- a/supabase/migrations/20260317195011_5ea4d303-7fb3-416a-8dd9-2beebe4f6112.sql +++ b/supabase/migrations/20260317195011_5ea4d303-7fb3-416a-8dd9-2beebe4f6112.sql @@ -1,6 +1,6 @@ -- Replace the overly permissive INSERT policy with a scoped one -DROP POLICY "Authenticated users can create organizations" ON public.organizations; +DROP POLICY IF EXISTS "Authenticated users can create organizations" ON public.organizations; CREATE POLICY "Authenticated users can create organizations" ON public.organizations FOR INSERT TO authenticated WITH CHECK (auth.uid() IS NOT NULL); diff --git a/supabase/migrations/20260317200129_4ffdbef0-6d17-4623-85f9-a67792e90fe0.sql b/supabase/migrations/20260317200129_4ffdbef0-6d17-4623-85f9-a67792e90fe0.sql index d4ecdf2f7..e6c5166f0 100644 --- a/supabase/migrations/20260317200129_4ffdbef0-6d17-4623-85f9-a67792e90fe0.sql +++ b/supabase/migrations/20260317200129_4ffdbef0-6d17-4623-85f9-a67792e90fe0.sql @@ -4,7 +4,7 @@ -- We need to allow SELECT for orgs where the user just created it -- Drop and recreate the SELECT policy to also allow seeing orgs you just created -DROP POLICY "Members can view their organizations" ON public.organizations; +DROP POLICY IF EXISTS "Members can view their organizations" ON public.organizations; CREATE POLICY "Members can view their organizations" ON public.organizations FOR SELECT TO authenticated diff --git a/supabase/migrations/20260317205124_5fdf0e1d-c8cb-49bd-8324-d63f86795020.sql b/supabase/migrations/20260317205124_5fdf0e1d-c8cb-49bd-8324-d63f86795020.sql index 8ecf8fde3..d856945a6 100644 --- a/supabase/migrations/20260317205124_5fdf0e1d-c8cb-49bd-8324-d63f86795020.sql +++ b/supabase/migrations/20260317205124_5fdf0e1d-c8cb-49bd-8324-d63f86795020.sql @@ -1,5 +1,5 @@ -CREATE TABLE public.product_price_history ( +CREATE TABLE IF NOT EXISTS public.product_price_history ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), product_id text NOT NULL, product_sku text, @@ -17,21 +17,24 @@ CREATE TABLE public.product_price_history ( created_at timestamptz NOT NULL DEFAULT now() ); -CREATE INDEX idx_price_history_product ON public.product_price_history(product_id); -CREATE INDEX idx_price_history_created ON public.product_price_history(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_price_history_product ON public.product_price_history(product_id); +CREATE INDEX IF NOT EXISTS idx_price_history_created ON public.product_price_history(created_at DESC); ALTER TABLE public.product_price_history ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Authenticated users can read price history" ON public.product_price_history; CREATE POLICY "Authenticated users can read price history" ON public.product_price_history FOR SELECT TO authenticated USING (true); +DROP POLICY IF EXISTS "Authenticated users can insert price history" ON public.product_price_history; CREATE POLICY "Authenticated users can insert price history" ON public.product_price_history FOR INSERT TO authenticated WITH CHECK (true); +DROP POLICY IF EXISTS "Admins can delete price history" ON public.product_price_history; CREATE POLICY "Admins can delete price history" ON public.product_price_history FOR DELETE TO authenticated diff --git a/supabase/migrations/20260317205135_fd451baf-9eb7-416d-943c-c36a5aa9d1f0.sql b/supabase/migrations/20260317205135_fd451baf-9eb7-416d-943c-c36a5aa9d1f0.sql index 77e4cd85b..e3e988c59 100644 --- a/supabase/migrations/20260317205135_fd451baf-9eb7-416d-943c-c36a5aa9d1f0.sql +++ b/supabase/migrations/20260317205135_fd451baf-9eb7-416d-943c-c36a5aa9d1f0.sql @@ -1,5 +1,5 @@ -DROP POLICY "Authenticated users can insert price history" ON public.product_price_history; +DROP POLICY IF EXISTS "Authenticated users can insert price history" ON public.product_price_history; CREATE POLICY "Users can insert own price records" ON public.product_price_history FOR INSERT TO authenticated diff --git a/supabase/migrations/20260317212837_5deaff1e-a171-4f3f-a601-6d83e2068fd9.sql b/supabase/migrations/20260317212837_5deaff1e-a171-4f3f-a601-6d83e2068fd9.sql index f07b2347a..51d1b673d 100644 --- a/supabase/migrations/20260317212837_5deaff1e-a171-4f3f-a601-6d83e2068fd9.sql +++ b/supabase/migrations/20260317212837_5deaff1e-a171-4f3f-a601-6d83e2068fd9.sql @@ -1,6 +1,6 @@ -- Create quote_comments table with thread support -CREATE TABLE public.quote_comments ( +CREATE TABLE IF NOT EXISTS public.quote_comments ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, quote_id TEXT NOT NULL, user_id UUID NOT NULL, @@ -15,6 +15,7 @@ CREATE TABLE public.quote_comments ( ALTER TABLE public.quote_comments ENABLE ROW LEVEL SECURITY; -- Authenticated users can read all comments (team collaboration) +DROP POLICY IF EXISTS "Authenticated users can read comments" ON public.quote_comments; CREATE POLICY "Authenticated users can read comments" ON public.quote_comments FOR SELECT @@ -22,6 +23,7 @@ TO authenticated USING (true); -- Users can insert their own comments +DROP POLICY IF EXISTS "Users can insert own comments" ON public.quote_comments; CREATE POLICY "Users can insert own comments" ON public.quote_comments FOR INSERT @@ -29,6 +31,7 @@ TO authenticated WITH CHECK (user_id = auth.uid()); -- Users can update their own comments +DROP POLICY IF EXISTS "Users can update own comments" ON public.quote_comments; CREATE POLICY "Users can update own comments" ON public.quote_comments FOR UPDATE @@ -37,6 +40,7 @@ USING (user_id = auth.uid()) WITH CHECK (user_id = auth.uid()); -- Users can delete own comments, admins can delete any +DROP POLICY IF EXISTS "Users can delete own comments" ON public.quote_comments; CREATE POLICY "Users can delete own comments" ON public.quote_comments FOR DELETE @@ -44,7 +48,7 @@ TO authenticated USING (user_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)); -- Indexes -CREATE INDEX idx_quote_comments_quote_id ON public.quote_comments(quote_id); -CREATE INDEX idx_quote_comments_parent_id ON public.quote_comments(parent_id); -CREATE INDEX idx_quote_comments_user_id ON public.quote_comments(user_id); -CREATE INDEX idx_quote_comments_created_at ON public.quote_comments(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_quote_comments_quote_id ON public.quote_comments(quote_id); +CREATE INDEX IF NOT EXISTS idx_quote_comments_parent_id ON public.quote_comments(parent_id); +CREATE INDEX IF NOT EXISTS idx_quote_comments_user_id ON public.quote_comments(user_id); +CREATE INDEX IF NOT EXISTS idx_quote_comments_created_at ON public.quote_comments(created_at DESC); diff --git a/supabase/migrations/20260317213620_f869ffe7-2023-4507-99c4-90bc90a6e84a.sql b/supabase/migrations/20260317213620_f869ffe7-2023-4507-99c4-90bc90a6e84a.sql index 106727649..8abad401e 100644 --- a/supabase/migrations/20260317213620_f869ffe7-2023-4507-99c4-90bc90a6e84a.sql +++ b/supabase/migrations/20260317213620_f869ffe7-2023-4507-99c4-90bc90a6e84a.sql @@ -1,6 +1,6 @@ -- Table for user saved filter presets -CREATE TABLE public.saved_filters ( +CREATE TABLE IF NOT EXISTS public.saved_filters ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE, name TEXT NOT NULL, @@ -17,26 +17,30 @@ CREATE TABLE public.saved_filters ( -- RLS ALTER TABLE public.saved_filters ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view own filters" ON public.saved_filters; CREATE POLICY "Users can view own filters" ON public.saved_filters FOR SELECT TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "Users can insert own filters" ON public.saved_filters; CREATE POLICY "Users can insert own filters" ON public.saved_filters FOR INSERT TO authenticated WITH CHECK (user_id = auth.uid()); +DROP POLICY IF EXISTS "Users can update own filters" ON public.saved_filters; CREATE POLICY "Users can update own filters" ON public.saved_filters FOR UPDATE TO authenticated USING (user_id = auth.uid()) WITH CHECK (user_id = auth.uid()); +DROP POLICY IF EXISTS "Users can delete own filters" ON public.saved_filters; CREATE POLICY "Users can delete own filters" ON public.saved_filters FOR DELETE TO authenticated USING (user_id = auth.uid()); -- Index for fast lookups -CREATE INDEX idx_saved_filters_user_context ON public.saved_filters(user_id, context); +CREATE INDEX IF NOT EXISTS idx_saved_filters_user_context ON public.saved_filters(user_id, context); diff --git a/supabase/migrations/20260317214344_7220ff37-54d9-40bb-84f7-024f87321175.sql b/supabase/migrations/20260317214344_7220ff37-54d9-40bb-84f7-024f87321175.sql index 96fdb3f62..fbd41469c 100644 --- a/supabase/migrations/20260317214344_7220ff37-54d9-40bb-84f7-024f87321175.sql +++ b/supabase/migrations/20260317214344_7220ff37-54d9-40bb-84f7-024f87321175.sql @@ -1,6 +1,6 @@ -- Tokens for public quote approval links -CREATE TABLE public.quote_approval_tokens ( +CREATE TABLE IF NOT EXISTS public.quote_approval_tokens ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), quote_id TEXT NOT NULL, token TEXT NOT NULL UNIQUE DEFAULT encode(gen_random_bytes(32), 'hex'), @@ -20,6 +20,7 @@ CREATE TABLE public.quote_approval_tokens ( ALTER TABLE public.quote_approval_tokens ENABLE ROW LEVEL SECURITY; -- Sellers can manage their own tokens +DROP POLICY IF EXISTS "Users can manage own approval tokens" ON public.quote_approval_tokens; CREATE POLICY "Users can manage own approval tokens" ON public.quote_approval_tokens FOR ALL TO authenticated @@ -27,23 +28,25 @@ CREATE POLICY "Users can manage own approval tokens" WITH CHECK (seller_id = auth.uid()); -- Anon users can read tokens by token value (for public page) +DROP POLICY IF EXISTS "Anyone can read by token" ON public.quote_approval_tokens; CREATE POLICY "Anyone can read by token" ON public.quote_approval_tokens FOR SELECT TO anon USING (true); -- Anon users can update response fields +DROP POLICY IF EXISTS "Anyone can update response" ON public.quote_approval_tokens; CREATE POLICY "Anyone can update response" ON public.quote_approval_tokens FOR UPDATE TO anon USING (true) WITH CHECK (true); -CREATE INDEX idx_approval_tokens_token ON public.quote_approval_tokens(token); -CREATE INDEX idx_approval_tokens_quote ON public.quote_approval_tokens(quote_id); +CREATE INDEX IF NOT EXISTS idx_approval_tokens_token ON public.quote_approval_tokens(token); +CREATE INDEX IF NOT EXISTS idx_approval_tokens_quote ON public.quote_approval_tokens(quote_id); -- Follow-up reminders for expiring quotes -CREATE TABLE public.follow_up_reminders ( +CREATE TABLE IF NOT EXISTS public.follow_up_reminders ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), quote_id TEXT NOT NULL, seller_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE, @@ -56,10 +59,11 @@ CREATE TABLE public.follow_up_reminders ( ALTER TABLE public.follow_up_reminders ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can manage own reminders" ON public.follow_up_reminders; CREATE POLICY "Users can manage own reminders" ON public.follow_up_reminders FOR ALL TO authenticated USING (seller_id = auth.uid()) WITH CHECK (seller_id = auth.uid()); -CREATE INDEX idx_follow_up_pending ON public.follow_up_reminders(is_sent, scheduled_for); +CREATE INDEX IF NOT EXISTS idx_follow_up_pending ON public.follow_up_reminders(is_sent, scheduled_for); diff --git a/supabase/migrations/20260317214358_74a298da-2fb1-4f86-a1f1-4408ccb78f58.sql b/supabase/migrations/20260317214358_74a298da-2fb1-4f86-a1f1-4408ccb78f58.sql index 5ffbc3f96..83679ed5e 100644 --- a/supabase/migrations/20260317214358_74a298da-2fb1-4f86-a1f1-4408ccb78f58.sql +++ b/supabase/migrations/20260317214358_74a298da-2fb1-4f86-a1f1-4408ccb78f58.sql @@ -1,6 +1,6 @@ -- Tighten anon update policy to only allow response-related updates -DROP POLICY "Anyone can update response" ON public.quote_approval_tokens; +DROP POLICY IF EXISTS "Anyone can update response" ON public.quote_approval_tokens; CREATE POLICY "Anon can update response fields only" ON public.quote_approval_tokens FOR UPDATE diff --git a/supabase/migrations/20260317222414_40f1b3e0-564b-40b4-84ec-819a732de4aa.sql b/supabase/migrations/20260317222414_40f1b3e0-564b-40b4-84ec-819a732de4aa.sql index 085ad33ab..3b09c94e0 100644 --- a/supabase/migrations/20260317222414_40f1b3e0-564b-40b4-84ec-819a732de4aa.sql +++ b/supabase/migrations/20260317222414_40f1b3e0-564b-40b4-84ec-819a732de4aa.sql @@ -1,4 +1,5 @@ -- Attach the existing prevent_profile_role_change function as a trigger +DROP TRIGGER IF EXISTS prevent_profile_role_change ON public.profiles; CREATE TRIGGER prevent_profile_role_change BEFORE UPDATE ON public.profiles FOR EACH ROW diff --git a/supabase/migrations/20260317222739_a1573d74-411b-4cec-b337-20f1f9c8c012.sql b/supabase/migrations/20260317222739_a1573d74-411b-4cec-b337-20f1f9c8c012.sql index dc016a632..d074fab1d 100644 --- a/supabase/migrations/20260317222739_a1573d74-411b-4cec-b337-20f1f9c8c012.sql +++ b/supabase/migrations/20260317222739_a1573d74-411b-4cec-b337-20f1f9c8c012.sql @@ -2,6 +2,7 @@ DROP POLICY IF EXISTS "Org admins/owners can insert members" ON public.organization_members; -- Owners can insert members with any role +DROP POLICY IF EXISTS "Org owners can insert members any role" ON public.organization_members; CREATE POLICY "Org owners can insert members any role" ON public.organization_members FOR INSERT @@ -11,6 +12,7 @@ WITH CHECK ( ); -- Admins can only insert members with 'member' role (no escalation) +DROP POLICY IF EXISTS "Org admins can insert members only" ON public.organization_members; CREATE POLICY "Org admins can insert members only" ON public.organization_members FOR INSERT diff --git a/supabase/migrations/20260320135344_625f7c16-8ef6-49e7-b1bc-251139acf5dd.sql b/supabase/migrations/20260320135344_625f7c16-8ef6-49e7-b1bc-251139acf5dd.sql index bd15c0e19..859286f79 100644 --- a/supabase/migrations/20260320135344_625f7c16-8ef6-49e7-b1bc-251139acf5dd.sql +++ b/supabase/migrations/20260320135344_625f7c16-8ef6-49e7-b1bc-251139acf5dd.sql @@ -8,12 +8,14 @@ FOR SELECT TO authenticated USING (seller_id = auth.uid()); +DROP POLICY IF EXISTS "Sellers can insert own tokens" ON public.quote_approval_tokens; CREATE POLICY "Sellers can insert own tokens" ON public.quote_approval_tokens FOR INSERT TO authenticated WITH CHECK (seller_id = auth.uid()); +DROP POLICY IF EXISTS "Sellers can update own tokens" ON public.quote_approval_tokens; CREATE POLICY "Sellers can update own tokens" ON public.quote_approval_tokens FOR UPDATE @@ -21,6 +23,7 @@ TO authenticated USING (seller_id = auth.uid()) WITH CHECK (seller_id = auth.uid()); +DROP POLICY IF EXISTS "Sellers can delete own tokens" ON public.quote_approval_tokens; CREATE POLICY "Sellers can delete own tokens" ON public.quote_approval_tokens FOR DELETE diff --git a/supabase/migrations/20260320141635_9ecbea1e-b434-4261-872a-30b190585e19.sql b/supabase/migrations/20260320141635_9ecbea1e-b434-4261-872a-30b190585e19.sql index 25742bc8e..cbe9a661f 100644 --- a/supabase/migrations/20260320141635_9ecbea1e-b434-4261-872a-30b190585e19.sql +++ b/supabase/migrations/20260320141635_9ecbea1e-b434-4261-872a-30b190585e19.sql @@ -1,40 +1,47 @@ -- P1 #5: Profiles INSERT policy (for edge cases beyond trigger) +DROP POLICY IF EXISTS "Users can insert own profile" ON public.profiles; CREATE POLICY "Users can insert own profile" ON public.profiles FOR INSERT TO authenticated WITH CHECK (user_id = auth.uid()); -- P2 #6: category_icons admin write policies +DROP POLICY IF EXISTS "Admins can insert category icons" ON public.category_icons; CREATE POLICY "Admins can insert category icons" ON public.category_icons FOR INSERT TO authenticated WITH CHECK (has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Admins can update category icons" ON public.category_icons; CREATE POLICY "Admins can update category icons" ON public.category_icons FOR UPDATE TO authenticated USING (has_role(auth.uid(), 'admin'::app_role)) WITH CHECK (has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Admins can delete category icons" ON public.category_icons; CREATE POLICY "Admins can delete category icons" ON public.category_icons FOR DELETE TO authenticated USING (has_role(auth.uid(), 'admin'::app_role)); -- P2 #7: user_onboarding DELETE policy +DROP POLICY IF EXISTS "Users can delete own onboarding" ON public.user_onboarding; CREATE POLICY "Users can delete own onboarding" ON public.user_onboarding FOR DELETE TO authenticated USING (user_id = auth.uid()); -- P2 #8: quote_comments — add manager visibility +DROP POLICY IF EXISTS "Managers can read all comments" ON public.quote_comments; CREATE POLICY "Managers can read all comments" ON public.quote_comments FOR SELECT TO authenticated USING (is_manager_or_admin()); -- P3 #12: product_price_history UPDATE for admins +DROP POLICY IF EXISTS "Admins can update price history" ON public.product_price_history; CREATE POLICY "Admins can update price history" ON public.product_price_history FOR UPDATE TO authenticated diff --git a/supabase/migrations/20260320171208_7037bbd1-0532-40f0-9d66-743f3e065127.sql b/supabase/migrations/20260320171208_7037bbd1-0532-40f0-9d66-743f3e065127.sql index 7a0fa971f..d17d0fb43 100644 --- a/supabase/migrations/20260320171208_7037bbd1-0532-40f0-9d66-743f3e065127.sql +++ b/supabase/migrations/20260320171208_7037bbd1-0532-40f0-9d66-743f3e065127.sql @@ -40,11 +40,13 @@ CREATE TABLE IF NOT EXISTS public.quotes ( ALTER TABLE public.quotes ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Sellers can manage own quotes" ON public.quotes; CREATE POLICY "Sellers can manage own quotes" ON public.quotes FOR ALL TO authenticated USING (seller_id = auth.uid() OR has_role(auth.uid(), 'admin')) WITH CHECK (seller_id = auth.uid() OR has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Managers can read all quotes" ON public.quotes; CREATE POLICY "Managers can read all quotes" ON public.quotes FOR SELECT TO authenticated USING (is_manager_or_admin()); @@ -71,6 +73,7 @@ CREATE TABLE IF NOT EXISTS public.quote_items ( ALTER TABLE public.quote_items ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can manage quote items via quote ownership" ON public.quote_items; CREATE POLICY "Users can manage quote items via quote ownership" ON public.quote_items FOR ALL TO authenticated USING (EXISTS (SELECT 1 FROM public.quotes q WHERE q.id = quote_items.quote_id AND (q.seller_id = auth.uid() OR has_role(auth.uid(), 'admin')))) @@ -98,6 +101,7 @@ CREATE TABLE IF NOT EXISTS public.quote_item_personalizations ( ALTER TABLE public.quote_item_personalizations ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can manage personalizations via quote ownership" ON public.quote_item_personalizations; CREATE POLICY "Users can manage personalizations via quote ownership" ON public.quote_item_personalizations FOR ALL TO authenticated USING (EXISTS ( @@ -129,6 +133,7 @@ CREATE TABLE IF NOT EXISTS public.quote_history ( ALTER TABLE public.quote_history ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can manage history via quote ownership" ON public.quote_history; CREATE POLICY "Users can manage history via quote ownership" ON public.quote_history FOR ALL TO authenticated USING (EXISTS (SELECT 1 FROM public.quotes q WHERE q.id = quote_history.quote_id AND (q.seller_id = auth.uid() OR has_role(auth.uid(), 'admin')))) @@ -156,6 +161,7 @@ CREATE TABLE IF NOT EXISTS public.quote_templates ( ALTER TABLE public.quote_templates ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Sellers can manage own templates" ON public.quote_templates; CREATE POLICY "Sellers can manage own templates" ON public.quote_templates FOR ALL TO authenticated USING (seller_id = auth.uid() OR has_role(auth.uid(), 'admin')) @@ -194,6 +200,7 @@ BEGIN END; $$; +DROP TRIGGER IF EXISTS trigger_generate_quote_number ON public.quotes; CREATE TRIGGER trigger_generate_quote_number BEFORE INSERT ON public.quotes FOR EACH ROW diff --git a/supabase/migrations/20260321200700_8f74fe5f-51a1-4980-860f-a145b6d14d44.sql b/supabase/migrations/20260321200700_8f74fe5f-51a1-4980-860f-a145b6d14d44.sql index 1eef60ab1..be4eaaf13 100644 --- a/supabase/migrations/20260321200700_8f74fe5f-51a1-4980-860f-a145b6d14d44.sql +++ b/supabase/migrations/20260321200700_8f74fe5f-51a1-4980-860f-a145b6d14d44.sql @@ -1,6 +1,7 @@ -- Fix #1: Allow sellers to see their own order_items (via future orders table linkage) -- For now, allow all authenticated users to read order_items +DROP POLICY IF EXISTS "Sellers can read order items" ON public.order_items; CREATE POLICY "Sellers can read order items" ON public.order_items FOR SELECT @@ -8,6 +9,7 @@ TO authenticated USING (true); -- Fix #2: Allow sellers to read comments on their own quotes +DROP POLICY IF EXISTS "Sellers can read comments on own quotes" ON own; CREATE POLICY "Sellers can read comments on own quotes" ON public.quote_comments FOR SELECT diff --git a/supabase/migrations/20260322010007_d4d996b0-d883-4e68-936d-5bcf4ad29032.sql b/supabase/migrations/20260322010007_d4d996b0-d883-4e68-936d-5bcf4ad29032.sql index bc14c5012..56e8d1d0e 100644 --- a/supabase/migrations/20260322010007_d4d996b0-d883-4e68-936d-5bcf4ad29032.sql +++ b/supabase/migrations/20260322010007_d4d996b0-d883-4e68-936d-5bcf4ad29032.sql @@ -1,6 +1,6 @@ -- 1. Create orders table -CREATE TABLE public.orders ( +CREATE TABLE IF NOT EXISTS public.orders ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), seller_id uuid NOT NULL, order_number text NOT NULL DEFAULT '', @@ -30,11 +30,13 @@ CREATE TABLE public.orders ( ALTER TABLE public.orders ENABLE ROW LEVEL SECURITY; -- RLS policies +DROP POLICY IF EXISTS "Sellers can manage own orders" ON public.orders; CREATE POLICY "Sellers can manage own orders" ON public.orders FOR ALL TO authenticated USING (seller_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)) WITH CHECK (seller_id = auth.uid() OR has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Managers can read all orders" ON public.orders; CREATE POLICY "Managers can read all orders" ON public.orders FOR SELECT TO authenticated USING (is_manager_or_admin()); @@ -67,12 +69,13 @@ BEGIN END; $$; +DROP TRIGGER IF EXISTS set_order_number ON public.orders; CREATE TRIGGER set_order_number BEFORE INSERT ON public.orders FOR EACH ROW EXECUTE FUNCTION generate_order_number(); -- 2. Create login_attempts table -CREATE TABLE public.login_attempts ( +CREATE TABLE IF NOT EXISTS public.login_attempts ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), email text NOT NULL, user_id uuid, @@ -87,10 +90,12 @@ CREATE TABLE public.login_attempts ( ALTER TABLE public.login_attempts ENABLE ROW LEVEL SECURITY; -- RLS: admins can read all, users can insert +DROP POLICY IF EXISTS "Admins can read all login attempts" ON public.login_attempts; CREATE POLICY "Admins can read all login attempts" ON public.login_attempts FOR SELECT TO authenticated USING (has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Authenticated can insert login attempts" ON public.login_attempts; CREATE POLICY "Authenticated can insert login attempts" ON public.login_attempts FOR INSERT TO authenticated WITH CHECK (true); diff --git a/supabase/migrations/20260322130651_add_trigger_pca_sync_products_count.sql b/supabase/migrations/20260322130651_add_trigger_pca_sync_products_count.sql new file mode 100644 index 000000000..35969ab5c --- /dev/null +++ b/supabase/migrations/20260322130651_add_trigger_pca_sync_products_count.sql @@ -0,0 +1,2 @@ +-- Migration 20260322130651 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260322130947_drop_old_trigger_products_count.sql b/supabase/migrations/20260322130947_drop_old_trigger_products_count.sql new file mode 100644 index 000000000..8a555a4c9 --- /dev/null +++ b/supabase/migrations/20260322130947_drop_old_trigger_products_count.sql @@ -0,0 +1,2 @@ +-- Migration 20260322130947 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260322132852_fix_functions_filter_active_products_in_pca_count.sql b/supabase/migrations/20260322132852_fix_functions_filter_active_products_in_pca_count.sql new file mode 100644 index 000000000..9502638ba --- /dev/null +++ b/supabase/migrations/20260322132852_fix_functions_filter_active_products_in_pca_count.sql @@ -0,0 +1,2 @@ +-- Migration 20260322132852 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260322133758_7dc8f3c8-e0a0-4b62-b9e6-75995b2199c5.sql b/supabase/migrations/20260322133758_7dc8f3c8-e0a0-4b62-b9e6-75995b2199c5.sql index 38d360149..4da709b8b 100644 --- a/supabase/migrations/20260322133758_7dc8f3c8-e0a0-4b62-b9e6-75995b2199c5.sql +++ b/supabase/migrations/20260322133758_7dc8f3c8-e0a0-4b62-b9e6-75995b2199c5.sql @@ -1,6 +1,6 @@ -- Tabela para persistir kits customizados montados pelos vendedores -CREATE TABLE public.custom_kits ( +CREATE TABLE IF NOT EXISTS public.custom_kits ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), user_id uuid NOT NULL, name text NOT NULL DEFAULT 'Kit sem nome', @@ -22,6 +22,7 @@ CREATE TABLE public.custom_kits ( ALTER TABLE public.custom_kits ENABLE ROW LEVEL SECURITY; -- Vendedores gerenciam seus próprios kits +DROP POLICY IF EXISTS "Users can manage own kits" ON public.custom_kits; CREATE POLICY "Users can manage own kits" ON public.custom_kits FOR ALL @@ -30,6 +31,7 @@ CREATE POLICY "Users can manage own kits" WITH CHECK (user_id = auth.uid() OR public.has_role(auth.uid(), 'admin'::app_role)); -- Admins podem ler todos +DROP POLICY IF EXISTS "Admins can read all kits" ON public.custom_kits; CREATE POLICY "Admins can read all kits" ON public.custom_kits FOR SELECT diff --git a/supabase/migrations/20260322143357_add_trigger_products_status_sync_category_count.sql b/supabase/migrations/20260322143357_add_trigger_products_status_sync_category_count.sql new file mode 100644 index 000000000..2274d092b --- /dev/null +++ b/supabase/migrations/20260322143357_add_trigger_products_status_sync_category_count.sql @@ -0,0 +1,2 @@ +-- Migration 20260322143357 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260322143406_drop_duplicate_unique_constraint_pca.sql b/supabase/migrations/20260322143406_drop_duplicate_unique_constraint_pca.sql new file mode 100644 index 000000000..bc693966e --- /dev/null +++ b/supabase/migrations/20260322143406_drop_duplicate_unique_constraint_pca.sql @@ -0,0 +1,2 @@ +-- Migration 20260322143406 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260322145733_gap5_trigger_sync_product_status_fields.sql b/supabase/migrations/20260322145733_gap5_trigger_sync_product_status_fields.sql new file mode 100644 index 000000000..b8a9b0554 --- /dev/null +++ b/supabase/migrations/20260322145733_gap5_trigger_sync_product_status_fields.sql @@ -0,0 +1,2 @@ +-- Migration 20260322145733 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260322153427_gap4_fix_sitemap_categories_exclude_empty_leaves.sql b/supabase/migrations/20260322153427_gap4_fix_sitemap_categories_exclude_empty_leaves.sql new file mode 100644 index 000000000..eb2424eaa --- /dev/null +++ b/supabase/migrations/20260322153427_gap4_fix_sitemap_categories_exclude_empty_leaves.sql @@ -0,0 +1,2 @@ +-- Migration 20260322153427 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260322153515_gap2_trigger_sync_descendants_count.sql b/supabase/migrations/20260322153515_gap2_trigger_sync_descendants_count.sql new file mode 100644 index 000000000..147e783c8 --- /dev/null +++ b/supabase/migrations/20260322153515_gap2_trigger_sync_descendants_count.sql @@ -0,0 +1,2 @@ +-- Migration 20260322153515 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260322174557_5c7ba509-7cee-4ad9-af9b-02830f40ea42.sql b/supabase/migrations/20260322174557_5c7ba509-7cee-4ad9-af9b-02830f40ea42.sql index 4fcace824..a30c46908 100644 --- a/supabase/migrations/20260322174557_5c7ba509-7cee-4ad9-af9b-02830f40ea42.sql +++ b/supabase/migrations/20260322174557_5c7ba509-7cee-4ad9-af9b-02830f40ea42.sql @@ -1,5 +1,5 @@ -CREATE TABLE public.kit_share_tokens ( +CREATE TABLE IF NOT EXISTS public.kit_share_tokens ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, kit_id UUID NOT NULL REFERENCES public.custom_kits(id) ON DELETE CASCADE, seller_id UUID NOT NULL, @@ -16,6 +16,7 @@ CREATE TABLE public.kit_share_tokens ( ALTER TABLE public.kit_share_tokens ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Sellers can manage own kit share tokens" ON public.kit_share_tokens; CREATE POLICY "Sellers can manage own kit share tokens" ON public.kit_share_tokens FOR ALL diff --git a/supabase/migrations/20260322224817_54541d0b-46a0-471b-8386-fd60f4bc7d34.sql b/supabase/migrations/20260322224817_54541d0b-46a0-471b-8386-fd60f4bc7d34.sql index 1e027d8a5..39d26e18f 100644 --- a/supabase/migrations/20260322224817_54541d0b-46a0-471b-8386-fd60f4bc7d34.sql +++ b/supabase/migrations/20260322224817_54541d0b-46a0-471b-8386-fd60f4bc7d34.sql @@ -3,6 +3,7 @@ DROP POLICY IF EXISTS "Users can insert own login attempts" ON public.login_atte -- Create new INSERT policy allowing both authenticated and anonymous inserts -- This is needed because failed login attempts happen before auth +DROP POLICY IF EXISTS "Anyone can insert login attempts" ON public.login_attempts; CREATE POLICY "Anyone can insert login attempts" ON public.login_attempts FOR INSERT @@ -10,6 +11,7 @@ TO authenticated WITH CHECK (true); -- Also add anonymous insert capability for pre-auth logging +DROP POLICY IF EXISTS "Anon can insert login attempts" ON public.login_attempts; CREATE POLICY "Anon can insert login attempts" ON public.login_attempts FOR INSERT diff --git a/supabase/migrations/20260323100300_create_lead_intelligence_schema.sql b/supabase/migrations/20260323100300_create_lead_intelligence_schema.sql new file mode 100644 index 000000000..ccf187912 --- /dev/null +++ b/supabase/migrations/20260323100300_create_lead_intelligence_schema.sql @@ -0,0 +1,2 @@ +-- Migration 20260323100300 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323104757_drop_dead_columns_wave1_product_variants.sql b/supabase/migrations/20260323104757_drop_dead_columns_wave1_product_variants.sql new file mode 100644 index 000000000..e3a1def2d --- /dev/null +++ b/supabase/migrations/20260323104757_drop_dead_columns_wave1_product_variants.sql @@ -0,0 +1,2 @@ +-- Migration 20260323104757 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323112838_add_bitrix_images_synced_at.sql b/supabase/migrations/20260323112838_add_bitrix_images_synced_at.sql new file mode 100644 index 000000000..e48a82af3 --- /dev/null +++ b/supabase/migrations/20260323112838_add_bitrix_images_synced_at.sql @@ -0,0 +1,2 @@ +-- Migration 20260323112838 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323114317_fix_views_before_drop_image_url.sql b/supabase/migrations/20260323114317_fix_views_before_drop_image_url.sql new file mode 100644 index 000000000..fc6fc21a0 --- /dev/null +++ b/supabase/migrations/20260323114317_fix_views_before_drop_image_url.sql @@ -0,0 +1,2 @@ +-- Migration 20260323114317 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323114408_drop_recreate_trigger_then_drop_columns.sql b/supabase/migrations/20260323114408_drop_recreate_trigger_then_drop_columns.sql new file mode 100644 index 000000000..3adb2ba6c --- /dev/null +++ b/supabase/migrations/20260323114408_drop_recreate_trigger_then_drop_columns.sql @@ -0,0 +1,2 @@ +-- Migration 20260323114408 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323140109_expand_origin_country_varchar.sql b/supabase/migrations/20260323140109_expand_origin_country_varchar.sql new file mode 100644 index 000000000..6eb25f06a --- /dev/null +++ b/supabase/migrations/20260323140109_expand_origin_country_varchar.sql @@ -0,0 +1,2 @@ +-- Migration 20260323140109 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323140133_fix_set_product_defaults_remove_country_of_origin.sql b/supabase/migrations/20260323140133_fix_set_product_defaults_remove_country_of_origin.sql new file mode 100644 index 000000000..7465c57f2 --- /dev/null +++ b/supabase/migrations/20260323140133_fix_set_product_defaults_remove_country_of_origin.sql @@ -0,0 +1,2 @@ +-- Migration 20260323140133 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323140144_fix_set_is_imported_remove_country_of_origin.sql b/supabase/migrations/20260323140144_fix_set_is_imported_remove_country_of_origin.sql new file mode 100644 index 000000000..fd84b47d0 --- /dev/null +++ b/supabase/migrations/20260323140144_fix_set_is_imported_remove_country_of_origin.sql @@ -0,0 +1,2 @@ +-- Migration 20260323140144 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323145546_052422d8-a771-4b36-a442-b706fbac18e7.sql b/supabase/migrations/20260323145546_052422d8-a771-4b36-a442-b706fbac18e7.sql index ecb5c92dc..98f394794 100644 --- a/supabase/migrations/20260323145546_052422d8-a771-4b36-a442-b706fbac18e7.sql +++ b/supabase/migrations/20260323145546_052422d8-a771-4b36-a442-b706fbac18e7.sql @@ -1,5 +1,5 @@ -CREATE TABLE public.permissions ( +CREATE TABLE IF NOT EXISTS public.permissions ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), code text NOT NULL UNIQUE, name text NOT NULL, @@ -11,12 +11,14 @@ CREATE TABLE public.permissions ( ALTER TABLE public.permissions ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins can manage permissions" ON public.permissions; CREATE POLICY "Admins can manage permissions" ON public.permissions FOR ALL TO authenticated USING (has_role(auth.uid(), 'admin'::app_role)) WITH CHECK (has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Authenticated users can read permissions" ON public.permissions; CREATE POLICY "Authenticated users can read permissions" ON public.permissions FOR SELECT TO authenticated diff --git a/supabase/migrations/20260323162846_a9ad25c6-da2e-4be9-89f4-08fd3af447ed.sql b/supabase/migrations/20260323162846_a9ad25c6-da2e-4be9-89f4-08fd3af447ed.sql index 4699f4a11..5d56aef4b 100644 --- a/supabase/migrations/20260323162846_a9ad25c6-da2e-4be9-89f4-08fd3af447ed.sql +++ b/supabase/migrations/20260323162846_a9ad25c6-da2e-4be9-89f4-08fd3af447ed.sql @@ -1,5 +1,5 @@ -- Junction table: maps app_role enum to permission codes -CREATE TABLE public.role_permissions ( +CREATE TABLE IF NOT EXISTS public.role_permissions ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), role app_role NOT NULL, permission_code text NOT NULL, @@ -11,6 +11,7 @@ CREATE TABLE public.role_permissions ( ALTER TABLE public.role_permissions ENABLE ROW LEVEL SECURITY; -- Admins can manage role_permissions +DROP POLICY IF EXISTS "Admins can manage role_permissions" ON public.role_permissions; CREATE POLICY "Admins can manage role_permissions" ON public.role_permissions FOR ALL TO authenticated @@ -18,6 +19,7 @@ CREATE POLICY "Admins can manage role_permissions" WITH CHECK (has_role(auth.uid(), 'admin')); -- Authenticated users can read role_permissions +DROP POLICY IF EXISTS "Authenticated users can read role_permissions" ON public.role_permissions; CREATE POLICY "Authenticated users can read role_permissions" ON public.role_permissions FOR SELECT TO authenticated diff --git a/supabase/migrations/20260323164400_3d7928d1-f21a-4599-b4a4-0af60c245542.sql b/supabase/migrations/20260323164400_3d7928d1-f21a-4599-b4a4-0af60c245542.sql index dc28881dc..12f5f9f2d 100644 --- a/supabase/migrations/20260323164400_3d7928d1-f21a-4599-b4a4-0af60c245542.sql +++ b/supabase/migrations/20260323164400_3d7928d1-f21a-4599-b4a4-0af60c245542.sql @@ -3,6 +3,7 @@ DROP POLICY IF EXISTS "Anon can insert login attempts" ON public.login_attempts; DROP POLICY IF EXISTS "Anyone can insert login attempts" ON public.login_attempts; -- Add policy allowing only service_role to insert (Edge Function uses service_role) +DROP POLICY IF EXISTS "Service role can insert login attempts" ON public.login_attempts; CREATE POLICY "Service role can insert login attempts" ON public.login_attempts FOR INSERT diff --git a/supabase/migrations/20260323222000_etapa_01_remover_unique_constraints_duplicadas.sql b/supabase/migrations/20260323222000_etapa_01_remover_unique_constraints_duplicadas.sql new file mode 100644 index 000000000..dc3525e7c --- /dev/null +++ b/supabase/migrations/20260323222000_etapa_01_remover_unique_constraints_duplicadas.sql @@ -0,0 +1,2 @@ +-- Migration 20260323222000 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323222014_etapa_02_remover_triggers_updated_at_duplicados.sql b/supabase/migrations/20260323222014_etapa_02_remover_triggers_updated_at_duplicados.sql new file mode 100644 index 000000000..c04645978 --- /dev/null +++ b/supabase/migrations/20260323222014_etapa_02_remover_triggers_updated_at_duplicados.sql @@ -0,0 +1,2 @@ +-- Migration 20260323222014 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323222040_etapa_03_remover_jsonb_nunca_usados.sql b/supabase/migrations/20260323222040_etapa_03_remover_jsonb_nunca_usados.sql new file mode 100644 index 000000000..6de80cacb --- /dev/null +++ b/supabase/migrations/20260323222040_etapa_03_remover_jsonb_nunca_usados.sql @@ -0,0 +1,2 @@ +-- Migration 20260323222040 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323222247_etapa_04a_swap_primary_34_produtos.sql b/supabase/migrations/20260323222247_etapa_04a_swap_primary_34_produtos.sql new file mode 100644 index 000000000..01caf4bbe --- /dev/null +++ b/supabase/migrations/20260323222247_etapa_04a_swap_primary_34_produtos.sql @@ -0,0 +1,2 @@ +-- Migration 20260323222247 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323222309_etapa_04b_update_2_produtos_sem_assignment.sql b/supabase/migrations/20260323222309_etapa_04b_update_2_produtos_sem_assignment.sql new file mode 100644 index 000000000..c5974ebd2 --- /dev/null +++ b/supabase/migrations/20260323222309_etapa_04b_update_2_produtos_sem_assignment.sql @@ -0,0 +1,2 @@ +-- Migration 20260323222309 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323222355_etapa_05_sincronizar_active_is_active_categories.sql b/supabase/migrations/20260323222355_etapa_05_sincronizar_active_is_active_categories.sql new file mode 100644 index 000000000..ae770bb13 --- /dev/null +++ b/supabase/migrations/20260323222355_etapa_05_sincronizar_active_is_active_categories.sql @@ -0,0 +1,2 @@ +-- Migration 20260323222355 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323222451_etapa_06a_triggers_updated_at_lote1_24_tabelas.sql b/supabase/migrations/20260323222451_etapa_06a_triggers_updated_at_lote1_24_tabelas.sql new file mode 100644 index 000000000..366ad6247 --- /dev/null +++ b/supabase/migrations/20260323222451_etapa_06a_triggers_updated_at_lote1_24_tabelas.sql @@ -0,0 +1,2 @@ +-- Migration 20260323222451 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323222524_etapa_06b_triggers_updated_at_lote2_19_tabelas.sql b/supabase/migrations/20260323222524_etapa_06b_triggers_updated_at_lote2_19_tabelas.sql new file mode 100644 index 000000000..f6058515a --- /dev/null +++ b/supabase/migrations/20260323222524_etapa_06b_triggers_updated_at_lote2_19_tabelas.sql @@ -0,0 +1,2 @@ +-- Migration 20260323222524 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323222538_etapa_07a_timestamps_timezone_lote1.sql b/supabase/migrations/20260323222538_etapa_07a_timestamps_timezone_lote1.sql new file mode 100644 index 000000000..d99b6c098 --- /dev/null +++ b/supabase/migrations/20260323222538_etapa_07a_timestamps_timezone_lote1.sql @@ -0,0 +1,2 @@ +-- Migration 20260323222538 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323222618_etapa_07b_timestamps_timezone_lote2_sem_spr.sql b/supabase/migrations/20260323222618_etapa_07b_timestamps_timezone_lote2_sem_spr.sql new file mode 100644 index 000000000..a531ccb36 --- /dev/null +++ b/supabase/migrations/20260323222618_etapa_07b_timestamps_timezone_lote2_sem_spr.sql @@ -0,0 +1,2 @@ +-- Migration 20260323222618 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323222709_etapa_07c_timestamps_spr_drop_views.sql b/supabase/migrations/20260323222709_etapa_07c_timestamps_spr_drop_views.sql new file mode 100644 index 000000000..1a9a65577 --- /dev/null +++ b/supabase/migrations/20260323222709_etapa_07c_timestamps_spr_drop_views.sql @@ -0,0 +1,2 @@ +-- Migration 20260323222709 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323225021_544d47f7-3124-4c33-9ea0-cc6cd8ab9652.sql b/supabase/migrations/20260323225021_544d47f7-3124-4c33-9ea0-cc6cd8ab9652.sql index 9d9b41405..305c3f827 100644 --- a/supabase/migrations/20260323225021_544d47f7-3124-4c33-9ea0-cc6cd8ab9652.sql +++ b/supabase/migrations/20260323225021_544d47f7-3124-4c33-9ea0-cc6cd8ab9652.sql @@ -1,5 +1,5 @@ -CREATE TABLE public.web_vitals ( +CREATE TABLE IF NOT EXISTS public.web_vitals ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), user_id uuid REFERENCES auth.users(id) ON DELETE SET NULL, metric_name text NOT NULL, @@ -14,13 +14,15 @@ CREATE TABLE public.web_vitals ( ALTER TABLE public.web_vitals ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins can read web vitals" ON public.web_vitals; CREATE POLICY "Admins can read web vitals" ON public.web_vitals FOR SELECT TO authenticated USING (has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Authenticated users can insert web vitals" ON public.web_vitals; CREATE POLICY "Authenticated users can insert web vitals" ON public.web_vitals FOR INSERT TO authenticated WITH CHECK (user_id = auth.uid()); -CREATE INDEX idx_web_vitals_created_at ON public.web_vitals (created_at DESC); -CREATE INDEX idx_web_vitals_metric_name ON public.web_vitals (metric_name); +CREATE INDEX IF NOT EXISTS idx_web_vitals_created_at ON public.web_vitals (created_at DESC); +CREATE INDEX IF NOT EXISTS idx_web_vitals_metric_name ON public.web_vitals (metric_name); diff --git a/supabase/migrations/20260323230201_etapa_07c_drop_views_spr_lote1.sql b/supabase/migrations/20260323230201_etapa_07c_drop_views_spr_lote1.sql new file mode 100644 index 000000000..49131f0bc --- /dev/null +++ b/supabase/migrations/20260323230201_etapa_07c_drop_views_spr_lote1.sql @@ -0,0 +1,2 @@ +-- Migration 20260323230201 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323230208_etapa_07c_drop_views_spr_lote2.sql b/supabase/migrations/20260323230208_etapa_07c_drop_views_spr_lote2.sql new file mode 100644 index 000000000..021e52432 --- /dev/null +++ b/supabase/migrations/20260323230208_etapa_07c_drop_views_spr_lote2.sql @@ -0,0 +1,2 @@ +-- Migration 20260323230208 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323230216_etapa_07c_alter_spr_timestamps.sql b/supabase/migrations/20260323230216_etapa_07c_alter_spr_timestamps.sql new file mode 100644 index 000000000..626b5c309 --- /dev/null +++ b/supabase/migrations/20260323230216_etapa_07c_alter_spr_timestamps.sql @@ -0,0 +1,2 @@ +-- Migration 20260323230216 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323230306_etapa_07c_alter_spr_created_at.sql b/supabase/migrations/20260323230306_etapa_07c_alter_spr_created_at.sql new file mode 100644 index 000000000..66bf167ab --- /dev/null +++ b/supabase/migrations/20260323230306_etapa_07c_alter_spr_created_at.sql @@ -0,0 +1,2 @@ +-- Migration 20260323230306 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323230442_etapa_07c_recreate_views_asia.sql b/supabase/migrations/20260323230442_etapa_07c_recreate_views_asia.sql new file mode 100644 index 000000000..13ca2debb --- /dev/null +++ b/supabase/migrations/20260323230442_etapa_07c_recreate_views_asia.sql @@ -0,0 +1,2 @@ +-- Migration 20260323230442 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323230455_etapa_07c_recreate_views_asia_2.sql b/supabase/migrations/20260323230455_etapa_07c_recreate_views_asia_2.sql new file mode 100644 index 000000000..74c253b8f --- /dev/null +++ b/supabase/migrations/20260323230455_etapa_07c_recreate_views_asia_2.sql @@ -0,0 +1,2 @@ +-- Migration 20260323230455 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323230514_etapa_07c_recreate_views_somarcas.sql b/supabase/migrations/20260323230514_etapa_07c_recreate_views_somarcas.sql new file mode 100644 index 000000000..d123f7a20 --- /dev/null +++ b/supabase/migrations/20260323230514_etapa_07c_recreate_views_somarcas.sql @@ -0,0 +1,2 @@ +-- Migration 20260323230514 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323230534_etapa_07c_recreate_views_xbz_generic.sql b/supabase/migrations/20260323230534_etapa_07c_recreate_views_xbz_generic.sql new file mode 100644 index 000000000..a068e5d3d --- /dev/null +++ b/supabase/migrations/20260323230534_etapa_07c_recreate_views_xbz_generic.sql @@ -0,0 +1,2 @@ +-- Migration 20260323230534 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323230823_etapa_09a_criar_supplier_technique_mappings.sql b/supabase/migrations/20260323230823_etapa_09a_criar_supplier_technique_mappings.sql new file mode 100644 index 000000000..f708c3ba8 --- /dev/null +++ b/supabase/migrations/20260323230823_etapa_09a_criar_supplier_technique_mappings.sql @@ -0,0 +1,2 @@ +-- Migration 20260323230823 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323230839_etapa_09b_drop_schema_supplier_mappings.sql b/supabase/migrations/20260323230839_etapa_09b_drop_schema_supplier_mappings.sql new file mode 100644 index 000000000..652f86eb0 --- /dev/null +++ b/supabase/migrations/20260323230839_etapa_09b_drop_schema_supplier_mappings.sql @@ -0,0 +1,2 @@ +-- Migration 20260323230839 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260323231007_etapa_10_renomear_trigger_cor_pt_para_en.sql b/supabase/migrations/20260323231007_etapa_10_renomear_trigger_cor_pt_para_en.sql new file mode 100644 index 000000000..b9e2f57b0 --- /dev/null +++ b/supabase/migrations/20260323231007_etapa_10_renomear_trigger_cor_pt_para_en.sql @@ -0,0 +1,2 @@ +-- Migration 20260323231007 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260324201423_2dcd7bae-b019-488e-82e9-909882093806.sql b/supabase/migrations/20260324201423_2dcd7bae-b019-488e-82e9-909882093806.sql index b8bc375c1..06cbb45b0 100644 --- a/supabase/migrations/20260324201423_2dcd7bae-b019-488e-82e9-909882093806.sql +++ b/supabase/migrations/20260324201423_2dcd7bae-b019-488e-82e9-909882093806.sql @@ -1,6 +1,6 @@ -- Tabela de locais/áreas de personalização do produto (CRUD local) -CREATE TABLE public.product_personalization_areas ( +CREATE TABLE IF NOT EXISTS public.product_personalization_areas ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), product_id text NOT NULL, component_id uuid REFERENCES public.product_components(id) ON DELETE SET NULL, @@ -23,6 +23,7 @@ CREATE TABLE public.product_personalization_areas ( -- RLS ALTER TABLE public.product_personalization_areas ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins can manage personalization areas" ON public.product_personalization_areas; CREATE POLICY "Admins can manage personalization areas" ON public.product_personalization_areas FOR ALL @@ -30,6 +31,7 @@ CREATE POLICY "Admins can manage personalization areas" USING (has_role(auth.uid(), 'admin'::app_role)) WITH CHECK (has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Authenticated users can read personalization areas" ON public.product_personalization_areas; CREATE POLICY "Authenticated users can read personalization areas" ON public.product_personalization_areas FOR SELECT @@ -37,4 +39,4 @@ CREATE POLICY "Authenticated users can read personalization areas" USING (true); -- Index para busca por produto -CREATE INDEX idx_personalization_areas_product ON public.product_personalization_areas(product_id); +CREATE INDEX IF NOT EXISTS idx_personalization_areas_product ON public.product_personalization_areas(product_id); diff --git a/supabase/migrations/20260325124134_358bb2ce-0972-48ac-95a5-54b456907dd5.sql b/supabase/migrations/20260325124134_358bb2ce-0972-48ac-95a5-54b456907dd5.sql index 85a030edc..7645d1ada 100644 --- a/supabase/migrations/20260325124134_358bb2ce-0972-48ac-95a5-54b456907dd5.sql +++ b/supabase/migrations/20260325124134_358bb2ce-0972-48ac-95a5-54b456907dd5.sql @@ -1,6 +1,6 @@ -- Tabela de fontes de fornecimento (multi-supplier por produto) -CREATE TABLE public.product_supplier_sources ( +CREATE TABLE IF NOT EXISTS public.product_supplier_sources ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), product_id text NOT NULL, supplier_id text NOT NULL, @@ -22,10 +22,12 @@ CREATE TABLE public.product_supplier_sources ( -- RLS ALTER TABLE public.product_supplier_sources ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Authenticated users can read supplier sources" ON public.product_supplier_sources; CREATE POLICY "Authenticated users can read supplier sources" ON public.product_supplier_sources FOR SELECT TO authenticated USING (true); +DROP POLICY IF EXISTS "Admins can manage supplier sources" ON public.product_supplier_sources; CREATE POLICY "Admins can manage supplier sources" ON public.product_supplier_sources FOR ALL TO authenticated @@ -33,4 +35,4 @@ CREATE POLICY "Admins can manage supplier sources" WITH CHECK (has_role(auth.uid(), 'admin'::app_role)); -- Index para busca por produto -CREATE INDEX idx_product_supplier_sources_product_id ON public.product_supplier_sources (product_id); +CREATE INDEX IF NOT EXISTS idx_product_supplier_sources_product_id ON public.product_supplier_sources (product_id); diff --git a/supabase/migrations/20260325152410_9454cf25-f255-46f5-8756-000d4bfb17ef.sql b/supabase/migrations/20260325152410_9454cf25-f255-46f5-8756-000d4bfb17ef.sql index 860a5a920..2def1074a 100644 --- a/supabase/migrations/20260325152410_9454cf25-f255-46f5-8756-000d4bfb17ef.sql +++ b/supabase/migrations/20260325152410_9454cf25-f255-46f5-8756-000d4bfb17ef.sql @@ -5,7 +5,7 @@ VALUES ('component-media', 'component-media', true) ON CONFLICT (id) DO NOTHING; -- Table to store media metadata for kit components -CREATE TABLE public.component_media ( +CREATE TABLE IF NOT EXISTS public.component_media ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, component_id TEXT NOT NULL, product_id TEXT NOT NULL, @@ -21,6 +21,7 @@ CREATE TABLE public.component_media ( -- RLS ALTER TABLE public.component_media ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins can manage component media" ON public.component_media; CREATE POLICY "Admins can manage component media" ON public.component_media FOR ALL @@ -28,6 +29,7 @@ CREATE POLICY "Admins can manage component media" USING (has_role(auth.uid(), 'admin'::app_role)) WITH CHECK (has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Authenticated users can read component media" ON public.component_media; CREATE POLICY "Authenticated users can read component media" ON public.component_media FOR SELECT @@ -35,12 +37,14 @@ CREATE POLICY "Authenticated users can read component media" USING (true); -- Storage policies for component-media bucket +DROP POLICY IF EXISTS "Admins can upload component media" ON storage.objects; CREATE POLICY "Admins can upload component media" ON storage.objects FOR INSERT TO authenticated WITH CHECK (bucket_id = 'component-media' AND has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Admins can update component media" ON storage.objects; CREATE POLICY "Admins can update component media" ON storage.objects FOR UPDATE @@ -48,12 +52,14 @@ CREATE POLICY "Admins can update component media" USING (bucket_id = 'component-media' AND has_role(auth.uid(), 'admin'::app_role)) WITH CHECK (bucket_id = 'component-media' AND has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Admins can delete component media" ON storage.objects; CREATE POLICY "Admins can delete component media" ON storage.objects FOR DELETE TO authenticated USING (bucket_id = 'component-media' AND has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Anyone can read component media" ON storage.objects; CREATE POLICY "Anyone can read component media" ON storage.objects FOR SELECT diff --git a/supabase/migrations/20260325174929_add_supplier_product_url_to_products.sql b/supabase/migrations/20260325174929_add_supplier_product_url_to_products.sql new file mode 100644 index 000000000..d9743ff18 --- /dev/null +++ b/supabase/migrations/20260325174929_add_supplier_product_url_to_products.sql @@ -0,0 +1,2 @@ +-- Migration 20260325174929 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260325181646_create_supplier_branches.sql b/supabase/migrations/20260325181646_create_supplier_branches.sql new file mode 100644 index 000000000..f656cd651 --- /dev/null +++ b/supabase/migrations/20260325181646_create_supplier_branches.sql @@ -0,0 +1,2 @@ +-- Migration 20260325181646 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260325181722_add_fiscal_fields_to_variant_supplier_sources.sql b/supabase/migrations/20260325181722_add_fiscal_fields_to_variant_supplier_sources.sql new file mode 100644 index 000000000..af0731bc7 --- /dev/null +++ b/supabase/migrations/20260325181722_add_fiscal_fields_to_variant_supplier_sources.sql @@ -0,0 +1,2 @@ +-- Migration 20260325181722 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260325181736_add_logistics_fields_and_supplier_uf.sql b/supabase/migrations/20260325181736_add_logistics_fields_and_supplier_uf.sql new file mode 100644 index 000000000..75d757373 --- /dev/null +++ b/supabase/migrations/20260325181736_add_logistics_fields_and_supplier_uf.sql @@ -0,0 +1,2 @@ +-- Migration 20260325181736 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260325185701_add_cst_and_natureza_to_vss.sql b/supabase/migrations/20260325185701_add_cst_and_natureza_to_vss.sql new file mode 100644 index 000000000..355b869fa --- /dev/null +++ b/supabase/migrations/20260325185701_add_cst_and_natureza_to_vss.sql @@ -0,0 +1,2 @@ +-- Migration 20260325185701 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260325190449_create_image_import_log.sql b/supabase/migrations/20260325190449_create_image_import_log.sql new file mode 100644 index 000000000..ef14850a7 --- /dev/null +++ b/supabase/migrations/20260325190449_create_image_import_log.sql @@ -0,0 +1,2 @@ +-- Migration 20260325190449 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260325202953_add_default_fiscal_fields_to_supplier_branches.sql b/supabase/migrations/20260325202953_add_default_fiscal_fields_to_supplier_branches.sql new file mode 100644 index 000000000..37e094fec --- /dev/null +++ b/supabase/migrations/20260325202953_add_default_fiscal_fields_to_supplier_branches.sql @@ -0,0 +1,2 @@ +-- Migration 20260325202953 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260326104412_add_missing_supplier_fields.sql b/supabase/migrations/20260326104412_add_missing_supplier_fields.sql new file mode 100644 index 000000000..853f5af2a --- /dev/null +++ b/supabase/migrations/20260326104412_add_missing_supplier_fields.sql @@ -0,0 +1,2 @@ +-- Migration 20260326104412 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260326130251_enhance_print_area_techniques_for_lovable.sql b/supabase/migrations/20260326130251_enhance_print_area_techniques_for_lovable.sql new file mode 100644 index 000000000..b6ac02b30 --- /dev/null +++ b/supabase/migrations/20260326130251_enhance_print_area_techniques_for_lovable.sql @@ -0,0 +1,2 @@ +-- Migration 20260326130251 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260326175316_fix_rpc_remove_gravacao_columns_ref.sql b/supabase/migrations/20260326175316_fix_rpc_remove_gravacao_columns_ref.sql new file mode 100644 index 000000000..ceceb90d8 --- /dev/null +++ b/supabase/migrations/20260326175316_fix_rpc_remove_gravacao_columns_ref.sql @@ -0,0 +1,2 @@ +-- Migration 20260326175316 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260326183706_drop_dead_functions_link_and_find.sql b/supabase/migrations/20260326183706_drop_dead_functions_link_and_find.sql new file mode 100644 index 000000000..002ca81c2 --- /dev/null +++ b/supabase/migrations/20260326183706_drop_dead_functions_link_and_find.sql @@ -0,0 +1,2 @@ +-- Migration 20260326183706 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260326183730_drop_fn_link_correct_signature.sql b/supabase/migrations/20260326183730_drop_fn_link_correct_signature.sql new file mode 100644 index 000000000..39938c87a --- /dev/null +++ b/supabase/migrations/20260326183730_drop_fn_link_correct_signature.sql @@ -0,0 +1,2 @@ +-- Migration 20260326183730 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260326191912_07b386c9-cb61-45d6-aa44-bf2452d07c0e.sql b/supabase/migrations/20260326191912_07b386c9-cb61-45d6-aa44-bf2452d07c0e.sql index 630353654..7e1f2af41 100644 --- a/supabase/migrations/20260326191912_07b386c9-cb61-45d6-aa44-bf2452d07c0e.sql +++ b/supabase/migrations/20260326191912_07b386c9-cb61-45d6-aa44-bf2452d07c0e.sql @@ -1,6 +1,6 @@ -- Admin audit log for tracking sensitive administrative actions -CREATE TABLE public.admin_audit_log ( +CREATE TABLE IF NOT EXISTS public.admin_audit_log ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), user_id uuid NOT NULL, action text NOT NULL, @@ -13,14 +13,15 @@ CREATE TABLE public.admin_audit_log ( ); -- Index for querying by user and time -CREATE INDEX idx_admin_audit_log_user_id ON public.admin_audit_log(user_id); -CREATE INDEX idx_admin_audit_log_created_at ON public.admin_audit_log(created_at DESC); -CREATE INDEX idx_admin_audit_log_action ON public.admin_audit_log(action); +CREATE INDEX IF NOT EXISTS idx_admin_audit_log_user_id ON public.admin_audit_log(user_id); +CREATE INDEX IF NOT EXISTS idx_admin_audit_log_created_at ON public.admin_audit_log(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_admin_audit_log_action ON public.admin_audit_log(action); -- Enable RLS ALTER TABLE public.admin_audit_log ENABLE ROW LEVEL SECURITY; -- Only admins can read audit logs +DROP POLICY IF EXISTS "Admins can read audit logs" ON public.admin_audit_log; CREATE POLICY "Admins can read audit logs" ON public.admin_audit_log FOR SELECT @@ -28,6 +29,7 @@ CREATE POLICY "Admins can read audit logs" USING (has_role(auth.uid(), 'admin'::app_role)); -- Authenticated users can insert audit entries (the function controls what gets logged) +DROP POLICY IF EXISTS "System can insert audit entries" ON public.admin_audit_log; CREATE POLICY "System can insert audit entries" ON public.admin_audit_log FOR INSERT diff --git a/supabase/migrations/20260326233438_000e3c29-1ae2-4a26-999d-9dd00b512064.sql b/supabase/migrations/20260326233438_000e3c29-1ae2-4a26-999d-9dd00b512064.sql index 96a8ee2f6..345aa7092 100644 --- a/supabase/migrations/20260326233438_000e3c29-1ae2-4a26-999d-9dd00b512064.sql +++ b/supabase/migrations/20260326233438_000e3c29-1ae2-4a26-999d-9dd00b512064.sql @@ -1,3 +1,4 @@ +DROP POLICY IF EXISTS "Users can read own web vitals" ON public.web_vitals; CREATE POLICY "Users can read own web vitals" ON public.web_vitals FOR SELECT diff --git a/supabase/migrations/20260327193336_create_stock_snapshots_and_daily_summary.sql b/supabase/migrations/20260327193336_create_stock_snapshots_and_daily_summary.sql new file mode 100644 index 000000000..8ee392dbb --- /dev/null +++ b/supabase/migrations/20260327193336_create_stock_snapshots_and_daily_summary.sql @@ -0,0 +1,2 @@ +-- Migration 20260327193336 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260327193354_create_stock_snapshot_trigger.sql b/supabase/migrations/20260327193354_create_stock_snapshot_trigger.sql new file mode 100644 index 000000000..327dd4f17 --- /dev/null +++ b/supabase/migrations/20260327193354_create_stock_snapshot_trigger.sql @@ -0,0 +1,2 @@ +-- Migration 20260327193354 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260327193429_create_stock_aggregation_and_cron_jobs.sql b/supabase/migrations/20260327193429_create_stock_aggregation_and_cron_jobs.sql new file mode 100644 index 000000000..f33419b32 --- /dev/null +++ b/supabase/migrations/20260327193429_create_stock_aggregation_and_cron_jobs.sql @@ -0,0 +1,2 @@ +-- Migration 20260327193429 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260327193551_create_stock_intelligence_views_v2.sql b/supabase/migrations/20260327193551_create_stock_intelligence_views_v2.sql new file mode 100644 index 000000000..8efd486dc --- /dev/null +++ b/supabase/migrations/20260327193551_create_stock_intelligence_views_v2.sql @@ -0,0 +1,2 @@ +-- Migration 20260327193551 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260328161056_fix_stock_module_permissions_and_populate_mvs.sql b/supabase/migrations/20260328161056_fix_stock_module_permissions_and_populate_mvs.sql new file mode 100644 index 000000000..2961ad104 --- /dev/null +++ b/supabase/migrations/20260328161056_fix_stock_module_permissions_and_populate_mvs.sql @@ -0,0 +1,2 @@ +-- Migration 20260328161056 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260329143900_create_product_similarity_groups.sql b/supabase/migrations/20260329143900_create_product_similarity_groups.sql new file mode 100644 index 000000000..6c3f6096f --- /dev/null +++ b/supabase/migrations/20260329143900_create_product_similarity_groups.sql @@ -0,0 +1,2 @@ +-- Migration 20260329143900 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260329171833_create_fn_product_market_intelligence.sql b/supabase/migrations/20260329171833_create_fn_product_market_intelligence.sql new file mode 100644 index 000000000..bc423b6b9 --- /dev/null +++ b/supabase/migrations/20260329171833_create_fn_product_market_intelligence.sql @@ -0,0 +1,2 @@ +-- Migration 20260329171833 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260329172204_fix_fn_aggregate_stock_daily_uuid_min.sql b/supabase/migrations/20260329172204_fix_fn_aggregate_stock_daily_uuid_min.sql new file mode 100644 index 000000000..c55430501 --- /dev/null +++ b/supabase/migrations/20260329172204_fix_fn_aggregate_stock_daily_uuid_min.sql @@ -0,0 +1,2 @@ +-- Migration 20260329172204 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260329225247_create_similarity_auto_derivation_triggers.sql b/supabase/migrations/20260329225247_create_similarity_auto_derivation_triggers.sql new file mode 100644 index 000000000..73914440a --- /dev/null +++ b/supabase/migrations/20260329225247_create_similarity_auto_derivation_triggers.sql @@ -0,0 +1,2 @@ +-- Migration 20260329225247 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260330104621_b1c5cde5-1d76-43c7-b27d-7ce25242435c.sql b/supabase/migrations/20260330104621_b1c5cde5-1d76-43c7-b27d-7ce25242435c.sql index 97f7eba82..ba0627945 100644 --- a/supabase/migrations/20260330104621_b1c5cde5-1d76-43c7-b27d-7ce25242435c.sql +++ b/supabase/migrations/20260330104621_b1c5cde5-1d76-43c7-b27d-7ce25242435c.sql @@ -1,5 +1,5 @@ -- Table for workspace notifications -CREATE TABLE public.workspace_notifications ( +CREATE TABLE IF NOT EXISTS public.workspace_notifications ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), user_id uuid NOT NULL, title text NOT NULL, @@ -14,22 +14,26 @@ CREATE TABLE public.workspace_notifications ( ALTER TABLE public.workspace_notifications ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can read own notifications" ON public.workspace_notifications; CREATE POLICY "Users can read own notifications" ON public.workspace_notifications FOR SELECT TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "Users can update own notifications" ON public.workspace_notifications; CREATE POLICY "Users can update own notifications" ON public.workspace_notifications FOR UPDATE TO authenticated USING (user_id = auth.uid()) WITH CHECK (user_id = auth.uid()); +DROP POLICY IF EXISTS "Users can delete own notifications" ON public.workspace_notifications; CREATE POLICY "Users can delete own notifications" ON public.workspace_notifications FOR DELETE TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "System can insert notifications" ON public.workspace_notifications; CREATE POLICY "System can insert notifications" ON public.workspace_notifications FOR INSERT TO authenticated @@ -37,5 +41,5 @@ CREATE POLICY "System can insert notifications" ALTER PUBLICATION supabase_realtime ADD TABLE public.workspace_notifications; -CREATE INDEX idx_workspace_notifications_user_unread +CREATE INDEX IF NOT EXISTS idx_workspace_notifications_user_unread ON public.workspace_notifications (user_id, is_read, created_at DESC); \ No newline at end of file diff --git a/supabase/migrations/20260330130624_create_similarity_validation_and_product_sync_triggers.sql b/supabase/migrations/20260330130624_create_similarity_validation_and_product_sync_triggers.sql new file mode 100644 index 000000000..5ea0afb92 --- /dev/null +++ b/supabase/migrations/20260330130624_create_similarity_validation_and_product_sync_triggers.sql @@ -0,0 +1,2 @@ +-- Migration 20260330130624 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260330155517_add_public_read_policy_product_relationships.sql b/supabase/migrations/20260330155517_add_public_read_policy_product_relationships.sql new file mode 100644 index 000000000..2880d1ee1 --- /dev/null +++ b/supabase/migrations/20260330155517_add_public_read_policy_product_relationships.sql @@ -0,0 +1,2 @@ +-- Migration 20260330155517 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260330172914_add_public_read_policies_catalog_tables.sql b/supabase/migrations/20260330172914_add_public_read_policies_catalog_tables.sql new file mode 100644 index 000000000..8a3ee588c --- /dev/null +++ b/supabase/migrations/20260330172914_add_public_read_policies_catalog_tables.sql @@ -0,0 +1,2 @@ +-- Migration 20260330172914 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260330205223_enable_rls_similarity_tables_and_fix_trigger_security.sql b/supabase/migrations/20260330205223_enable_rls_similarity_tables_and_fix_trigger_security.sql new file mode 100644 index 000000000..d4d40bbda --- /dev/null +++ b/supabase/migrations/20260330205223_enable_rls_similarity_tables_and_fix_trigger_security.sql @@ -0,0 +1,2 @@ +-- Migration 20260330205223 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260331105103_add_index_product_relationships_related_product_id.sql b/supabase/migrations/20260331105103_add_index_product_relationships_related_product_id.sql new file mode 100644 index 000000000..eaf51c1e9 --- /dev/null +++ b/supabase/migrations/20260331105103_add_index_product_relationships_related_product_id.sql @@ -0,0 +1,2 @@ +-- Migration 20260331105103 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260331121005_add_public_read_policies_lockout_tables.sql b/supabase/migrations/20260331121005_add_public_read_policies_lockout_tables.sql new file mode 100644 index 000000000..9fd6daeed --- /dev/null +++ b/supabase/migrations/20260331121005_add_public_read_policies_lockout_tables.sql @@ -0,0 +1,2 @@ +-- Migration 20260331121005 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260331121349_create_views_product_groups_for_frontend.sql b/supabase/migrations/20260331121349_create_views_product_groups_for_frontend.sql new file mode 100644 index 000000000..9ecda360a --- /dev/null +++ b/supabase/migrations/20260331121349_create_views_product_groups_for_frontend.sql @@ -0,0 +1,2 @@ +-- Migration 20260331121349 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260402110748_b0de83ce-b140-45e8-94e9-ddfd2394e4c5.sql b/supabase/migrations/20260402110748_b0de83ce-b140-45e8-94e9-ddfd2394e4c5.sql index 834ea785a..503a5d3f7 100644 --- a/supabase/migrations/20260402110748_b0de83ce-b140-45e8-94e9-ddfd2394e4c5.sql +++ b/supabase/migrations/20260402110748_b0de83ce-b140-45e8-94e9-ddfd2394e4c5.sql @@ -1,5 +1,5 @@ -- Create scheduled reports table -CREATE TABLE public.scheduled_reports ( +CREATE TABLE IF NOT EXISTS public.scheduled_reports ( id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id uuid NOT NULL, report_type text NOT NULL DEFAULT 'sales', @@ -20,21 +20,25 @@ CREATE TABLE public.scheduled_reports ( ALTER TABLE public.scheduled_reports ENABLE ROW LEVEL SECURITY; -- RLS Policies +DROP POLICY IF EXISTS "Users can view own scheduled reports" ON public.scheduled_reports; CREATE POLICY "Users can view own scheduled reports" ON public.scheduled_reports FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can create own scheduled reports" ON public.scheduled_reports; CREATE POLICY "Users can create own scheduled reports" ON public.scheduled_reports FOR INSERT WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can update own scheduled reports" ON public.scheduled_reports; CREATE POLICY "Users can update own scheduled reports" ON public.scheduled_reports FOR UPDATE USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can delete own scheduled reports" ON public.scheduled_reports; CREATE POLICY "Users can delete own scheduled reports" ON public.scheduled_reports FOR DELETE USING (auth.uid() = user_id); -- Index for cron job lookups -CREATE INDEX idx_scheduled_reports_next_run ON public.scheduled_reports(next_run_at) WHERE is_active = true; \ No newline at end of file +CREATE INDEX IF NOT EXISTS idx_scheduled_reports_next_run ON public.scheduled_reports(next_run_at) WHERE is_active = true; \ No newline at end of file diff --git a/supabase/migrations/20260402112639_5bd2b86f-e2ed-4592-ba30-28e73bd297ef.sql b/supabase/migrations/20260402112639_5bd2b86f-e2ed-4592-ba30-28e73bd297ef.sql index 65cd8e92e..e19a243f7 100644 --- a/supabase/migrations/20260402112639_5bd2b86f-e2ed-4592-ba30-28e73bd297ef.sql +++ b/supabase/migrations/20260402112639_5bd2b86f-e2ed-4592-ba30-28e73bd297ef.sql @@ -1,5 +1,5 @@ --- 1. Create function to generate secure random tokens (64 hex chars = 32 bytes) +-- 1. CREATE OR REPLACE function to generate secure random tokens (64 hex chars = 32 bytes) CREATE OR REPLACE FUNCTION public.generate_secure_token() RETURNS trigger LANGUAGE plpgsql @@ -14,12 +14,13 @@ END; $$; -- 2. Create trigger to auto-generate secure tokens on insert +DROP TRIGGER IF EXISTS trg_generate_secure_approval_token ON public.quote_approval_tokens; CREATE TRIGGER trg_generate_secure_approval_token BEFORE INSERT ON public.quote_approval_tokens FOR EACH ROW EXECUTE FUNCTION public.generate_secure_token(); --- 3. Create function to auto-invalidate token after response +-- 3. CREATE OR REPLACE function to auto-invalidate token after response CREATE OR REPLACE FUNCTION public.invalidate_used_approval_token() RETURNS trigger LANGUAGE plpgsql @@ -38,6 +39,7 @@ END; $$; -- 4. Create trigger for auto-invalidation +DROP TRIGGER IF EXISTS trg_invalidate_used_approval_token ON public.quote_approval_tokens; CREATE TRIGGER trg_invalidate_used_approval_token BEFORE UPDATE ON public.quote_approval_tokens FOR EACH ROW diff --git a/supabase/migrations/20260404160306_350650c2-1099-41a7-bc9f-1db35424776f.sql b/supabase/migrations/20260404160306_350650c2-1099-41a7-bc9f-1db35424776f.sql index 337aa6d23..9c3e2a8e0 100644 --- a/supabase/migrations/20260404160306_350650c2-1099-41a7-bc9f-1db35424776f.sql +++ b/supabase/migrations/20260404160306_350650c2-1099-41a7-bc9f-1db35424776f.sql @@ -39,6 +39,7 @@ DROP POLICY IF EXISTS "Sellers can manage own quotes" ON public.quotes; DROP POLICY IF EXISTS "Managers can read all quotes" ON public.quotes; -- New org-scoped RLS policies for quotes +DROP POLICY IF EXISTS "Sellers can manage own org quotes" ON public.quotes; CREATE POLICY "Sellers can manage own org quotes" ON public.quotes FOR ALL TO authenticated @@ -51,6 +52,7 @@ WITH CHECK ( OR has_role(auth.uid(), 'admin'::app_role) ); +DROP POLICY IF EXISTS "Managers can read org quotes" ON public.quotes; CREATE POLICY "Managers can read org quotes" ON public.quotes FOR SELECT TO authenticated @@ -63,6 +65,7 @@ DROP POLICY IF EXISTS "Sellers can manage own orders" ON public.orders; DROP POLICY IF EXISTS "Managers can read all orders" ON public.orders; -- New org-scoped RLS policies for orders +DROP POLICY IF EXISTS "Sellers can manage own org orders" ON public.orders; CREATE POLICY "Sellers can manage own org orders" ON public.orders FOR ALL TO authenticated @@ -75,6 +78,7 @@ WITH CHECK ( OR has_role(auth.uid(), 'admin'::app_role) ); +DROP POLICY IF EXISTS "Managers can read org orders" ON public.orders; CREATE POLICY "Managers can read org orders" ON public.orders FOR SELECT TO authenticated @@ -87,6 +91,7 @@ DROP POLICY IF EXISTS "Admins can manage order items" ON public.order_items; DROP POLICY IF EXISTS "Sellers can read own order items" ON public.order_items; -- New org-scoped RLS policies for order_items +DROP POLICY IF EXISTS "Users can manage org order items" ON public.order_items; CREATE POLICY "Users can manage org order items" ON public.order_items FOR ALL TO authenticated diff --git a/supabase/migrations/20260404163500_afefb07b-77e7-4fe2-922f-66ac19b612b7.sql b/supabase/migrations/20260404163500_afefb07b-77e7-4fe2-922f-66ac19b612b7.sql index d3eec8f0d..c9febd332 100644 --- a/supabase/migrations/20260404163500_afefb07b-77e7-4fe2-922f-66ac19b612b7.sql +++ b/supabase/migrations/20260404163500_afefb07b-77e7-4fe2-922f-66ac19b612b7.sql @@ -8,6 +8,7 @@ DROP POLICY IF EXISTS "Order seller can update items" ON public.order_items; DROP POLICY IF EXISTS "Order seller can delete items" ON public.order_items; -- SELECT: org members can view items in their org +DROP POLICY IF EXISTS "Org members can view order items" ON public.order_items; CREATE POLICY "Org members can view order items" ON public.order_items FOR SELECT TO authenticated USING ( @@ -15,6 +16,7 @@ USING ( ); -- INSERT: seller of the parent order or admin/manager +DROP POLICY IF EXISTS "Order seller can insert items" ON public.order_items; CREATE POLICY "Order seller can insert items" ON public.order_items FOR INSERT TO authenticated WITH CHECK ( @@ -29,6 +31,7 @@ WITH CHECK ( ); -- UPDATE: seller of the parent order or admin/manager +DROP POLICY IF EXISTS "Order seller can update items" ON public.order_items; CREATE POLICY "Order seller can update items" ON public.order_items FOR UPDATE TO authenticated USING ( @@ -43,6 +46,7 @@ USING ( ); -- DELETE: seller of the parent order or admin/manager +DROP POLICY IF EXISTS "Order seller can delete items" ON public.order_items; CREATE POLICY "Order seller can delete items" ON public.order_items FOR DELETE TO authenticated USING ( diff --git a/supabase/migrations/20260404163550_edcf9c40-4c2e-4375-b248-d08264af8184.sql b/supabase/migrations/20260404163550_edcf9c40-4c2e-4375-b248-d08264af8184.sql index 0fcf7122b..bef5b5b76 100644 --- a/supabase/migrations/20260404163550_edcf9c40-4c2e-4375-b248-d08264af8184.sql +++ b/supabase/migrations/20260404163550_edcf9c40-4c2e-4375-b248-d08264af8184.sql @@ -5,6 +5,7 @@ DROP POLICY IF EXISTS "Authenticated users can upload supplier logos" ON storage DROP POLICY IF EXISTS "Authenticated users can manage supplier logos" ON storage.objects; -- Create admin-only INSERT policy +DROP POLICY IF EXISTS "Only admins can upload supplier logos" ON storage.objects; CREATE POLICY "Only admins can upload supplier logos" ON storage.objects FOR INSERT TO authenticated WITH CHECK ( diff --git a/supabase/migrations/20260404163714_6bef3545-0f19-4cdf-a174-a2c36071f860.sql b/supabase/migrations/20260404163714_6bef3545-0f19-4cdf-a174-a2c36071f860.sql index 698716f75..1a09c5cc1 100644 --- a/supabase/migrations/20260404163714_6bef3545-0f19-4cdf-a174-a2c36071f860.sql +++ b/supabase/migrations/20260404163714_6bef3545-0f19-4cdf-a174-a2c36071f860.sql @@ -1,6 +1,7 @@ -- Block non-admin INSERT on user_roles to prevent privilege escalation -- The existing ALL policy only covers admins; we need an explicit restrictive INSERT +DROP POLICY IF EXISTS "Only admins can insert roles" ON public.user_roles; CREATE POLICY "Only admins can insert roles" ON public.user_roles FOR INSERT TO authenticated WITH CHECK ( diff --git a/supabase/migrations/20260404164216_ae3eec30-3ab7-4eea-9a92-515277964fe4.sql b/supabase/migrations/20260404164216_ae3eec30-3ab7-4eea-9a92-515277964fe4.sql index 994b02fec..c631a93bd 100644 --- a/supabase/migrations/20260404164216_ae3eec30-3ab7-4eea-9a92-515277964fe4.sql +++ b/supabase/migrations/20260404164216_ae3eec30-3ab7-4eea-9a92-515277964fe4.sql @@ -1,3 +1,4 @@ +DROP POLICY IF EXISTS "Only admins can update product videos" ON storage.objects; CREATE POLICY "Only admins can update product videos" ON storage.objects FOR UPDATE TO authenticated USING (bucket_id = 'product-videos' AND has_role(auth.uid(), 'admin'::app_role)) diff --git a/supabase/migrations/20260404171222_ce98e80f-4714-4121-9a56-4dedf6e4349a.sql b/supabase/migrations/20260404171222_ce98e80f-4714-4121-9a56-4dedf6e4349a.sql index ccc8986d9..585f99d5a 100644 --- a/supabase/migrations/20260404171222_ce98e80f-4714-4121-9a56-4dedf6e4349a.sql +++ b/supabase/migrations/20260404171222_ce98e80f-4714-4121-9a56-4dedf6e4349a.sql @@ -20,6 +20,7 @@ BEGIN END; $$; +DROP TRIGGER IF EXISTS trg_validate_report_email ON public.scheduled_reports; CREATE TRIGGER trg_validate_report_email BEFORE INSERT OR UPDATE ON public.scheduled_reports FOR EACH ROW diff --git a/supabase/migrations/20260405151750_70c023c3-3de1-482f-8b19-134acfbf9f34.sql b/supabase/migrations/20260405151750_70c023c3-3de1-482f-8b19-134acfbf9f34.sql index 2e120d76c..d149efb37 100644 --- a/supabase/migrations/20260405151750_70c023c3-3de1-482f-8b19-134acfbf9f34.sql +++ b/supabase/migrations/20260405151750_70c023c3-3de1-482f-8b19-134acfbf9f34.sql @@ -1,5 +1,5 @@ -- Create voice command analytics table -CREATE TABLE public.voice_command_logs ( +CREATE TABLE IF NOT EXISTS public.voice_command_logs ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID NOT NULL, transcript TEXT NOT NULL, @@ -15,6 +15,7 @@ CREATE TABLE public.voice_command_logs ( ALTER TABLE public.voice_command_logs ENABLE ROW LEVEL SECURITY; -- Users can view their own logs +DROP POLICY IF EXISTS "Users can view own voice logs" ON public.voice_command_logs; CREATE POLICY "Users can view own voice logs" ON public.voice_command_logs FOR SELECT @@ -22,6 +23,7 @@ TO authenticated USING (auth.uid() = user_id); -- Users can insert their own logs +DROP POLICY IF EXISTS "Users can insert own voice logs" ON public.voice_command_logs; CREATE POLICY "Users can insert own voice logs" ON public.voice_command_logs FOR INSERT @@ -29,6 +31,7 @@ TO authenticated WITH CHECK (auth.uid() = user_id); -- Admins/managers can view all logs +DROP POLICY IF EXISTS "Admins can view all voice logs" ON public.voice_command_logs; CREATE POLICY "Admins can view all voice logs" ON public.voice_command_logs FOR SELECT @@ -36,5 +39,5 @@ TO authenticated USING (public.is_manager_or_admin()); -- Index for querying by user and date -CREATE INDEX idx_voice_command_logs_user_created +CREATE INDEX IF NOT EXISTS idx_voice_command_logs_user_created ON public.voice_command_logs (user_id, created_at DESC); \ No newline at end of file diff --git a/supabase/migrations/20260405211717_product_classification_columns.sql b/supabase/migrations/20260405211717_product_classification_columns.sql new file mode 100644 index 000000000..f43c31363 --- /dev/null +++ b/supabase/migrations/20260405211717_product_classification_columns.sql @@ -0,0 +1,2 @@ +-- Migration 20260405211717 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260405214122_enable_rls_all_tables_fuchsia_v2.sql b/supabase/migrations/20260405214122_enable_rls_all_tables_fuchsia_v2.sql new file mode 100644 index 000000000..f142f9df8 --- /dev/null +++ b/supabase/migrations/20260405214122_enable_rls_all_tables_fuchsia_v2.sql @@ -0,0 +1,2 @@ +-- Migration 20260405214122 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260405222509_610eaeb7-2cad-4cf8-aaf9-f4a4be5b9e55.sql b/supabase/migrations/20260405222509_610eaeb7-2cad-4cf8-aaf9-f4a4be5b9e55.sql index 1e43288cb..9626f213c 100644 --- a/supabase/migrations/20260405222509_610eaeb7-2cad-4cf8-aaf9-f4a4be5b9e55.sql +++ b/supabase/migrations/20260405222509_610eaeb7-2cad-4cf8-aaf9-f4a4be5b9e55.sql @@ -1 +1 @@ -ALTER PUBLICATION supabase_realtime DROP TABLE public.workspace_notifications; \ No newline at end of file +ALTER PUBLICATION supabase_realtime DROP TABLE IF EXISTS public.workspace_notifications; \ No newline at end of file diff --git a/supabase/migrations/20260405223038_perf_trigram_index_products_v2.sql b/supabase/migrations/20260405223038_perf_trigram_index_products_v2.sql new file mode 100644 index 000000000..6519d3213 --- /dev/null +++ b/supabase/migrations/20260405223038_perf_trigram_index_products_v2.sql @@ -0,0 +1,2 @@ +-- Migration 20260405223038 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260406124228_503718ad-7705-4325-8e04-b59adc685af3.sql b/supabase/migrations/20260406124228_503718ad-7705-4325-8e04-b59adc685af3.sql index 5f0330439..a1ea68024 100644 --- a/supabase/migrations/20260406124228_503718ad-7705-4325-8e04-b59adc685af3.sql +++ b/supabase/migrations/20260406124228_503718ad-7705-4325-8e04-b59adc685af3.sql @@ -2,6 +2,7 @@ DROP POLICY IF EXISTS "Authenticated users can insert web vitals" ON public.web_vitals; -- Recreate with explicit NOT NULL check on auth.uid() +DROP POLICY IF EXISTS "Authenticated users can insert web vitals" ON public.web_vitals; CREATE POLICY "Authenticated users can insert web vitals" ON public.web_vitals FOR INSERT diff --git a/supabase/migrations/20260406202212_20735579-941a-46d2-b872-abe769fe774a.sql b/supabase/migrations/20260406202212_20735579-941a-46d2-b872-abe769fe774a.sql index 9fafca01a..b239794fa 100644 --- a/supabase/migrations/20260406202212_20735579-941a-46d2-b872-abe769fe774a.sql +++ b/supabase/migrations/20260406202212_20735579-941a-46d2-b872-abe769fe774a.sql @@ -1,6 +1,6 @@ -- Table: ai_usage_logs -CREATE TABLE public.ai_usage_logs ( +CREATE TABLE IF NOT EXISTS public.ai_usage_logs ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), user_id uuid NOT NULL, function_name text NOT NULL, @@ -17,31 +17,34 @@ CREATE TABLE public.ai_usage_logs ( ); -- Indexes -CREATE INDEX idx_ai_usage_logs_user_id ON public.ai_usage_logs(user_id); -CREATE INDEX idx_ai_usage_logs_created_at ON public.ai_usage_logs(created_at); -CREATE INDEX idx_ai_usage_logs_function ON public.ai_usage_logs(function_name); -CREATE INDEX idx_ai_usage_logs_user_month ON public.ai_usage_logs(user_id, created_at); +CREATE INDEX IF NOT EXISTS idx_ai_usage_logs_user_id ON public.ai_usage_logs(user_id); +CREATE INDEX IF NOT EXISTS idx_ai_usage_logs_created_at ON public.ai_usage_logs(created_at); +CREATE INDEX IF NOT EXISTS idx_ai_usage_logs_function ON public.ai_usage_logs(function_name); +CREATE INDEX IF NOT EXISTS idx_ai_usage_logs_user_month ON public.ai_usage_logs(user_id, created_at); -- RLS ALTER TABLE public.ai_usage_logs ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view own AI usage logs" ON public.ai_usage_logs; CREATE POLICY "Users can view own AI usage logs" ON public.ai_usage_logs FOR SELECT TO authenticated USING (user_id = auth.uid()); +DROP POLICY IF EXISTS "Admins can view all AI usage logs" ON public.ai_usage_logs; CREATE POLICY "Admins can view all AI usage logs" ON public.ai_usage_logs FOR SELECT TO authenticated USING (has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Service role can insert AI usage logs" ON public.ai_usage_logs; CREATE POLICY "Service role can insert AI usage logs" ON public.ai_usage_logs FOR INSERT TO service_role WITH CHECK (true); -- Table: ai_usage_quotas -CREATE TABLE public.ai_usage_quotas ( +CREATE TABLE IF NOT EXISTS public.ai_usage_quotas ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), role app_role NOT NULL UNIQUE, monthly_limit integer NOT NULL DEFAULT 100, @@ -52,11 +55,13 @@ CREATE TABLE public.ai_usage_quotas ( ALTER TABLE public.ai_usage_quotas ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Authenticated users can read quotas" ON public.ai_usage_quotas; CREATE POLICY "Authenticated users can read quotas" ON public.ai_usage_quotas FOR SELECT TO authenticated USING (true); +DROP POLICY IF EXISTS "Admins can manage quotas" ON public.ai_usage_quotas; CREATE POLICY "Admins can manage quotas" ON public.ai_usage_quotas FOR ALL TO authenticated diff --git a/supabase/migrations/20260407014300_2724b8ff-1566-4bf2-b056-833e45cf0b85.sql b/supabase/migrations/20260407014300_2724b8ff-1566-4bf2-b056-833e45cf0b85.sql index d2fa0623b..2e83a03f3 100644 --- a/supabase/migrations/20260407014300_2724b8ff-1566-4bf2-b056-833e45cf0b85.sql +++ b/supabase/migrations/20260407014300_2724b8ff-1566-4bf2-b056-833e45cf0b85.sql @@ -1,6 +1,7 @@ -- Add UPDATE policy for service_role on ai_usage_logs -- This documents the existing behavior where updateAiLog() uses service_role +DROP POLICY IF EXISTS "Service role can update AI usage logs" ON public.ai_usage_logs; CREATE POLICY "Service role can update AI usage logs" ON public.ai_usage_logs FOR UPDATE diff --git a/supabase/migrations/20260408163551_zapp_test_setup_isolated_schema.sql b/supabase/migrations/20260408163551_zapp_test_setup_isolated_schema.sql new file mode 100644 index 000000000..8ca5db4df --- /dev/null +++ b/supabase/migrations/20260408163551_zapp_test_setup_isolated_schema.sql @@ -0,0 +1,2 @@ +-- Migration 20260408163551 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260408163609_zapp_test_create_call_transfers_table.sql b/supabase/migrations/20260408163609_zapp_test_create_call_transfers_table.sql new file mode 100644 index 000000000..fb96f4abe --- /dev/null +++ b/supabase/migrations/20260408163609_zapp_test_create_call_transfers_table.sql @@ -0,0 +1,2 @@ +-- Migration 20260408163609 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260408163655_zapp_test_create_rpcs.sql b/supabase/migrations/20260408163655_zapp_test_create_rpcs.sql new file mode 100644 index 000000000..f903c55aa --- /dev/null +++ b/supabase/migrations/20260408163655_zapp_test_create_rpcs.sql @@ -0,0 +1,2 @@ +-- Migration 20260408163655 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260410165642_7339bf0f-8ade-45d9-9065-79663e2c2364.sql b/supabase/migrations/20260410165642_7339bf0f-8ade-45d9-9065-79663e2c2364.sql index 096295fc5..be2014d76 100644 --- a/supabase/migrations/20260410165642_7339bf0f-8ade-45d9-9065-79663e2c2364.sql +++ b/supabase/migrations/20260410165642_7339bf0f-8ade-45d9-9065-79663e2c2364.sql @@ -110,16 +110,19 @@ END; $$; -- Create triggers +DROP TRIGGER IF EXISTS trg_notify_quote_status_change ON public.quotes; CREATE TRIGGER trg_notify_quote_status_change AFTER UPDATE ON public.quotes FOR EACH ROW EXECUTE FUNCTION public.notify_quote_status_change(); +DROP TRIGGER IF EXISTS trg_notify_new_order ON public.orders; CREATE TRIGGER trg_notify_new_order AFTER INSERT ON public.orders FOR EACH ROW EXECUTE FUNCTION public.notify_new_order(); +DROP TRIGGER IF EXISTS trg_notify_quote_client_response ON public.quote_approval_tokens; CREATE TRIGGER trg_notify_quote_client_response AFTER UPDATE ON public.quote_approval_tokens FOR EACH ROW diff --git a/supabase/migrations/20260411210929_9736ba78-4ddb-466f-b54d-c1c5f9d0d35f.sql b/supabase/migrations/20260411210929_9736ba78-4ddb-466f-b54d-c1c5f9d0d35f.sql index 1e43288cb..9626f213c 100644 --- a/supabase/migrations/20260411210929_9736ba78-4ddb-466f-b54d-c1c5f9d0d35f.sql +++ b/supabase/migrations/20260411210929_9736ba78-4ddb-466f-b54d-c1c5f9d0d35f.sql @@ -1 +1 @@ -ALTER PUBLICATION supabase_realtime DROP TABLE public.workspace_notifications; \ No newline at end of file +ALTER PUBLICATION supabase_realtime DROP TABLE IF EXISTS public.workspace_notifications; \ No newline at end of file diff --git a/supabase/migrations/20260412182408_a60c0965-6c47-4779-82e3-a2bbc011e204.sql b/supabase/migrations/20260412182408_a60c0965-6c47-4779-82e3-a2bbc011e204.sql index 46f4dbec5..c40e92e24 100644 --- a/supabase/migrations/20260412182408_a60c0965-6c47-4779-82e3-a2bbc011e204.sql +++ b/supabase/migrations/20260412182408_a60c0965-6c47-4779-82e3-a2bbc011e204.sql @@ -9,7 +9,7 @@ END; $$ LANGUAGE plpgsql SET search_path = public; -- Tabela de coleções -CREATE TABLE public.collections ( +CREATE TABLE IF NOT EXISTS public.collections ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID NOT NULL, name TEXT NOT NULL, @@ -21,7 +21,7 @@ CREATE TABLE public.collections ( ); -- Tabela de itens da coleção -CREATE TABLE public.collection_items ( +CREATE TABLE IF NOT EXISTS public.collection_items ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, collection_id UUID NOT NULL REFERENCES public.collections(id) ON DELETE CASCADE, product_id TEXT NOT NULL, @@ -34,18 +34,20 @@ CREATE TABLE public.collection_items ( ); -- Índices -CREATE INDEX idx_collections_user_id ON public.collections(user_id); -CREATE INDEX idx_collection_items_collection_id ON public.collection_items(collection_id); +CREATE INDEX IF NOT EXISTS idx_collections_user_id ON public.collections(user_id); +CREATE INDEX IF NOT EXISTS idx_collection_items_collection_id ON public.collection_items(collection_id); -- RLS ALTER TABLE public.collections ENABLE ROW LEVEL SECURITY; ALTER TABLE public.collection_items ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can manage own collections" ON public.collections; CREATE POLICY "Users can manage own collections" ON public.collections FOR ALL USING (user_id = auth.uid()) WITH CHECK (user_id = auth.uid()); +DROP POLICY IF EXISTS "Users can manage own collection items" ON public.collection_items; CREATE POLICY "Users can manage own collection items" ON public.collection_items FOR ALL USING (EXISTS ( @@ -60,6 +62,7 @@ CREATE POLICY "Users can manage own collection items" )); -- Trigger +DROP TRIGGER IF EXISTS update_collections_updated_at ON public.collections; CREATE TRIGGER update_collections_updated_at BEFORE UPDATE ON public.collections FOR EACH ROW diff --git a/supabase/migrations/20260412183140_b930bf89-5953-41dc-be97-45c56737810d.sql b/supabase/migrations/20260412183140_b930bf89-5953-41dc-be97-45c56737810d.sql index 2276525b3..49691781a 100644 --- a/supabase/migrations/20260412183140_b930bf89-5953-41dc-be97-45c56737810d.sql +++ b/supabase/migrations/20260412183140_b930bf89-5953-41dc-be97-45c56737810d.sql @@ -1 +1 @@ -ALTER TABLE public.collections ADD COLUMN icon TEXT DEFAULT '📁'; \ No newline at end of file +ALTER TABLE public.collections ADD COLUMN IF NOT EXISTS icon TEXT DEFAULT '📁'; \ No newline at end of file diff --git a/supabase/migrations/20260412184314_773a5c2e-8fca-4775-9165-0a2442d34dca.sql b/supabase/migrations/20260412184314_773a5c2e-8fca-4775-9165-0a2442d34dca.sql index df9cbf8db..d4c49d76f 100644 --- a/supabase/migrations/20260412184314_773a5c2e-8fca-4775-9165-0a2442d34dca.sql +++ b/supabase/migrations/20260412184314_773a5c2e-8fca-4775-9165-0a2442d34dca.sql @@ -1 +1 @@ -ALTER TABLE public.collection_items ADD COLUMN notes TEXT; \ No newline at end of file +ALTER TABLE public.collection_items ADD COLUMN IF NOT EXISTS notes TEXT; \ No newline at end of file diff --git a/supabase/migrations/20260412231951_faf4b360-0a4a-4dd0-b341-673e16044eb5.sql b/supabase/migrations/20260412231951_faf4b360-0a4a-4dd0-b341-673e16044eb5.sql index 63b3e8eb2..c0f376c81 100644 --- a/supabase/migrations/20260412231951_faf4b360-0a4a-4dd0-b341-673e16044eb5.sql +++ b/supabase/migrations/20260412231951_faf4b360-0a4a-4dd0-b341-673e16044eb5.sql @@ -50,22 +50,27 @@ END; $$; -- Apply triggers +DROP TRIGGER IF EXISTS trg_validate_quote_status ON public.quotes; CREATE TRIGGER trg_validate_quote_status BEFORE INSERT OR UPDATE ON public.quotes FOR EACH ROW EXECUTE FUNCTION public.validate_status_fields(); +DROP TRIGGER IF EXISTS trg_validate_order_status ON public.orders; CREATE TRIGGER trg_validate_order_status BEFORE INSERT OR UPDATE ON public.orders FOR EACH ROW EXECUTE FUNCTION public.validate_status_fields(); +DROP TRIGGER IF EXISTS trg_validate_kit_status ON public.custom_kits; CREATE TRIGGER trg_validate_kit_status BEFORE INSERT OR UPDATE ON public.custom_kits FOR EACH ROW EXECUTE FUNCTION public.validate_status_fields(); +DROP TRIGGER IF EXISTS trg_validate_kit_share_token_status ON public.kit_share_tokens; CREATE TRIGGER trg_validate_kit_share_token_status BEFORE INSERT OR UPDATE ON public.kit_share_tokens FOR EACH ROW EXECUTE FUNCTION public.validate_status_fields(); +DROP TRIGGER IF EXISTS trg_validate_approval_token_status ON public.quote_approval_tokens; CREATE TRIGGER trg_validate_approval_token_status BEFORE INSERT OR UPDATE ON public.quote_approval_tokens FOR EACH ROW EXECUTE FUNCTION public.validate_status_fields(); diff --git a/supabase/migrations/20260414193435_871210cd-f0d8-40ee-ae9f-401b4887727f.sql b/supabase/migrations/20260414193435_871210cd-f0d8-40ee-ae9f-401b4887727f.sql index 0a7b2dda1..3bc4eabba 100644 --- a/supabase/migrations/20260414193435_871210cd-f0d8-40ee-ae9f-401b4887727f.sql +++ b/supabase/migrations/20260414193435_871210cd-f0d8-40ee-ae9f-401b4887727f.sql @@ -1,6 +1,6 @@ -- 1. Create seller_discount_limits table -CREATE TABLE public.seller_discount_limits ( +CREATE TABLE IF NOT EXISTS public.seller_discount_limits ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE, max_discount_percent NUMERIC NOT NULL DEFAULT 5, @@ -13,23 +13,26 @@ CREATE TABLE public.seller_discount_limits ( ALTER TABLE public.seller_discount_limits ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins can manage all discount limits" ON public.seller_discount_limits; CREATE POLICY "Admins can manage all discount limits" ON public.seller_discount_limits FOR ALL TO authenticated USING (public.has_role(auth.uid(), 'admin'::app_role)) WITH CHECK (public.has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Sellers can read own discount limit" ON public.seller_discount_limits; CREATE POLICY "Sellers can read own discount limit" ON public.seller_discount_limits FOR SELECT TO authenticated USING (user_id = auth.uid()); +DROP TRIGGER IF EXISTS update_seller_discount_limits_updated_at ON public.seller_discount_limits; CREATE TRIGGER update_seller_discount_limits_updated_at BEFORE UPDATE ON public.seller_discount_limits FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); -- 2. Create discount_approval_requests table -CREATE TABLE public.discount_approval_requests ( +CREATE TABLE IF NOT EXISTS public.discount_approval_requests ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), quote_id UUID NOT NULL REFERENCES public.quotes(id) ON DELETE CASCADE, seller_id UUID NOT NULL, @@ -46,22 +49,26 @@ CREATE TABLE public.discount_approval_requests ( ALTER TABLE public.discount_approval_requests ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins can manage all approval requests" ON public.discount_approval_requests; CREATE POLICY "Admins can manage all approval requests" ON public.discount_approval_requests FOR ALL TO authenticated USING (public.has_role(auth.uid(), 'admin'::app_role)) WITH CHECK (public.has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Sellers can read own approval requests" ON public.discount_approval_requests; CREATE POLICY "Sellers can read own approval requests" ON public.discount_approval_requests FOR SELECT TO authenticated USING (seller_id = auth.uid()); +DROP POLICY IF EXISTS "Sellers can create own approval requests" ON public.discount_approval_requests; CREATE POLICY "Sellers can create own approval requests" ON public.discount_approval_requests FOR INSERT TO authenticated WITH CHECK (seller_id = auth.uid()); +DROP TRIGGER IF EXISTS update_discount_approval_requests_updated_at ON public.discount_approval_requests; CREATE TRIGGER update_discount_approval_requests_updated_at BEFORE UPDATE ON public.discount_approval_requests FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); @@ -81,6 +88,7 @@ BEGIN END; $$; +DROP TRIGGER IF EXISTS validate_discount_approval_status_trigger ON public.discount_approval_requests; CREATE TRIGGER validate_discount_approval_status_trigger BEFORE INSERT OR UPDATE ON public.discount_approval_requests FOR EACH ROW EXECUTE FUNCTION public.validate_discount_approval_status(); @@ -192,12 +200,13 @@ BEGIN END; $$; +DROP TRIGGER IF EXISTS notify_discount_approval_trigger ON public.discount_approval_requests; CREATE TRIGGER notify_discount_approval_trigger AFTER INSERT OR UPDATE ON public.discount_approval_requests FOR EACH ROW EXECUTE FUNCTION public.notify_discount_approval_request(); -- 6. Indexes -CREATE INDEX idx_discount_approval_requests_quote_id ON public.discount_approval_requests(quote_id); -CREATE INDEX idx_discount_approval_requests_seller_id ON public.discount_approval_requests(seller_id); -CREATE INDEX idx_discount_approval_requests_status ON public.discount_approval_requests(status); -CREATE INDEX idx_seller_discount_limits_user_id ON public.seller_discount_limits(user_id); +CREATE INDEX IF NOT EXISTS idx_discount_approval_requests_quote_id ON public.discount_approval_requests(quote_id); +CREATE INDEX IF NOT EXISTS idx_discount_approval_requests_seller_id ON public.discount_approval_requests(seller_id); +CREATE INDEX IF NOT EXISTS idx_discount_approval_requests_status ON public.discount_approval_requests(status); +CREATE INDEX IF NOT EXISTS idx_seller_discount_limits_user_id ON public.seller_discount_limits(user_id); diff --git a/supabase/migrations/20260414232135_91832f4f-3bda-41e0-8707-cac75a069d44.sql b/supabase/migrations/20260414232135_91832f4f-3bda-41e0-8707-cac75a069d44.sql index 37a415205..d97349d45 100644 --- a/supabase/migrations/20260414232135_91832f4f-3bda-41e0-8707-cac75a069d44.sql +++ b/supabase/migrations/20260414232135_91832f4f-3bda-41e0-8707-cac75a069d44.sql @@ -1,11 +1,13 @@ -- Trigger: notificar admins quando vendedor solicita aprovação de desconto -- e notificar vendedor quando admin responde +DROP TRIGGER IF EXISTS trg_notify_discount_approval ON public.discount_approval_requests; CREATE TRIGGER trg_notify_discount_approval AFTER INSERT OR UPDATE ON public.discount_approval_requests FOR EACH ROW EXECUTE FUNCTION public.notify_discount_approval_request(); -- Trigger: validar status da solicitação +DROP TRIGGER IF EXISTS trg_validate_discount_status ON public.discount_approval_requests; CREATE TRIGGER trg_validate_discount_status BEFORE INSERT OR UPDATE ON public.discount_approval_requests FOR EACH ROW diff --git a/supabase/migrations/20260415010140_79877aa0-dbae-45cb-a872-7cc3520827b7.sql b/supabase/migrations/20260415010140_79877aa0-dbae-45cb-a872-7cc3520827b7.sql index c4fb00015..d0184aad9 100644 --- a/supabase/migrations/20260415010140_79877aa0-dbae-45cb-a872-7cc3520827b7.sql +++ b/supabase/migrations/20260415010140_79877aa0-dbae-45cb-a872-7cc3520827b7.sql @@ -43,12 +43,14 @@ FOR SELECT TO authenticated USING (seller_id = auth.uid() OR public.is_admin()); +DROP POLICY IF EXISTS "Sellers can create approval requests" ON public.discount_approval_requests; CREATE POLICY "Sellers can create approval requests" ON public.discount_approval_requests FOR INSERT TO authenticated WITH CHECK (seller_id = auth.uid()); +DROP POLICY IF EXISTS "Admins can update approval requests" ON public.discount_approval_requests; CREATE POLICY "Admins can update approval requests" ON public.discount_approval_requests FOR UPDATE diff --git a/supabase/migrations/20260416153503_5163f0f9-e6f0-4664-9f53-8cdb24d9150e.sql b/supabase/migrations/20260416153503_5163f0f9-e6f0-4664-9f53-8cdb24d9150e.sql index df21493c1..ba562fa77 100644 --- a/supabase/migrations/20260416153503_5163f0f9-e6f0-4664-9f53-8cdb24d9150e.sql +++ b/supabase/migrations/20260416153503_5163f0f9-e6f0-4664-9f53-8cdb24d9150e.sql @@ -1,5 +1,5 @@ -- Commission rules table -CREATE TABLE public.commission_rules ( +CREATE TABLE IF NOT EXISTS public.commission_rules ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, seller_id UUID REFERENCES auth.users(id) ON DELETE CASCADE, commission_percent NUMERIC(5,2) NOT NULL DEFAULT 5.00, @@ -12,7 +12,7 @@ CREATE TABLE public.commission_rules ( ); -- Commission entries table -CREATE TABLE public.commission_entries ( +CREATE TABLE IF NOT EXISTS public.commission_entries ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, order_id UUID REFERENCES public.orders(id) ON DELETE SET NULL, seller_id UUID NOT NULL, @@ -31,24 +31,28 @@ ALTER TABLE public.commission_rules ENABLE ROW LEVEL SECURITY; ALTER TABLE public.commission_entries ENABLE ROW LEVEL SECURITY; -- RLS: commission_rules +DROP POLICY IF EXISTS "Admins can manage commission rules" ON public.commission_rules; CREATE POLICY "Admins can manage commission rules" ON public.commission_rules FOR ALL TO authenticated USING (public.is_admin()) WITH CHECK (public.is_admin()); +DROP POLICY IF EXISTS "Sellers can view their own commission rules" ON public.commission_rules; CREATE POLICY "Sellers can view their own commission rules" ON public.commission_rules FOR SELECT TO authenticated USING (seller_id = auth.uid() OR is_default = true); -- RLS: commission_entries +DROP POLICY IF EXISTS "Admins can manage all commission entries" ON public.commission_entries; CREATE POLICY "Admins can manage all commission entries" ON public.commission_entries FOR ALL TO authenticated USING (public.is_admin()) WITH CHECK (public.is_admin()); +DROP POLICY IF EXISTS "Sellers can view their own commissions" ON public.commission_entries; CREATE POLICY "Sellers can view their own commissions" ON public.commission_entries FOR SELECT TO authenticated @@ -69,15 +73,18 @@ BEGIN END; $$; +DROP TRIGGER IF EXISTS trg_validate_commission_status ON public.commission_entries; CREATE TRIGGER trg_validate_commission_status BEFORE INSERT OR UPDATE ON public.commission_entries FOR EACH ROW EXECUTE FUNCTION public.validate_commission_status(); -- Updated_at triggers +DROP TRIGGER IF EXISTS update_commission_rules_updated_at ON public.commission_rules; CREATE TRIGGER update_commission_rules_updated_at BEFORE UPDATE ON public.commission_rules FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); +DROP TRIGGER IF EXISTS update_commission_entries_updated_at ON public.commission_entries; CREATE TRIGGER update_commission_entries_updated_at BEFORE UPDATE ON public.commission_entries FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); diff --git a/supabase/migrations/20260416153731_08813198-7d0b-4164-bf3d-5ea3fc83810c.sql b/supabase/migrations/20260416153731_08813198-7d0b-4164-bf3d-5ea3fc83810c.sql index 881007822..d9bc9ffcc 100644 --- a/supabase/migrations/20260416153731_08813198-7d0b-4164-bf3d-5ea3fc83810c.sql +++ b/supabase/migrations/20260416153731_08813198-7d0b-4164-bf3d-5ea3fc83810c.sql @@ -5,7 +5,7 @@ ALTER TABLE public.follow_up_reminders ADD COLUMN IF NOT EXISTS is_completed BOOLEAN NOT NULL DEFAULT false, ADD COLUMN IF NOT EXISTS completed_at TIMESTAMPTZ; --- Create index for agenda queries +-- CREATE INDEX IF NOT EXISTS for agenda queries CREATE INDEX IF NOT EXISTS idx_follow_up_reminders_seller_scheduled ON public.follow_up_reminders (seller_id, scheduled_for DESC); diff --git a/supabase/migrations/20260416154332_bbeb74b9-5778-41cd-a12c-6fe3f15ef1d6.sql b/supabase/migrations/20260416154332_bbeb74b9-5778-41cd-a12c-6fe3f15ef1d6.sql index ad1375f84..8e51690b5 100644 --- a/supabase/migrations/20260416154332_bbeb74b9-5778-41cd-a12c-6fe3f15ef1d6.sql +++ b/supabase/migrations/20260416154332_bbeb74b9-5778-41cd-a12c-6fe3f15ef1d6.sql @@ -58,6 +58,7 @@ BEGIN END; $$; +DROP TRIGGER IF EXISTS trg_auto_commission_on_order ON public.orders; CREATE TRIGGER trg_auto_commission_on_order AFTER INSERT ON public.orders FOR EACH ROW EXECUTE FUNCTION public.auto_create_commission_entry(); \ No newline at end of file diff --git a/supabase/migrations/20260416180602_e309aad1-04f2-4286-b3a6-888c04671457.sql b/supabase/migrations/20260416180602_e309aad1-04f2-4286-b3a6-888c04671457.sql index 3855ba994..68f4bd046 100644 --- a/supabase/migrations/20260416180602_e309aad1-04f2-4286-b3a6-888c04671457.sql +++ b/supabase/migrations/20260416180602_e309aad1-04f2-4286-b3a6-888c04671457.sql @@ -24,21 +24,25 @@ END $$; -- Recriar policies SELECT restritas: somente usuários autenticados podem listar/ler via API -- (URLs públicas continuam funcionando via CDN sem policy) +DROP POLICY IF EXISTS "Authenticated can read personalization-images" ON storage.objects; CREATE POLICY "Authenticated can read personalization-images" ON storage.objects FOR SELECT TO authenticated USING (bucket_id = 'personalization-images'); +DROP POLICY IF EXISTS "Authenticated can read product-videos" ON storage.objects; CREATE POLICY "Authenticated can read product-videos" ON storage.objects FOR SELECT TO authenticated USING (bucket_id = 'product-videos'); +DROP POLICY IF EXISTS "Authenticated can read supplier-logos" ON storage.objects; CREATE POLICY "Authenticated can read supplier-logos" ON storage.objects FOR SELECT TO authenticated USING (bucket_id = 'supplier-logos'); +DROP POLICY IF EXISTS "Authenticated can read component-media" ON storage.objects; CREATE POLICY "Authenticated can read component-media" ON storage.objects FOR SELECT TO authenticated diff --git a/supabase/migrations/20260416183342_786cf75e-5ec6-4c53-a314-9b622e8b7027.sql b/supabase/migrations/20260416183342_786cf75e-5ec6-4c53-a314-9b622e8b7027.sql index 2051af61a..29546b646 100644 --- a/supabase/migrations/20260416183342_786cf75e-5ec6-4c53-a314-9b622e8b7027.sql +++ b/supabase/migrations/20260416183342_786cf75e-5ec6-4c53-a314-9b622e8b7027.sql @@ -23,10 +23,12 @@ CREATE INDEX IF NOT EXISTS idx_rate_limits_blocked_until ALTER TABLE public.request_rate_limits ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins can read rate limits" ON public.request_rate_limits; CREATE POLICY "Admins can read rate limits" ON public.request_rate_limits FOR SELECT TO authenticated USING (has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Service role can manage rate limits" ON public.request_rate_limits; CREATE POLICY "Service role can manage rate limits" ON public.request_rate_limits FOR ALL TO service_role USING (true) WITH CHECK (true); @@ -50,10 +52,12 @@ CREATE INDEX IF NOT EXISTS idx_bot_log_blocked ON public.bot_detection_log(block ALTER TABLE public.bot_detection_log ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins can read bot log" ON public.bot_detection_log; CREATE POLICY "Admins can read bot log" ON public.bot_detection_log FOR SELECT TO authenticated USING (has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Service role can insert bot log" ON public.bot_detection_log; CREATE POLICY "Service role can insert bot log" ON public.bot_detection_log FOR INSERT TO service_role WITH CHECK (true); diff --git a/supabase/migrations/20260416183415_d7c7a7a0-725a-471b-8c3d-424230285729.sql b/supabase/migrations/20260416183415_d7c7a7a0-725a-471b-8c3d-424230285729.sql index 98081d754..066b7e3b4 100644 --- a/supabase/migrations/20260416183415_d7c7a7a0-725a-471b-8c3d-424230285729.sql +++ b/supabase/migrations/20260416183415_d7c7a7a0-725a-471b-8c3d-424230285729.sql @@ -32,12 +32,14 @@ BEGIN END $$; -- Authenticated users can list/read objects in these buckets (for app functionality) +DROP POLICY IF EXISTS "Authenticated can read protected buckets" ON storage.objects; CREATE POLICY "Authenticated can read protected buckets" ON storage.objects FOR SELECT TO authenticated USING (bucket_id IN ('supplier-logos', 'product-videos', 'personalization-images', 'component-media')); -- Service role full access (for edge functions / image-proxy) +DROP POLICY IF EXISTS "Service role full access protected buckets" ON storage.objects; CREATE POLICY "Service role full access protected buckets" ON storage.objects FOR SELECT TO service_role diff --git a/supabase/migrations/20260416183821_54ccc054-be01-4793-ab8d-d415f2108fe9.sql b/supabase/migrations/20260416183821_54ccc054-be01-4793-ab8d-d415f2108fe9.sql index 819f08ebf..303feba8a 100644 --- a/supabase/migrations/20260416183821_54ccc054-be01-4793-ab8d-d415f2108fe9.sql +++ b/supabase/migrations/20260416183821_54ccc054-be01-4793-ab8d-d415f2108fe9.sql @@ -3,4 +3,4 @@ CREATE SCHEMA IF NOT EXISTS extensions; GRANT USAGE ON SCHEMA extensions TO postgres, anon, authenticated, service_role; DROP EXTENSION IF EXISTS pg_net; -CREATE EXTENSION pg_net WITH SCHEMA extensions; \ No newline at end of file +CREATE EXTENSION IF NOT EXISTS pg_net WITH SCHEMA extensions; \ No newline at end of file diff --git a/supabase/migrations/20260416184056_e28ea309-c50d-46b1-85e5-9e283352d97d.sql b/supabase/migrations/20260416184056_e28ea309-c50d-46b1-85e5-9e283352d97d.sql index 908cfb002..106f7cd6f 100644 --- a/supabase/migrations/20260416184056_e28ea309-c50d-46b1-85e5-9e283352d97d.sql +++ b/supabase/migrations/20260416184056_e28ea309-c50d-46b1-85e5-9e283352d97d.sql @@ -1,5 +1,5 @@ -- IP access control table (manual allowlist/blocklist) -CREATE TABLE public.ip_access_control ( +CREATE TABLE IF NOT EXISTS public.ip_access_control ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), ip_address TEXT NOT NULL UNIQUE, list_type TEXT NOT NULL, @@ -12,6 +12,7 @@ CREATE TABLE public.ip_access_control ( ALTER TABLE public.ip_access_control ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins can manage ip_access_control" ON public.ip_access_control; CREATE POLICY "Admins can manage ip_access_control" ON public.ip_access_control FOR ALL @@ -19,6 +20,7 @@ CREATE POLICY "Admins can manage ip_access_control" USING (has_role(auth.uid(), 'admin'::app_role)) WITH CHECK (has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Service role full access ip_access_control" ON public.ip_access_control; CREATE POLICY "Service role full access ip_access_control" ON public.ip_access_control FOR ALL @@ -41,16 +43,18 @@ BEGIN END; $$; +DROP TRIGGER IF EXISTS trg_validate_ip_access_control ON public.ip_access_control; CREATE TRIGGER trg_validate_ip_access_control BEFORE INSERT OR UPDATE ON public.ip_access_control FOR EACH ROW EXECUTE FUNCTION public.validate_ip_access_control(); +DROP TRIGGER IF EXISTS trg_ip_access_control_updated_at ON public.ip_access_control; CREATE TRIGGER trg_ip_access_control_updated_at BEFORE UPDATE ON public.ip_access_control FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); -CREATE INDEX idx_ip_access_control_ip ON public.ip_access_control(ip_address); -CREATE INDEX idx_ip_access_control_type_expires ON public.ip_access_control(list_type, expires_at); +CREATE INDEX IF NOT EXISTS idx_ip_access_control_ip ON public.ip_access_control(ip_address); +CREATE INDEX IF NOT EXISTS idx_ip_access_control_type_expires ON public.ip_access_control(list_type, expires_at); -- Atomic check function used by edge functions CREATE OR REPLACE FUNCTION public.check_ip_access(_ip TEXT) diff --git a/supabase/migrations/20260416195918_397d6363-83a0-45f5-a8f6-ea33e21352a6.sql b/supabase/migrations/20260416195918_397d6363-83a0-45f5-a8f6-ea33e21352a6.sql index 563977557..2f5a39fe6 100644 --- a/supabase/migrations/20260416195918_397d6363-83a0-45f5-a8f6-ea33e21352a6.sql +++ b/supabase/migrations/20260416195918_397d6363-83a0-45f5-a8f6-ea33e21352a6.sql @@ -21,22 +21,27 @@ CREATE INDEX IF NOT EXISTS idx_mockup_templates_product ON public.mockup_templat ALTER TABLE public.mockup_templates ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users view own mockup templates" ON public.mockup_templates; CREATE POLICY "Users view own mockup templates" ON public.mockup_templates FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users insert own mockup templates" ON public.mockup_templates; CREATE POLICY "Users insert own mockup templates" ON public.mockup_templates FOR INSERT WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users update own mockup templates" ON public.mockup_templates; CREATE POLICY "Users update own mockup templates" ON public.mockup_templates FOR UPDATE USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users delete own mockup templates" ON public.mockup_templates; CREATE POLICY "Users delete own mockup templates" ON public.mockup_templates FOR DELETE USING (auth.uid() = user_id); +DROP TRIGGER IF EXISTS update_mockup_templates_updated_at ON public.mockup_templates; CREATE TRIGGER update_mockup_templates_updated_at BEFORE UPDATE ON public.mockup_templates FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); @@ -64,22 +69,27 @@ CREATE INDEX IF NOT EXISTS idx_art_files_quote ON public.art_file_attachments(qu ALTER TABLE public.art_file_attachments ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users view own art files" ON public.art_file_attachments; CREATE POLICY "Users view own art files" ON public.art_file_attachments FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users insert own art files" ON public.art_file_attachments; CREATE POLICY "Users insert own art files" ON public.art_file_attachments FOR INSERT WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users update own art files" ON public.art_file_attachments; CREATE POLICY "Users update own art files" ON public.art_file_attachments FOR UPDATE USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users delete own art files" ON public.art_file_attachments; CREATE POLICY "Users delete own art files" ON public.art_file_attachments FOR DELETE USING (auth.uid() = user_id); +DROP TRIGGER IF EXISTS update_art_files_updated_at ON public.art_file_attachments; CREATE TRIGGER update_art_files_updated_at BEFORE UPDATE ON public.art_file_attachments FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); @@ -89,18 +99,22 @@ INSERT INTO storage.buckets (id, name, public) VALUES ('mockup-art-files', 'mockup-art-files', false) ON CONFLICT (id) DO NOTHING; +DROP POLICY IF EXISTS "Users view own art files in storage" ON storage.objects; CREATE POLICY "Users view own art files in storage" ON storage.objects FOR SELECT USING (bucket_id = 'mockup-art-files' AND auth.uid()::text = (storage.foldername(name))[1]); +DROP POLICY IF EXISTS "Users upload own art files to storage" ON storage.objects; CREATE POLICY "Users upload own art files to storage" ON storage.objects FOR INSERT WITH CHECK (bucket_id = 'mockup-art-files' AND auth.uid()::text = (storage.foldername(name))[1]); +DROP POLICY IF EXISTS "Users update own art files in storage" ON storage.objects; CREATE POLICY "Users update own art files in storage" ON storage.objects FOR UPDATE USING (bucket_id = 'mockup-art-files' AND auth.uid()::text = (storage.foldername(name))[1]); +DROP POLICY IF EXISTS "Users delete own art files in storage" ON storage.objects; CREATE POLICY "Users delete own art files in storage" ON storage.objects FOR DELETE USING (bucket_id = 'mockup-art-files' AND auth.uid()::text = (storage.foldername(name))[1]); \ No newline at end of file diff --git a/supabase/migrations/20260416200125_980ed90e-0927-4d03-be42-7db5bbe12309.sql b/supabase/migrations/20260416200125_980ed90e-0927-4d03-be42-7db5bbe12309.sql index 6f4c9b0c5..f65836906 100644 --- a/supabase/migrations/20260416200125_980ed90e-0927-4d03-be42-7db5bbe12309.sql +++ b/supabase/migrations/20260416200125_980ed90e-0927-4d03-be42-7db5bbe12309.sql @@ -17,11 +17,13 @@ CREATE INDEX IF NOT EXISTS idx_mockup_prompt_configs_technique ON public.mockup_ ALTER TABLE public.mockup_prompt_configs ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins manage prompt configs" ON public.mockup_prompt_configs; CREATE POLICY "Admins manage prompt configs" ON public.mockup_prompt_configs FOR ALL USING (public.has_role(auth.uid(), 'admin')) WITH CHECK (public.has_role(auth.uid(), 'admin')); +DROP TRIGGER IF EXISTS update_mockup_prompt_configs_updated_at ON public.mockup_prompt_configs; CREATE TRIGGER update_mockup_prompt_configs_updated_at BEFORE UPDATE ON public.mockup_prompt_configs FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); @@ -44,10 +46,12 @@ CREATE INDEX IF NOT EXISTS idx_mockup_prompt_history_config ON public.mockup_pro ALTER TABLE public.mockup_prompt_history ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins view prompt history" ON public.mockup_prompt_history; CREATE POLICY "Admins view prompt history" ON public.mockup_prompt_history FOR SELECT USING (public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Admins insert prompt history" ON public.mockup_prompt_history; CREATE POLICY "Admins insert prompt history" ON public.mockup_prompt_history FOR INSERT WITH CHECK (public.has_role(auth.uid(), 'admin')); @@ -72,6 +76,7 @@ BEGIN END; $$; +DROP TRIGGER IF EXISTS trg_log_mockup_prompt_change ON public.mockup_prompt_configs; CREATE TRIGGER trg_log_mockup_prompt_change BEFORE UPDATE ON public.mockup_prompt_configs FOR EACH ROW EXECUTE FUNCTION public.log_mockup_prompt_change(); \ No newline at end of file diff --git a/supabase/migrations/20260416200310_2cc4af04-9203-498c-874b-d923fcfdc7fc.sql b/supabase/migrations/20260416200310_2cc4af04-9203-498c-874b-d923fcfdc7fc.sql index 9af144e07..61613492e 100644 --- a/supabase/migrations/20260416200310_2cc4af04-9203-498c-874b-d923fcfdc7fc.sql +++ b/supabase/migrations/20260416200310_2cc4af04-9203-498c-874b-d923fcfdc7fc.sql @@ -19,10 +19,12 @@ CREATE INDEX IF NOT EXISTS idx_product_sync_logs_source ON public.product_sync_l ALTER TABLE public.product_sync_logs ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins view product sync logs" ON public.product_sync_logs; CREATE POLICY "Admins view product sync logs" ON public.product_sync_logs FOR SELECT USING (public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Admins insert product sync logs" ON public.product_sync_logs; CREATE POLICY "Admins insert product sync logs" ON public.product_sync_logs FOR INSERT WITH CHECK (public.has_role(auth.uid(), 'admin')); @@ -47,16 +49,19 @@ CREATE INDEX IF NOT EXISTS idx_product_comp_loc_component ON public.product_comp ALTER TABLE public.product_component_locations ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Authenticated view component locations" ON public.product_component_locations; CREATE POLICY "Authenticated view component locations" ON public.product_component_locations FOR SELECT TO authenticated USING (true); +DROP POLICY IF EXISTS "Admins manage component locations" ON public.product_component_locations; CREATE POLICY "Admins manage component locations" ON public.product_component_locations FOR ALL USING (public.has_role(auth.uid(), 'admin')) WITH CHECK (public.has_role(auth.uid(), 'admin')); +DROP TRIGGER IF EXISTS update_product_comp_loc_updated_at ON public.product_component_locations; CREATE TRIGGER update_product_comp_loc_updated_at BEFORE UPDATE ON public.product_component_locations FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); \ No newline at end of file diff --git a/supabase/migrations/20260416231122_95edd411-9f96-4389-a9fe-93b2d4c557d8.sql b/supabase/migrations/20260416231122_95edd411-9f96-4389-a9fe-93b2d4c557d8.sql index 302d15205..f7ad816dd 100644 --- a/supabase/migrations/20260416231122_95edd411-9f96-4389-a9fe-93b2d4c557d8.sql +++ b/supabase/migrations/20260416231122_95edd411-9f96-4389-a9fe-93b2d4c557d8.sql @@ -15,6 +15,7 @@ CREATE INDEX IF NOT EXISTS idx_search_analytics_zero_results ON public.search_an ALTER TABLE public.search_analytics ENABLE ROW LEVEL SECURITY; -- Anyone authenticated can log a search (insert) +DROP POLICY IF EXISTS "Authenticated users can log searches" ON public.search_analytics; CREATE POLICY "Authenticated users can log searches" ON public.search_analytics FOR INSERT @@ -22,6 +23,7 @@ TO authenticated WITH CHECK (auth.uid() IS NOT NULL); -- Allow anonymous logging too (catalog is public-facing for visitors) +DROP POLICY IF EXISTS "Anyone can log searches" ON public.search_analytics; CREATE POLICY "Anyone can log searches" ON public.search_analytics FOR INSERT @@ -29,6 +31,7 @@ TO anon WITH CHECK (true); -- Only managers/admins can read aggregated search analytics +DROP POLICY IF EXISTS "Managers and admins can read search analytics" ON public.search_analytics; CREATE POLICY "Managers and admins can read search analytics" ON public.search_analytics FOR SELECT diff --git a/supabase/migrations/20260416232134_c5bae7ef-804a-4d27-81b4-73ce0154fdc8.sql b/supabase/migrations/20260416232134_c5bae7ef-804a-4d27-81b4-73ce0154fdc8.sql index a6445940f..1ec51d0a3 100644 --- a/supabase/migrations/20260416232134_c5bae7ef-804a-4d27-81b4-73ce0154fdc8.sql +++ b/supabase/migrations/20260416232134_c5bae7ef-804a-4d27-81b4-73ce0154fdc8.sql @@ -1,5 +1,5 @@ -CREATE TABLE public.saved_trends_views ( +CREATE TABLE IF NOT EXISTS public.saved_trends_views ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID NOT NULL, name TEXT NOT NULL, @@ -10,6 +10,7 @@ CREATE TABLE public.saved_trends_views ( ALTER TABLE public.saved_trends_views ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users manage own saved trends views" ON public.saved_trends_views; CREATE POLICY "Users manage own saved trends views" ON public.saved_trends_views FOR ALL @@ -17,8 +18,9 @@ TO authenticated USING (user_id = auth.uid()) WITH CHECK (user_id = auth.uid()); -CREATE INDEX idx_saved_trends_views_user ON public.saved_trends_views(user_id); +CREATE INDEX IF NOT EXISTS idx_saved_trends_views_user ON public.saved_trends_views(user_id); +DROP TRIGGER IF EXISTS update_saved_trends_views_updated_at ON public.saved_trends_views; CREATE TRIGGER update_saved_trends_views_updated_at BEFORE UPDATE ON public.saved_trends_views FOR EACH ROW diff --git a/supabase/migrations/20260417001408_df418063-07d5-4aaf-938b-c3e01a5653fb.sql b/supabase/migrations/20260417001408_df418063-07d5-4aaf-938b-c3e01a5653fb.sql index 79f09228b..6991770e3 100644 --- a/supabase/migrations/20260417001408_df418063-07d5-4aaf-938b-c3e01a5653fb.sql +++ b/supabase/migrations/20260417001408_df418063-07d5-4aaf-938b-c3e01a5653fb.sql @@ -77,21 +77,25 @@ END $$; -- Supabase storage list API still works for authenticated owners via existing -- per-folder policies; anon clients can only fetch by exact path. +DROP POLICY IF EXISTS "Direct read personalization-images" ON storage.objects; CREATE POLICY "Direct read personalization-images" ON storage.objects FOR SELECT TO anon, authenticated USING (bucket_id = 'personalization-images' AND name IS NOT NULL AND length(name) > 0); +DROP POLICY IF EXISTS "Direct read product-videos" ON storage.objects; CREATE POLICY "Direct read product-videos" ON storage.objects FOR SELECT TO anon, authenticated USING (bucket_id = 'product-videos' AND name IS NOT NULL AND length(name) > 0); +DROP POLICY IF EXISTS "Direct read supplier-logos" ON storage.objects; CREATE POLICY "Direct read supplier-logos" ON storage.objects FOR SELECT TO anon, authenticated USING (bucket_id = 'supplier-logos' AND name IS NOT NULL AND length(name) > 0); +DROP POLICY IF EXISTS "Direct read component-media" ON storage.objects; CREATE POLICY "Direct read component-media" ON storage.objects FOR SELECT TO anon, authenticated diff --git a/supabase/migrations/20260417171441_83bb6a48-4d55-4495-a23b-4539e6ed5707.sql b/supabase/migrations/20260417171441_83bb6a48-4d55-4495-a23b-4539e6ed5707.sql index a58bebc02..dcad2ad3c 100644 --- a/supabase/migrations/20260417171441_83bb6a48-4d55-4495-a23b-4539e6ed5707.sql +++ b/supabase/migrations/20260417171441_83bb6a48-4d55-4495-a23b-4539e6ed5707.sql @@ -12,5 +12,5 @@ DROP FUNCTION IF EXISTS public.get_web_vitals_summary(integer, text); DROP FUNCTION IF EXISTS public.get_web_vitals_summary(integer, text, text, text, boolean); DROP FUNCTION IF EXISTS public.get_web_vitals_regression(); --- Drop table (cascades indexes + RLS policies) +-- DROP TABLE IF EXISTS (cascades indexes + RLS policies) DROP TABLE IF EXISTS public.web_vitals CASCADE; \ No newline at end of file diff --git a/supabase/migrations/20260418131950_ac0f8ad7-b1bf-4c81-8849-6cd759e19198.sql b/supabase/migrations/20260418131950_ac0f8ad7-b1bf-4c81-8849-6cd759e19198.sql index 5a0615df7..172f9b41a 100644 --- a/supabase/migrations/20260418131950_ac0f8ad7-b1bf-4c81-8849-6cd759e19198.sql +++ b/supabase/migrations/20260418131950_ac0f8ad7-b1bf-4c81-8849-6cd759e19198.sql @@ -21,18 +21,21 @@ CREATE INDEX IF NOT EXISTS idx_ai_insights_cache_expires ALTER TABLE public.ai_insights_cache ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view their own cached insights" ON public.ai_insights_cache; CREATE POLICY "Users can view their own cached insights" ON public.ai_insights_cache FOR SELECT TO authenticated USING (auth.uid() = user_id OR has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Users can insert their own cached insights" ON public.ai_insights_cache; CREATE POLICY "Users can insert their own cached insights" ON public.ai_insights_cache FOR INSERT TO authenticated WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can update their own cached insights" ON public.ai_insights_cache; CREATE POLICY "Users can update their own cached insights" ON public.ai_insights_cache FOR UPDATE @@ -40,6 +43,7 @@ CREATE POLICY "Users can update their own cached insights" USING (auth.uid() = user_id) WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can delete their own cached insights" ON public.ai_insights_cache; CREATE POLICY "Users can delete their own cached insights" ON public.ai_insights_cache FOR DELETE @@ -63,12 +67,14 @@ CREATE INDEX IF NOT EXISTS idx_ai_usage_events_fn_created ALTER TABLE public.ai_usage_events ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view their own usage events" ON public.ai_usage_events; CREATE POLICY "Users can view their own usage events" ON public.ai_usage_events FOR SELECT TO authenticated USING (auth.uid() = user_id OR has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Users can insert their own usage events" ON public.ai_usage_events; CREATE POLICY "Users can insert their own usage events" ON public.ai_usage_events FOR INSERT diff --git a/supabase/migrations/20260418175315_6317f072-62ee-49c8-af36-6c992764a582.sql b/supabase/migrations/20260418175315_6317f072-62ee-49c8-af36-6c992764a582.sql index 579e892d0..b9967d171 100644 --- a/supabase/migrations/20260418175315_6317f072-62ee-49c8-af36-6c992764a582.sql +++ b/supabase/migrations/20260418175315_6317f072-62ee-49c8-af36-6c992764a582.sql @@ -2,7 +2,7 @@ -- ============================================ -- KIT VARIANTS (multi-variante P/M/G) -- ============================================ -CREATE TABLE public.kit_variants ( +CREATE TABLE IF NOT EXISTS public.kit_variants ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), kit_master_id UUID NOT NULL REFERENCES public.custom_kits(id) ON DELETE CASCADE, label TEXT NOT NULL, @@ -15,31 +15,36 @@ CREATE TABLE public.kit_variants ( created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); -CREATE INDEX idx_kit_variants_master ON public.kit_variants(kit_master_id); +CREATE INDEX IF NOT EXISTS idx_kit_variants_master ON public.kit_variants(kit_master_id); ALTER TABLE public.kit_variants ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Owner can view variants" ON public.kit_variants; CREATE POLICY "Owner can view variants" ON public.kit_variants FOR SELECT USING ( EXISTS (SELECT 1 FROM public.custom_kits k WHERE k.id = kit_master_id AND k.user_id = auth.uid()) OR has_role(auth.uid(), 'admin') ); +DROP POLICY IF EXISTS "Owner can insert variants" ON public.kit_variants; CREATE POLICY "Owner can insert variants" ON public.kit_variants FOR INSERT WITH CHECK ( EXISTS (SELECT 1 FROM public.custom_kits k WHERE k.id = kit_master_id AND k.user_id = auth.uid()) ); +DROP POLICY IF EXISTS "Owner can update variants" ON public.kit_variants; CREATE POLICY "Owner can update variants" ON public.kit_variants FOR UPDATE USING ( EXISTS (SELECT 1 FROM public.custom_kits k WHERE k.id = kit_master_id AND k.user_id = auth.uid()) ); +DROP POLICY IF EXISTS "Owner can delete variants" ON public.kit_variants; CREATE POLICY "Owner can delete variants" ON public.kit_variants FOR DELETE USING ( EXISTS (SELECT 1 FROM public.custom_kits k WHERE k.id = kit_master_id AND k.user_id = auth.uid()) ); +DROP TRIGGER IF EXISTS update_kit_variants_updated_at ON public.kit_variants; CREATE TRIGGER update_kit_variants_updated_at BEFORE UPDATE ON public.kit_variants FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); @@ -47,7 +52,7 @@ FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); -- ============================================ -- KIT COLLABORATORS -- ============================================ -CREATE TABLE public.kit_collaborators ( +CREATE TABLE IF NOT EXISTS public.kit_collaborators ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), kit_id UUID NOT NULL REFERENCES public.custom_kits(id) ON DELETE CASCADE, user_id UUID NOT NULL, @@ -58,8 +63,8 @@ CREATE TABLE public.kit_collaborators ( updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), UNIQUE(kit_id, user_id) ); -CREATE INDEX idx_kit_collab_kit ON public.kit_collaborators(kit_id); -CREATE INDEX idx_kit_collab_user ON public.kit_collaborators(user_id); +CREATE INDEX IF NOT EXISTS idx_kit_collab_kit ON public.kit_collaborators(kit_id); +CREATE INDEX IF NOT EXISTS idx_kit_collab_user ON public.kit_collaborators(user_id); ALTER TABLE public.kit_collaborators ENABLE ROW LEVEL SECURITY; -- Helper SECURITY DEFINER to avoid recursion in RLS @@ -88,6 +93,7 @@ AS $$ ); $$; +DROP POLICY IF EXISTS "View collaborators if owner or self" ON public.kit_collaborators; CREATE POLICY "View collaborators if owner or self" ON public.kit_collaborators FOR SELECT USING ( @@ -95,16 +101,20 @@ USING ( OR user_id = auth.uid() OR has_role(auth.uid(), 'admin') ); +DROP POLICY IF EXISTS "Owner can invite collaborators" ON public.kit_collaborators; CREATE POLICY "Owner can invite collaborators" ON public.kit_collaborators FOR INSERT WITH CHECK (public.is_kit_owner(kit_id, auth.uid())); +DROP POLICY IF EXISTS "Owner can update collaborators" ON public.kit_collaborators; CREATE POLICY "Owner can update collaborators" ON public.kit_collaborators FOR UPDATE USING (public.is_kit_owner(kit_id, auth.uid())); +DROP POLICY IF EXISTS "Owner can remove collaborators" ON public.kit_collaborators; CREATE POLICY "Owner can remove collaborators" ON public.kit_collaborators FOR DELETE USING (public.is_kit_owner(kit_id, auth.uid())); +DROP TRIGGER IF EXISTS update_kit_collab_updated_at ON public.kit_collaborators; CREATE TRIGGER update_kit_collab_updated_at BEFORE UPDATE ON public.kit_collaborators FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); @@ -112,7 +122,7 @@ FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); -- ============================================ -- KIT COMMENTS -- ============================================ -CREATE TABLE public.kit_comments ( +CREATE TABLE IF NOT EXISTS public.kit_comments ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), kit_id UUID NOT NULL REFERENCES public.custom_kits(id) ON DELETE CASCADE, author_id UUID NOT NULL, @@ -123,10 +133,11 @@ CREATE TABLE public.kit_comments ( created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); -CREATE INDEX idx_kit_comments_kit ON public.kit_comments(kit_id); -CREATE INDEX idx_kit_comments_parent ON public.kit_comments(parent_id); +CREATE INDEX IF NOT EXISTS idx_kit_comments_kit ON public.kit_comments(kit_id); +CREATE INDEX IF NOT EXISTS idx_kit_comments_parent ON public.kit_comments(parent_id); ALTER TABLE public.kit_comments ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "View comments if owner/collab/admin" ON public.kit_comments; CREATE POLICY "View comments if owner/collab/admin" ON public.kit_comments FOR SELECT USING ( @@ -134,6 +145,7 @@ USING ( OR public.is_kit_collaborator(kit_id, auth.uid()) OR has_role(auth.uid(), 'admin') ); +DROP POLICY IF EXISTS "Owner or collab can comment" ON public.kit_comments; CREATE POLICY "Owner or collab can comment" ON public.kit_comments FOR INSERT WITH CHECK ( @@ -142,13 +154,16 @@ WITH CHECK ( OR public.is_kit_collaborator(kit_id, auth.uid()) ) ); +DROP POLICY IF EXISTS "Author can edit own comment" ON public.kit_comments; CREATE POLICY "Author can edit own comment" ON public.kit_comments FOR UPDATE USING (author_id = auth.uid() OR has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Author can delete own comment" ON public.kit_comments; CREATE POLICY "Author can delete own comment" ON public.kit_comments FOR DELETE USING (author_id = auth.uid() OR has_role(auth.uid(), 'admin')); +DROP TRIGGER IF EXISTS update_kit_comments_updated_at ON public.kit_comments; CREATE TRIGGER update_kit_comments_updated_at BEFORE UPDATE ON public.kit_comments FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); diff --git a/supabase/migrations/20260418183756_107f80f6-c724-4ce3-a61f-d3b256419118.sql b/supabase/migrations/20260418183756_107f80f6-c724-4ce3-a61f-d3b256419118.sql index 046e1ed60..cc878abe2 100644 --- a/supabase/migrations/20260418183756_107f80f6-c724-4ce3-a61f-d3b256419118.sql +++ b/supabase/migrations/20260418183756_107f80f6-c724-4ce3-a61f-d3b256419118.sql @@ -44,27 +44,32 @@ CREATE INDEX IF NOT EXISTS idx_kit_templates_usage ALTER TABLE public.kit_templates ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Authenticated users can view active templates" ON public.kit_templates; CREATE POLICY "Authenticated users can view active templates" ON public.kit_templates FOR SELECT TO authenticated USING (is_active = true OR public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Admins can insert templates" ON public.kit_templates; CREATE POLICY "Admins can insert templates" ON public.kit_templates FOR INSERT TO authenticated WITH CHECK (public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Admins can update templates" ON public.kit_templates; CREATE POLICY "Admins can update templates" ON public.kit_templates FOR UPDATE TO authenticated USING (public.has_role(auth.uid(), 'admin')) WITH CHECK (public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Admins can delete templates" ON public.kit_templates; CREATE POLICY "Admins can delete templates" ON public.kit_templates FOR DELETE TO authenticated USING (public.has_role(auth.uid(), 'admin')); +DROP TRIGGER IF EXISTS trg_kit_templates_updated_at ON public.kit_templates; CREATE TRIGGER trg_kit_templates_updated_at BEFORE UPDATE ON public.kit_templates FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); diff --git a/supabase/migrations/20260419024908_0f2085d5-a9a9-4182-b3b0-88377a2749d2.sql b/supabase/migrations/20260419024908_0f2085d5-a9a9-4182-b3b0-88377a2749d2.sql index bdf1a3b1e..eeca56fd8 100644 --- a/supabase/migrations/20260419024908_0f2085d5-a9a9-4182-b3b0-88377a2749d2.sql +++ b/supabase/migrations/20260419024908_0f2085d5-a9a9-4182-b3b0-88377a2749d2.sql @@ -29,19 +29,23 @@ CREATE POLICY "Authenticated direct read component-media" ON storage.objects FOR SELECT TO authenticated USING (bucket_id = 'component-media' AND name IS NOT NULL AND length(name) > 0); +DROP POLICY IF EXISTS "Authenticated direct read personalization-images" ON storage.objects; CREATE POLICY "Authenticated direct read personalization-images" ON storage.objects FOR SELECT TO authenticated USING (bucket_id = 'personalization-images' AND name IS NOT NULL AND length(name) > 0); +DROP POLICY IF EXISTS "Authenticated direct read product-videos" ON storage.objects; CREATE POLICY "Authenticated direct read product-videos" ON storage.objects FOR SELECT TO authenticated USING (bucket_id = 'product-videos' AND name IS NOT NULL AND length(name) > 0); +DROP POLICY IF EXISTS "Authenticated direct read supplier-logos" ON storage.objects; CREATE POLICY "Authenticated direct read supplier-logos" ON storage.objects FOR SELECT TO authenticated USING (bucket_id = 'supplier-logos' AND name IS NOT NULL AND length(name) > 0); -- 4. Admins can list (full SELECT without name guard) for management UIs +DROP POLICY IF EXISTS "Admins can list protected buckets" ON storage.objects; CREATE POLICY "Admins can list protected buckets" ON storage.objects FOR SELECT TO authenticated USING ( diff --git a/supabase/migrations/20260419024928_74dafaf0-67e3-42ef-83f5-1634b4a26328.sql b/supabase/migrations/20260419024928_74dafaf0-67e3-42ef-83f5-1634b4a26328.sql index 23b63d74b..f9c2baa27 100644 --- a/supabase/migrations/20260419024928_74dafaf0-67e3-42ef-83f5-1634b4a26328.sql +++ b/supabase/migrations/20260419024928_74dafaf0-67e3-42ef-83f5-1634b4a26328.sql @@ -1,4 +1,4 @@ -ALTER PUBLICATION supabase_realtime DROP TABLE public.discount_approval_requests; -ALTER PUBLICATION supabase_realtime DROP TABLE public.kit_comments; -ALTER PUBLICATION supabase_realtime DROP TABLE public.kit_variants; +ALTER PUBLICATION supabase_realtime DROP TABLE IF EXISTS public.discount_approval_requests; +ALTER PUBLICATION supabase_realtime DROP TABLE IF EXISTS public.kit_comments; +ALTER PUBLICATION supabase_realtime DROP TABLE IF EXISTS public.kit_variants; diff --git a/supabase/migrations/20260419025022_7d122b20-2611-49b6-874d-b1d72d133ad3.sql b/supabase/migrations/20260419025022_7d122b20-2611-49b6-874d-b1d72d133ad3.sql index 51c28c937..cb73670bb 100644 --- a/supabase/migrations/20260419025022_7d122b20-2611-49b6-874d-b1d72d133ad3.sql +++ b/supabase/migrations/20260419025022_7d122b20-2611-49b6-874d-b1d72d133ad3.sql @@ -36,11 +36,13 @@ CREATE INDEX IF NOT EXISTS idx_public_token_failures_ip ALTER TABLE public.public_token_failures ENABLE ROW LEVEL SECURITY; -- Only admins can read failures (sellers see anomalies via SecurityCenter) +DROP POLICY IF EXISTS "Admins read token failures" ON public.public_token_failures; CREATE POLICY "Admins read token failures" ON public.public_token_failures FOR SELECT TO authenticated USING (has_role(auth.uid(), 'admin'::app_role)); -- Service role / edge functions write failures (no insert from authenticated/anon) +DROP POLICY IF EXISTS "Service role inserts token failures" ON public.public_token_failures; CREATE POLICY "Service role inserts token failures" ON public.public_token_failures FOR INSERT TO service_role WITH CHECK (true); diff --git a/supabase/migrations/20260419130037_5f01e5dd-e3d5-4d26-8a08-328d432a05aa.sql b/supabase/migrations/20260419130037_5f01e5dd-e3d5-4d26-8a08-328d432a05aa.sql index 5fdc165f2..f2bb79c56 100644 --- a/supabase/migrations/20260419130037_5f01e5dd-e3d5-4d26-8a08-328d432a05aa.sql +++ b/supabase/migrations/20260419130037_5f01e5dd-e3d5-4d26-8a08-328d432a05aa.sql @@ -21,12 +21,14 @@ CREATE TABLE IF NOT EXISTS public.external_connections ( ALTER TABLE public.external_connections ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins manage external_connections" ON public.external_connections; CREATE POLICY "Admins manage external_connections" ON public.external_connections FOR ALL USING (public.has_role(auth.uid(), 'admin')) WITH CHECK (public.has_role(auth.uid(), 'admin')); +DROP TRIGGER IF EXISTS trg_external_connections_updated_at ON public.external_connections; CREATE TRIGGER trg_external_connections_updated_at BEFORE UPDATE ON public.external_connections FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); @@ -51,12 +53,14 @@ CREATE TABLE IF NOT EXISTS public.outbound_webhooks ( ALTER TABLE public.outbound_webhooks ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins manage outbound_webhooks" ON public.outbound_webhooks; CREATE POLICY "Admins manage outbound_webhooks" ON public.outbound_webhooks FOR ALL USING (public.has_role(auth.uid(), 'admin')) WITH CHECK (public.has_role(auth.uid(), 'admin')); +DROP TRIGGER IF EXISTS trg_outbound_webhooks_updated_at ON public.outbound_webhooks; CREATE TRIGGER trg_outbound_webhooks_updated_at BEFORE UPDATE ON public.outbound_webhooks FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); @@ -81,11 +85,13 @@ CREATE TABLE IF NOT EXISTS public.webhook_deliveries ( ALTER TABLE public.webhook_deliveries ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins read webhook_deliveries" ON public.webhook_deliveries; CREATE POLICY "Admins read webhook_deliveries" ON public.webhook_deliveries FOR SELECT USING (public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Admins delete webhook_deliveries" ON public.webhook_deliveries; CREATE POLICY "Admins delete webhook_deliveries" ON public.webhook_deliveries FOR DELETE @@ -116,12 +122,14 @@ CREATE TABLE IF NOT EXISTS public.inbound_webhook_endpoints ( ALTER TABLE public.inbound_webhook_endpoints ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins manage inbound_webhook_endpoints" ON public.inbound_webhook_endpoints; CREATE POLICY "Admins manage inbound_webhook_endpoints" ON public.inbound_webhook_endpoints FOR ALL USING (public.has_role(auth.uid(), 'admin')) WITH CHECK (public.has_role(auth.uid(), 'admin')); +DROP TRIGGER IF EXISTS trg_inbound_endpoints_updated_at ON public.inbound_webhook_endpoints; CREATE TRIGGER trg_inbound_endpoints_updated_at BEFORE UPDATE ON public.inbound_webhook_endpoints FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); @@ -141,11 +149,13 @@ CREATE TABLE IF NOT EXISTS public.inbound_webhook_events ( ALTER TABLE public.inbound_webhook_events ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins read inbound_webhook_events" ON public.inbound_webhook_events; CREATE POLICY "Admins read inbound_webhook_events" ON public.inbound_webhook_events FOR SELECT USING (public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Admins delete inbound_webhook_events" ON public.inbound_webhook_events; CREATE POLICY "Admins delete inbound_webhook_events" ON public.inbound_webhook_events FOR DELETE @@ -172,12 +182,14 @@ CREATE TABLE IF NOT EXISTS public.mcp_api_keys ( ALTER TABLE public.mcp_api_keys ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins manage mcp_api_keys" ON public.mcp_api_keys; CREATE POLICY "Admins manage mcp_api_keys" ON public.mcp_api_keys FOR ALL USING (public.has_role(auth.uid(), 'admin')) WITH CHECK (public.has_role(auth.uid(), 'admin')); +DROP TRIGGER IF EXISTS trg_mcp_api_keys_updated_at ON public.mcp_api_keys; CREATE TRIGGER trg_mcp_api_keys_updated_at BEFORE UPDATE ON public.mcp_api_keys FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); diff --git a/supabase/migrations/20260419184445_0ce235ea-4083-4bbd-85e2-e4a201876c1f.sql b/supabase/migrations/20260419184445_0ce235ea-4083-4bbd-85e2-e4a201876c1f.sql index c34b3ae7a..7330d0eb8 100644 --- a/supabase/migrations/20260419184445_0ce235ea-4083-4bbd-85e2-e4a201876c1f.sql +++ b/supabase/migrations/20260419184445_0ce235ea-4083-4bbd-85e2-e4a201876c1f.sql @@ -1,5 +1,5 @@ -- 1. Tabela de log de rotação de secrets -CREATE TABLE public.secret_rotation_log ( +CREATE TABLE IF NOT EXISTS public.secret_rotation_log ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), secret_name TEXT NOT NULL, rotated_by UUID NOT NULL, @@ -9,15 +9,17 @@ CREATE TABLE public.secret_rotation_log ( notes TEXT ); -CREATE INDEX idx_secret_rotation_log_name_time +CREATE INDEX IF NOT EXISTS idx_secret_rotation_log_name_time ON public.secret_rotation_log (secret_name, rotated_at DESC); ALTER TABLE public.secret_rotation_log ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins read secret_rotation_log" ON public.secret_rotation_log; CREATE POLICY "Admins read secret_rotation_log" ON public.secret_rotation_log FOR SELECT USING (has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Admins insert secret_rotation_log" ON public.secret_rotation_log; CREATE POLICY "Admins insert secret_rotation_log" ON public.secret_rotation_log FOR INSERT WITH CHECK (has_role(auth.uid(), 'admin'::app_role) AND rotated_by = auth.uid()); diff --git a/supabase/migrations/20260419185334_4b0780a3-f1c4-4f99-aaf2-5597e820d8e6.sql b/supabase/migrations/20260419185334_4b0780a3-f1c4-4f99-aaf2-5597e820d8e6.sql index 398f2fc9a..2acb25954 100644 --- a/supabase/migrations/20260419185334_4b0780a3-f1c4-4f99-aaf2-5597e820d8e6.sql +++ b/supabase/migrations/20260419185334_4b0780a3-f1c4-4f99-aaf2-5597e820d8e6.sql @@ -1,5 +1,5 @@ -- Tabela de histórico de testes de conexões externas -CREATE TABLE public.connection_test_history ( +CREATE TABLE IF NOT EXISTS public.connection_test_history ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, connection_id UUID NOT NULL REFERENCES public.external_connections(id) ON DELETE CASCADE, tested_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), @@ -11,23 +11,26 @@ CREATE TABLE public.connection_test_history ( ); -- Índice principal de leitura -CREATE INDEX idx_connection_test_history_conn_time +CREATE INDEX IF NOT EXISTS idx_connection_test_history_conn_time ON public.connection_test_history(connection_id, tested_at DESC); -- RLS ALTER TABLE public.connection_test_history ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins read connection_test_history" ON public.connection_test_history; CREATE POLICY "Admins read connection_test_history" ON public.connection_test_history FOR SELECT USING (has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Service role inserts connection_test_history" ON public.connection_test_history; CREATE POLICY "Service role inserts connection_test_history" ON public.connection_test_history FOR INSERT TO service_role WITH CHECK (true); +DROP POLICY IF EXISTS "Admins delete connection_test_history" ON public.connection_test_history; CREATE POLICY "Admins delete connection_test_history" ON public.connection_test_history FOR DELETE @@ -53,6 +56,7 @@ BEGIN END; $$; +DROP TRIGGER IF EXISTS trg_trim_connection_test_history ON public.connection_test_history; CREATE TRIGGER trg_trim_connection_test_history AFTER INSERT ON public.connection_test_history FOR EACH ROW diff --git a/supabase/migrations/20260420123931_cfdf94d4-a89e-4f3a-bd30-2a7f43cc62df.sql b/supabase/migrations/20260420123931_cfdf94d4-a89e-4f3a-bd30-2a7f43cc62df.sql index 799e77b80..590bd30af 100644 --- a/supabase/migrations/20260420123931_cfdf94d4-a89e-4f3a-bd30-2a7f43cc62df.sql +++ b/supabase/migrations/20260420123931_cfdf94d4-a89e-4f3a-bd30-2a7f43cc62df.sql @@ -3,7 +3,7 @@ -- ============================================================ -- 1) Tabela: favorite_lists -CREATE TABLE public.favorite_lists ( +CREATE TABLE IF NOT EXISTS public.favorite_lists ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, user_id UUID NOT NULL, name TEXT NOT NULL DEFAULT 'Minha lista', @@ -21,22 +21,25 @@ CREATE TABLE public.favorite_lists ( updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); -CREATE INDEX idx_favorite_lists_user ON public.favorite_lists(user_id, position); -CREATE INDEX idx_favorite_lists_shared_token ON public.favorite_lists(shared_token) WHERE shared_token IS NOT NULL; -CREATE UNIQUE INDEX idx_favorite_lists_one_default +CREATE INDEX IF NOT EXISTS idx_favorite_lists_user ON public.favorite_lists(user_id, position); +CREATE INDEX IF NOT EXISTS idx_favorite_lists_shared_token ON public.favorite_lists(shared_token) WHERE shared_token IS NOT NULL; +CREATE UNIQUE INDEX IF NOT EXISTS idx_favorite_lists_one_default ON public.favorite_lists(user_id) WHERE is_default = true; ALTER TABLE public.favorite_lists ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users manage own favorite lists" ON public.favorite_lists; CREATE POLICY "Users manage own favorite lists" ON public.favorite_lists FOR ALL TO authenticated USING (user_id = auth.uid()) WITH CHECK (user_id = auth.uid()); +DROP POLICY IF EXISTS "Admins read all favorite lists" ON public.favorite_lists; CREATE POLICY "Admins read all favorite lists" ON public.favorite_lists FOR SELECT TO authenticated USING (has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Public can read shared lists by token" ON public.favorite_lists; CREATE POLICY "Public can read shared lists by token" ON public.favorite_lists FOR SELECT TO anon, authenticated USING ( @@ -45,7 +48,7 @@ CREATE POLICY "Public can read shared lists by token" ); -- 2) Tabela: favorite_items -CREATE TABLE public.favorite_items ( +CREATE TABLE IF NOT EXISTS public.favorite_items ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, list_id UUID NOT NULL REFERENCES public.favorite_lists(id) ON DELETE CASCADE, user_id UUID NOT NULL, @@ -59,23 +62,26 @@ CREATE TABLE public.favorite_items ( updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); -CREATE UNIQUE INDEX idx_favorite_items_unique +CREATE UNIQUE INDEX IF NOT EXISTS idx_favorite_items_unique ON public.favorite_items(list_id, product_id, COALESCE(variant_id, '')); -CREATE INDEX idx_favorite_items_user ON public.favorite_items(user_id); -CREATE INDEX idx_favorite_items_list ON public.favorite_items(list_id, position); -CREATE INDEX idx_favorite_items_product ON public.favorite_items(product_id); +CREATE INDEX IF NOT EXISTS idx_favorite_items_user ON public.favorite_items(user_id); +CREATE INDEX IF NOT EXISTS idx_favorite_items_list ON public.favorite_items(list_id, position); +CREATE INDEX IF NOT EXISTS idx_favorite_items_product ON public.favorite_items(product_id); ALTER TABLE public.favorite_items ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users manage own favorite items" ON public.favorite_items; CREATE POLICY "Users manage own favorite items" ON public.favorite_items FOR ALL TO authenticated USING (user_id = auth.uid()) WITH CHECK (user_id = auth.uid()); +DROP POLICY IF EXISTS "Admins read all favorite items" ON public.favorite_items; CREATE POLICY "Admins read all favorite items" ON public.favorite_items FOR SELECT TO authenticated USING (has_role(auth.uid(), 'admin'::app_role)); +DROP POLICY IF EXISTS "Public can read items of shared lists" ON public.favorite_items; CREATE POLICY "Public can read items of shared lists" ON public.favorite_items FOR SELECT TO anon, authenticated USING (EXISTS ( @@ -86,7 +92,7 @@ CREATE POLICY "Public can read items of shared lists" )); -- 3) Tabela: favorite_items_trash (lixeira TTL 30d) -CREATE TABLE public.favorite_items_trash ( +CREATE TABLE IF NOT EXISTS public.favorite_items_trash ( id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, original_id UUID NOT NULL, list_id UUID NOT NULL, @@ -100,21 +106,24 @@ CREATE TABLE public.favorite_items_trash ( expires_at TIMESTAMPTZ NOT NULL DEFAULT (now() + INTERVAL '30 days') ); -CREATE INDEX idx_favorite_items_trash_user ON public.favorite_items_trash(user_id, deleted_at DESC); -CREATE INDEX idx_favorite_items_trash_expires ON public.favorite_items_trash(expires_at); +CREATE INDEX IF NOT EXISTS idx_favorite_items_trash_user ON public.favorite_items_trash(user_id, deleted_at DESC); +CREATE INDEX IF NOT EXISTS idx_favorite_items_trash_expires ON public.favorite_items_trash(expires_at); ALTER TABLE public.favorite_items_trash ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users manage own trash" ON public.favorite_items_trash; CREATE POLICY "Users manage own trash" ON public.favorite_items_trash FOR ALL TO authenticated USING (user_id = auth.uid()) WITH CHECK (user_id = auth.uid()); -- 4) Trigger: updated_at +DROP TRIGGER IF EXISTS set_favorite_lists_updated_at ON public.favorite_lists; CREATE TRIGGER set_favorite_lists_updated_at BEFORE UPDATE ON public.favorite_lists FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); +DROP TRIGGER IF EXISTS set_favorite_items_updated_at ON public.favorite_items; CREATE TRIGGER set_favorite_items_updated_at BEFORE UPDATE ON public.favorite_items FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); @@ -163,6 +172,7 @@ BEGIN END; $$; +DROP TRIGGER IF EXISTS trg_favorite_items_to_trash ON public.favorite_items; CREATE TRIGGER trg_favorite_items_to_trash BEFORE DELETE ON public.favorite_items FOR EACH ROW EXECUTE FUNCTION public.move_favorite_to_trash(); diff --git a/supabase/migrations/20260420130407_e4ba785a-ef0c-4a8d-a1ce-b5b9c84d5c94.sql b/supabase/migrations/20260420130407_e4ba785a-ef0c-4a8d-a1ce-b5b9c84d5c94.sql index 75e644ecd..f2d2cdcfe 100644 --- a/supabase/migrations/20260420130407_e4ba785a-ef0c-4a8d-a1ce-b5b9c84d5c94.sql +++ b/supabase/migrations/20260420130407_e4ba785a-ef0c-4a8d-a1ce-b5b9c84d5c94.sql @@ -22,6 +22,7 @@ CREATE INDEX IF NOT EXISTS idx_favorite_reactions_created ON public.favorite_ite ALTER TABLE public.favorite_item_reactions ENABLE ROW LEVEL SECURITY; -- Pública (anon + auth): leitura/insert SE a lista pai está compartilhada por token válido +DROP POLICY IF EXISTS "Public can read reactions of shared lists" ON public.favorite_item_reactions; CREATE POLICY "Public can read reactions of shared lists" ON public.favorite_item_reactions FOR SELECT @@ -35,6 +36,7 @@ CREATE POLICY "Public can read reactions of shared lists" ) ); +DROP POLICY IF EXISTS "Public can insert reactions on shared lists" ON shared; CREATE POLICY "Public can insert reactions on shared lists" ON public.favorite_item_reactions FOR INSERT @@ -49,6 +51,7 @@ CREATE POLICY "Public can insert reactions on shared lists" ); -- Dono da lista pode ver todas as reactions de suas listas +DROP POLICY IF EXISTS "Owners read own list reactions" ON public.favorite_item_reactions; CREATE POLICY "Owners read own list reactions" ON public.favorite_item_reactions FOR SELECT @@ -62,6 +65,7 @@ CREATE POLICY "Owners read own list reactions" ); -- Dono pode deletar reactions (moderação) +DROP POLICY IF EXISTS "Owners delete own list reactions" ON public.favorite_item_reactions; CREATE POLICY "Owners delete own list reactions" ON public.favorite_item_reactions FOR DELETE @@ -75,6 +79,7 @@ CREATE POLICY "Owners delete own list reactions" ); -- Admin total +DROP POLICY IF EXISTS "Admins read all reactions" ON public.favorite_item_reactions; CREATE POLICY "Admins read all reactions" ON public.favorite_item_reactions FOR SELECT diff --git a/supabase/migrations/20260420142509_3657c725-d2da-43e4-9c02-36993a7e02f4.sql b/supabase/migrations/20260420142509_3657c725-d2da-43e4-9c02-36993a7e02f4.sql index 29f7de0dd..040f2d0a2 100644 --- a/supabase/migrations/20260420142509_3657c725-d2da-43e4-9c02-36993a7e02f4.sql +++ b/supabase/migrations/20260420142509_3657c725-d2da-43e4-9c02-36993a7e02f4.sql @@ -21,14 +21,17 @@ CREATE INDEX IF NOT EXISTS idx_collection_trash_collection ON public.collection_ ALTER TABLE public.collection_items_trash ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users view own collection trash" ON public.collection_items_trash; CREATE POLICY "Users view own collection trash" ON public.collection_items_trash FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users insert own collection trash" ON public.collection_items_trash; CREATE POLICY "Users insert own collection trash" ON public.collection_items_trash FOR INSERT WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users delete own collection trash" ON public.collection_items_trash; CREATE POLICY "Users delete own collection trash" ON public.collection_items_trash FOR DELETE USING (auth.uid() = user_id); diff --git a/supabase/migrations/20260420142542_7ad9d3cc-c5e1-44e6-b3f8-6b315c4da7f8.sql b/supabase/migrations/20260420142542_7ad9d3cc-c5e1-44e6-b3f8-6b315c4da7f8.sql index 961690c4a..ac9308044 100644 --- a/supabase/migrations/20260420142542_7ad9d3cc-c5e1-44e6-b3f8-6b315c4da7f8.sql +++ b/supabase/migrations/20260420142542_7ad9d3cc-c5e1-44e6-b3f8-6b315c4da7f8.sql @@ -14,6 +14,7 @@ CREATE INDEX IF NOT EXISTS idx_collections_share_token ON public.collections(sha CREATE INDEX IF NOT EXISTS idx_collections_client ON public.collections(client_id) WHERE client_id IS NOT NULL; -- Política: leitura pública via token válido +DROP POLICY IF EXISTS "Public can view collection by valid share token" ON public.collections; CREATE POLICY "Public can view collection by valid share token" ON public.collections FOR SELECT USING ( @@ -22,6 +23,7 @@ CREATE POLICY "Public can view collection by valid share token" AND (share_expires_at IS NULL OR share_expires_at > now()) ); +DROP POLICY IF EXISTS "Public can view items of public collections" ON public.collection_items; CREATE POLICY "Public can view items of public collections" ON public.collection_items FOR SELECT USING ( @@ -52,6 +54,7 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_collection_reactions_anon ON public.collect ALTER TABLE public.collection_item_reactions ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Public can view reactions for public collections" ON public.collection_item_reactions; CREATE POLICY "Public can view reactions for public collections" ON public.collection_item_reactions FOR SELECT USING ( @@ -70,6 +73,7 @@ CREATE POLICY "Public can view reactions for public collections" ); -- Insert via edge function (service role) +DROP POLICY IF EXISTS "Service role inserts reactions" ON public.collection_item_reactions; CREATE POLICY "Service role inserts reactions" ON public.collection_item_reactions FOR INSERT WITH CHECK (false); diff --git a/supabase/migrations/20260420172157_b0ec64e0-2e7d-496d-82c4-8dbdea3fe417.sql b/supabase/migrations/20260420172157_b0ec64e0-2e7d-496d-82c4-8dbdea3fe417.sql index 95f1a6e62..a9e02fe6c 100644 --- a/supabase/migrations/20260420172157_b0ec64e0-2e7d-496d-82c4-8dbdea3fe417.sql +++ b/supabase/migrations/20260420172157_b0ec64e0-2e7d-496d-82c4-8dbdea3fe417.sql @@ -9,13 +9,17 @@ CREATE TABLE IF NOT EXISTS public.user_preferences ( ALTER TABLE public.user_preferences ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users view own preferences" ON public.user_preferences; CREATE POLICY "Users view own preferences" ON public.user_preferences FOR SELECT USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users insert own preferences" ON public.user_preferences; CREATE POLICY "Users insert own preferences" ON public.user_preferences FOR INSERT WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users update own preferences" ON public.user_preferences; CREATE POLICY "Users update own preferences" ON public.user_preferences FOR UPDATE USING (auth.uid() = user_id); +DROP TRIGGER IF EXISTS update_user_preferences_updated_at ON public.user_preferences; CREATE TRIGGER update_user_preferences_updated_at BEFORE UPDATE ON public.user_preferences FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column(); \ No newline at end of file diff --git a/supabase/migrations/20260420185009_19ba5060-cb2d-4030-82d6-dc64b8365cee.sql b/supabase/migrations/20260420185009_19ba5060-cb2d-4030-82d6-dc64b8365cee.sql index 7eef2371e..84250b972 100644 --- a/supabase/migrations/20260420185009_19ba5060-cb2d-4030-82d6-dc64b8365cee.sql +++ b/supabase/migrations/20260420185009_19ba5060-cb2d-4030-82d6-dc64b8365cee.sql @@ -93,29 +93,49 @@ ALTER TABLE public.magic_up_comments ENABLE ROW LEVEL SECURITY; ALTER TABLE public.magic_up_reactions ENABLE ROW LEVEL SECURITY; ALTER TABLE public.magic_up_public_shares ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view own Magic Up campaigns" ON public.magic_up_campaigns; CREATE POLICY "Users can view own Magic Up campaigns" ON public.magic_up_campaigns FOR SELECT TO authenticated USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can create own Magic Up campaigns" ON public.magic_up_campaigns; CREATE POLICY "Users can create own Magic Up campaigns" ON public.magic_up_campaigns FOR INSERT TO authenticated WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can update own Magic Up campaigns" ON public.magic_up_campaigns; CREATE POLICY "Users can update own Magic Up campaigns" ON public.magic_up_campaigns FOR UPDATE TO authenticated USING (auth.uid() = user_id) WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can delete own Magic Up campaigns" ON public.magic_up_campaigns; CREATE POLICY "Users can delete own Magic Up campaigns" ON public.magic_up_campaigns FOR DELETE TO authenticated USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can view own Magic Up brand kits" ON public.magic_up_brand_kits; CREATE POLICY "Users can view own Magic Up brand kits" ON public.magic_up_brand_kits FOR SELECT TO authenticated USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can create own Magic Up brand kits" ON public.magic_up_brand_kits; CREATE POLICY "Users can create own Magic Up brand kits" ON public.magic_up_brand_kits FOR INSERT TO authenticated WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can update own Magic Up brand kits" ON public.magic_up_brand_kits; CREATE POLICY "Users can update own Magic Up brand kits" ON public.magic_up_brand_kits FOR UPDATE TO authenticated USING (auth.uid() = user_id) WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can delete own Magic Up brand kits" ON public.magic_up_brand_kits; CREATE POLICY "Users can delete own Magic Up brand kits" ON public.magic_up_brand_kits FOR DELETE TO authenticated USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can view comments on own Magic Up generations" ON own; CREATE POLICY "Users can view comments on own Magic Up generations" ON public.magic_up_comments FOR SELECT TO authenticated USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can create comments on own Magic Up generations" ON own; CREATE POLICY "Users can create comments on own Magic Up generations" ON public.magic_up_comments FOR INSERT TO authenticated WITH CHECK (auth.uid() = user_id AND EXISTS (SELECT 1 FROM public.magic_up_generations g WHERE g.id = generation_id AND g.user_id = auth.uid())); +DROP POLICY IF EXISTS "Users can update comments on own Magic Up generations" ON own; CREATE POLICY "Users can update comments on own Magic Up generations" ON public.magic_up_comments FOR UPDATE TO authenticated USING (auth.uid() = user_id) WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can delete comments on own Magic Up generations" ON own; CREATE POLICY "Users can delete comments on own Magic Up generations" ON public.magic_up_comments FOR DELETE TO authenticated USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can view reactions on own Magic Up generations" ON own; CREATE POLICY "Users can view reactions on own Magic Up generations" ON public.magic_up_reactions FOR SELECT TO authenticated USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can create reactions on own Magic Up generations" ON own; CREATE POLICY "Users can create reactions on own Magic Up generations" ON public.magic_up_reactions FOR INSERT TO authenticated WITH CHECK (auth.uid() = user_id AND EXISTS (SELECT 1 FROM public.magic_up_generations g WHERE g.id = generation_id AND g.user_id = auth.uid())); +DROP POLICY IF EXISTS "Users can update reactions on own Magic Up generations" ON own; CREATE POLICY "Users can update reactions on own Magic Up generations" ON public.magic_up_reactions FOR UPDATE TO authenticated USING (auth.uid() = user_id) WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can delete reactions on own Magic Up generations" ON own; CREATE POLICY "Users can delete reactions on own Magic Up generations" ON public.magic_up_reactions FOR DELETE TO authenticated USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can view own Magic Up public shares" ON public.magic_up_public_shares; CREATE POLICY "Users can view own Magic Up public shares" ON public.magic_up_public_shares FOR SELECT TO authenticated USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can create own Magic Up public shares" ON public.magic_up_public_shares; CREATE POLICY "Users can create own Magic Up public shares" ON public.magic_up_public_shares FOR INSERT TO authenticated WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can update own Magic Up public shares" ON public.magic_up_public_shares; CREATE POLICY "Users can update own Magic Up public shares" ON public.magic_up_public_shares FOR UPDATE TO authenticated USING (auth.uid() = user_id) WITH CHECK (auth.uid() = user_id); +DROP POLICY IF EXISTS "Users can delete own Magic Up public shares" ON public.magic_up_public_shares; CREATE POLICY "Users can delete own Magic Up public shares" ON public.magic_up_public_shares FOR DELETE TO authenticated USING (auth.uid() = user_id); CREATE INDEX IF NOT EXISTS idx_magic_up_campaigns_user_status ON public.magic_up_campaigns(user_id, status, created_at DESC); diff --git a/supabase/migrations/20260423123340_fix_all_views_security_invoker_batch1.sql b/supabase/migrations/20260423123340_fix_all_views_security_invoker_batch1.sql new file mode 100644 index 000000000..bc74f516d --- /dev/null +++ b/supabase/migrations/20260423123340_fix_all_views_security_invoker_batch1.sql @@ -0,0 +1,2 @@ +-- Migration 20260423123340 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260423123406_fix_all_views_security_invoker_batch2.sql b/supabase/migrations/20260423123406_fix_all_views_security_invoker_batch2.sql new file mode 100644 index 000000000..c5f6b8533 --- /dev/null +++ b/supabase/migrations/20260423123406_fix_all_views_security_invoker_batch2.sql @@ -0,0 +1,2 @@ +-- Migration 20260423123406 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260423123503_fix_all_functions_search_path_safe.sql b/supabase/migrations/20260423123503_fix_all_functions_search_path_safe.sql new file mode 100644 index 000000000..3ed859166 --- /dev/null +++ b/supabase/migrations/20260423123503_fix_all_functions_search_path_safe.sql @@ -0,0 +1,2 @@ +-- Migration 20260423123503 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260423123546_fix_rls_restrict_public_all_policies.sql b/supabase/migrations/20260423123546_fix_rls_restrict_public_all_policies.sql new file mode 100644 index 000000000..72e9d6712 --- /dev/null +++ b/supabase/migrations/20260423123546_fix_rls_restrict_public_all_policies.sql @@ -0,0 +1,2 @@ +-- Migration 20260423123546 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260423123712_fix_supplier_products_raw_rls_policy.sql b/supabase/migrations/20260423123712_fix_supplier_products_raw_rls_policy.sql new file mode 100644 index 000000000..cdcd22890 --- /dev/null +++ b/supabase/migrations/20260423123712_fix_supplier_products_raw_rls_policy.sql @@ -0,0 +1,2 @@ +-- Migration 20260423123712 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260423123729_fix_rls_insert_always_true_to_service.sql b/supabase/migrations/20260423123729_fix_rls_insert_always_true_to_service.sql new file mode 100644 index 000000000..5d03bb5fa --- /dev/null +++ b/supabase/migrations/20260423123729_fix_rls_insert_always_true_to_service.sql @@ -0,0 +1,2 @@ +-- Migration 20260423123729 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260423145604_f3748654-19e3-4d8c-bc72-bcfeee5df79c.sql b/supabase/migrations/20260423145604_f3748654-19e3-4d8c-bc72-bcfeee5df79c.sql index 137c1d540..064ca5f5f 100644 --- a/supabase/migrations/20260423145604_f3748654-19e3-4d8c-bc72-bcfeee5df79c.sql +++ b/supabase/migrations/20260423145604_f3748654-19e3-4d8c-bc72-bcfeee5df79c.sql @@ -17,18 +17,21 @@ CREATE INDEX IF NOT EXISTS idx_integration_credentials_name ALTER TABLE public.integration_credentials ENABLE ROW LEVEL SECURITY; -- RLS: somente admins +DROP POLICY IF EXISTS "Admins can view integration credentials" ON public.integration_credentials; CREATE POLICY "Admins can view integration credentials" ON public.integration_credentials FOR SELECT TO authenticated USING (public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Admins can insert integration credentials" ON public.integration_credentials; CREATE POLICY "Admins can insert integration credentials" ON public.integration_credentials FOR INSERT TO authenticated WITH CHECK (public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Admins can update integration credentials" ON public.integration_credentials; CREATE POLICY "Admins can update integration credentials" ON public.integration_credentials FOR UPDATE @@ -36,6 +39,7 @@ CREATE POLICY "Admins can update integration credentials" USING (public.has_role(auth.uid(), 'admin')) WITH CHECK (public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Admins can delete integration credentials" ON public.integration_credentials; CREATE POLICY "Admins can delete integration credentials" ON public.integration_credentials FOR DELETE diff --git a/supabase/migrations/20260423193705_0c82aded-4fab-436d-a56f-4b96ecdb4a6f.sql b/supabase/migrations/20260423193705_0c82aded-4fab-436d-a56f-4b96ecdb4a6f.sql index 4a5b215c3..d6bed0a9b 100644 --- a/supabase/migrations/20260423193705_0c82aded-4fab-436d-a56f-4b96ecdb4a6f.sql +++ b/supabase/migrations/20260423193705_0c82aded-4fab-436d-a56f-4b96ecdb4a6f.sql @@ -12,18 +12,21 @@ CREATE TABLE IF NOT EXISTS public.admin_settings ( ALTER TABLE public.admin_settings ENABLE ROW LEVEL SECURITY; -- Admin-only access (read + write). Relies on the existing has_role() helper. +DROP POLICY IF EXISTS "Admins can view admin_settings" ON public.admin_settings; CREATE POLICY "Admins can view admin_settings" ON public.admin_settings FOR SELECT TO authenticated USING (public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Admins can insert admin_settings" ON public.admin_settings; CREATE POLICY "Admins can insert admin_settings" ON public.admin_settings FOR INSERT TO authenticated WITH CHECK (public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Admins can update admin_settings" ON public.admin_settings; CREATE POLICY "Admins can update admin_settings" ON public.admin_settings FOR UPDATE @@ -31,6 +34,7 @@ TO authenticated USING (public.has_role(auth.uid(), 'admin')) WITH CHECK (public.has_role(auth.uid(), 'admin')); +DROP TRIGGER IF EXISTS update_admin_settings_updated_at ON public.admin_settings; CREATE TRIGGER update_admin_settings_updated_at BEFORE UPDATE ON public.admin_settings FOR EACH ROW diff --git a/supabase/migrations/20260424104612_add_price_updated_at_to_vss.sql b/supabase/migrations/20260424104612_add_price_updated_at_to_vss.sql new file mode 100644 index 000000000..47bb01b12 --- /dev/null +++ b/supabase/migrations/20260424104612_add_price_updated_at_to_vss.sql @@ -0,0 +1,2 @@ +-- Migration 20260424104612 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260424104632_add_price_updated_at_to_products.sql b/supabase/migrations/20260424104632_add_price_updated_at_to_products.sql new file mode 100644 index 000000000..4e09c8472 --- /dev/null +++ b/supabase/migrations/20260424104632_add_price_updated_at_to_products.sql @@ -0,0 +1,2 @@ +-- Migration 20260424104632 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260424110636_f5d85f4b-a5ae-46a4-932a-409dff195653.sql b/supabase/migrations/20260424110636_f5d85f4b-a5ae-46a4-932a-409dff195653.sql index 377553707..cb9b5fe9d 100644 --- a/supabase/migrations/20260424110636_f5d85f4b-a5ae-46a4-932a-409dff195653.sql +++ b/supabase/migrations/20260424110636_f5d85f4b-a5ae-46a4-932a-409dff195653.sql @@ -1,7 +1,7 @@ -- Tabela local de overrides de validade de preço por produto. -- O BD externo (catálogo) é SSOT do produto, mas a janela de validade é um -- conceito operacional do nosso vendedor — fica isolada aqui. -CREATE TABLE public.product_price_freshness_overrides ( +CREATE TABLE IF NOT EXISTS public.product_price_freshness_overrides ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), product_id text NOT NULL UNIQUE, threshold_days int NOT NULL CHECK (threshold_days IN (30, 60, 90)), @@ -10,12 +10,13 @@ CREATE TABLE public.product_price_freshness_overrides ( updated_at timestamptz NOT NULL DEFAULT now() ); -CREATE INDEX idx_pfo_product_id +CREATE INDEX IF NOT EXISTS idx_pfo_product_id ON public.product_price_freshness_overrides (product_id); ALTER TABLE public.product_price_freshness_overrides ENABLE ROW LEVEL SECURITY; -- Leitura: todo autenticado (badge precisa do valor para qualquer vendedor). +DROP POLICY IF EXISTS "Authenticated can read freshness overrides" ON public.product_price_freshness_overrides; CREATE POLICY "Authenticated can read freshness overrides" ON public.product_price_freshness_overrides FOR SELECT @@ -23,12 +24,14 @@ CREATE POLICY "Authenticated can read freshness overrides" USING (true); -- Escrita: somente admins. +DROP POLICY IF EXISTS "Admins can insert freshness overrides" ON public.product_price_freshness_overrides; CREATE POLICY "Admins can insert freshness overrides" ON public.product_price_freshness_overrides FOR INSERT TO authenticated WITH CHECK (public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Admins can update freshness overrides" ON public.product_price_freshness_overrides; CREATE POLICY "Admins can update freshness overrides" ON public.product_price_freshness_overrides FOR UPDATE @@ -36,6 +39,7 @@ CREATE POLICY "Admins can update freshness overrides" USING (public.has_role(auth.uid(), 'admin')) WITH CHECK (public.has_role(auth.uid(), 'admin')); +DROP POLICY IF EXISTS "Admins can delete freshness overrides" ON public.product_price_freshness_overrides; CREATE POLICY "Admins can delete freshness overrides" ON public.product_price_freshness_overrides FOR DELETE @@ -43,6 +47,7 @@ CREATE POLICY "Admins can delete freshness overrides" USING (public.has_role(auth.uid(), 'admin')); -- updated_at automático. +DROP TRIGGER IF EXISTS trg_pfo_set_updated_at ON public.product_price_freshness_overrides; CREATE TRIGGER trg_pfo_set_updated_at BEFORE UPDATE ON public.product_price_freshness_overrides FOR EACH ROW diff --git a/supabase/migrations/20260425150735_delete_bord_dir_01_with_backup.sql b/supabase/migrations/20260425150735_delete_bord_dir_01_with_backup.sql new file mode 100644 index 000000000..e8cf3d1ce --- /dev/null +++ b/supabase/migrations/20260425150735_delete_bord_dir_01_with_backup.sql @@ -0,0 +1,2 @@ +-- Migration 20260425150735 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425152341_backup_e_matriz_mochila_pre_faxina.sql b/supabase/migrations/20260425152341_backup_e_matriz_mochila_pre_faxina.sql new file mode 100644 index 000000000..722f89026 --- /dev/null +++ b/supabase/migrations/20260425152341_backup_e_matriz_mochila_pre_faxina.sql @@ -0,0 +1,2 @@ +-- Migration 20260425152341 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425153052_faxina_fase5_matriz_v2_e_debito_tecnico.sql b/supabase/migrations/20260425153052_faxina_fase5_matriz_v2_e_debito_tecnico.sql new file mode 100644 index 000000000..b575b9c7f --- /dev/null +++ b/supabase/migrations/20260425153052_faxina_fase5_matriz_v2_e_debito_tecnico.sql @@ -0,0 +1,2 @@ +-- Migration 20260425153052 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425154940_p1_1_corrigir_paradoxo_co2_cn_01.sql b/supabase/migrations/20260425154940_p1_1_corrigir_paradoxo_co2_cn_01.sql new file mode 100644 index 000000000..960307761 --- /dev/null +++ b/supabase/migrations/20260425154940_p1_1_corrigir_paradoxo_co2_cn_01.sql @@ -0,0 +1,2 @@ +-- Migration 20260425154940 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425155046_p1_2_corrigir_curva_v_uvdig_canetas.sql b/supabase/migrations/20260425155046_p1_2_corrigir_curva_v_uvdig_canetas.sql new file mode 100644 index 000000000..9d4fce854 --- /dev/null +++ b/supabase/migrations/20260425155046_p1_2_corrigir_curva_v_uvdig_canetas.sql @@ -0,0 +1,2 @@ +-- Migration 20260425155046 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425155201_p1_3_clamp_paradoxos_dimensionais.sql b/supabase/migrations/20260425155201_p1_3_clamp_paradoxos_dimensionais.sql new file mode 100644 index 000000000..13a252faa --- /dev/null +++ b/supabase/migrations/20260425155201_p1_3_clamp_paradoxos_dimensionais.sql @@ -0,0 +1,2 @@ +-- Migration 20260425155201 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425155226_p2_corrigir_custo_aplicacao_null.sql b/supabase/migrations/20260425155226_p2_corrigir_custo_aplicacao_null.sql new file mode 100644 index 000000000..32c8ec388 --- /dev/null +++ b/supabase/migrations/20260425155226_p2_corrigir_custo_aplicacao_null.sql @@ -0,0 +1,2 @@ +-- Migration 20260425155226 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425155311_p3_corrigir_seriuv_cil_360_full_color.sql b/supabase/migrations/20260425155311_p3_corrigir_seriuv_cil_360_full_color.sql new file mode 100644 index 000000000..b2f3356ea --- /dev/null +++ b/supabase/migrations/20260425155311_p3_corrigir_seriuv_cil_360_full_color.sql @@ -0,0 +1,2 @@ +-- Migration 20260425155311 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425155349_p4_desativar_38_tecnicas_orfas.sql b/supabase/migrations/20260425155349_p4_desativar_38_tecnicas_orfas.sql new file mode 100644 index 000000000..e4da0f1f2 --- /dev/null +++ b/supabase/migrations/20260425155349_p4_desativar_38_tecnicas_orfas.sql @@ -0,0 +1,2 @@ +-- Migration 20260425155349 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425155423_p6_preencher_max_cores_uv_digital.sql b/supabase/migrations/20260425155423_p6_preencher_max_cores_uv_digital.sql new file mode 100644 index 000000000..a6468918e --- /dev/null +++ b/supabase/migrations/20260425155423_p6_preencher_max_cores_uv_digital.sql @@ -0,0 +1,2 @@ +-- Migration 20260425155423 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425155524_p7_corrigir_flag_dimensional.sql b/supabase/migrations/20260425155524_p7_corrigir_flag_dimensional.sql new file mode 100644 index 000000000..8632c33f5 --- /dev/null +++ b/supabase/migrations/20260425155524_p7_corrigir_flag_dimensional.sql @@ -0,0 +1,2 @@ +-- Migration 20260425155524 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425160208_p8_preencher_prazo_dias_null.sql b/supabase/migrations/20260425160208_p8_preencher_prazo_dias_null.sql new file mode 100644 index 000000000..e7d4f0174 --- /dev/null +++ b/supabase/migrations/20260425160208_p8_preencher_prazo_dias_null.sql @@ -0,0 +1,2 @@ +-- Migration 20260425160208 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425160528_p11_documentacao_excelencia_25_04_2026.sql b/supabase/migrations/20260425160528_p11_documentacao_excelencia_25_04_2026.sql new file mode 100644 index 000000000..9aeecd029 --- /dev/null +++ b/supabase/migrations/20260425160528_p11_documentacao_excelencia_25_04_2026.sql @@ -0,0 +1,2 @@ +-- Migration 20260425160528 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425163605_p16_documentar_fiber_cil_01_design_intencional.sql b/supabase/migrations/20260425163605_p16_documentar_fiber_cil_01_design_intencional.sql new file mode 100644 index 000000000..5d15cb58e --- /dev/null +++ b/supabase/migrations/20260425163605_p16_documentar_fiber_cil_01_design_intencional.sql @@ -0,0 +1,2 @@ +-- Migration 20260425163605 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425164021_feb09752-3b1b-491d-bc44-4905fb74cf8e.sql b/supabase/migrations/20260425164021_feb09752-3b1b-491d-bc44-4905fb74cf8e.sql index cc53b2250..82bcd145f 100644 --- a/supabase/migrations/20260425164021_feb09752-3b1b-491d-bc44-4905fb74cf8e.sql +++ b/supabase/migrations/20260425164021_feb09752-3b1b-491d-bc44-4905fb74cf8e.sql @@ -93,6 +93,7 @@ $$; DROP TRIGGER IF EXISTS sync_external_connections_on_credential_change ON public.integration_credentials; +DROP TRIGGER IF EXISTS sync_external_connections_on_credential_change ON public.integration_credentials; CREATE TRIGGER sync_external_connections_on_credential_change AFTER INSERT OR UPDATE OR DELETE ON public.integration_credentials FOR EACH ROW diff --git a/supabase/migrations/20260425164834_backup_snapshot_gravacao_20260425.sql b/supabase/migrations/20260425164834_backup_snapshot_gravacao_20260425.sql new file mode 100644 index 000000000..f5b88ff72 --- /dev/null +++ b/supabase/migrations/20260425164834_backup_snapshot_gravacao_20260425.sql @@ -0,0 +1,2 @@ +-- Migration 20260425164834 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425164859_fix_01_qty_maxima_null_sentinel.sql b/supabase/migrations/20260425164859_fix_01_qty_maxima_null_sentinel.sql new file mode 100644 index 000000000..1bf214f5b --- /dev/null +++ b/supabase/migrations/20260425164859_fix_01_qty_maxima_null_sentinel.sql @@ -0,0 +1,2 @@ +-- Migration 20260425164859 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425164921_fix_02_regra_anti_paradoxo_universal.sql b/supabase/migrations/20260425164921_fix_02_regra_anti_paradoxo_universal.sql new file mode 100644 index 000000000..77c73597f --- /dev/null +++ b/supabase/migrations/20260425164921_fix_02_regra_anti_paradoxo_universal.sql @@ -0,0 +1,2 @@ +-- Migration 20260425164921 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425164948_fix_03_multiplicador_cor_explicito.sql b/supabase/migrations/20260425164948_fix_03_multiplicador_cor_explicito.sql new file mode 100644 index 000000000..e724a48c4 --- /dev/null +++ b/supabase/migrations/20260425164948_fix_03_multiplicador_cor_explicito.sql @@ -0,0 +1,2 @@ +-- Migration 20260425164948 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425165022_fix_04_faturamento_minimo_universal.sql b/supabase/migrations/20260425165022_fix_04_faturamento_minimo_universal.sql new file mode 100644 index 000000000..e9193423a --- /dev/null +++ b/supabase/migrations/20260425165022_fix_04_faturamento_minimo_universal.sql @@ -0,0 +1,2 @@ +-- Migration 20260425165022 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425165126_fix_05_fn_simular_combo_gravacao_v10.sql b/supabase/migrations/20260425165126_fix_05_fn_simular_combo_gravacao_v10.sql new file mode 100644 index 000000000..f08160a0f --- /dev/null +++ b/supabase/migrations/20260425165126_fix_05_fn_simular_combo_gravacao_v10.sql @@ -0,0 +1,2 @@ +-- Migration 20260425165126 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425165208_pad_01_deprecar_descontos_cor.sql b/supabase/migrations/20260425165208_pad_01_deprecar_descontos_cor.sql new file mode 100644 index 000000000..645d1dc53 --- /dev/null +++ b/supabase/migrations/20260425165208_pad_01_deprecar_descontos_cor.sql @@ -0,0 +1,2 @@ +-- Migration 20260425165208 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425165229_pad_02_reconciliar_preco_minimo.sql b/supabase/migrations/20260425165229_pad_02_reconciliar_preco_minimo.sql new file mode 100644 index 000000000..590c75afc --- /dev/null +++ b/supabase/migrations/20260425165229_pad_02_reconciliar_preco_minimo.sql @@ -0,0 +1,2 @@ +-- Migration 20260425165229 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425165252_pad_03_documentar_setup_por_cor_pendente.sql b/supabase/migrations/20260425165252_pad_03_documentar_setup_por_cor_pendente.sql new file mode 100644 index 000000000..0307ca3a1 --- /dev/null +++ b/supabase/migrations/20260425165252_pad_03_documentar_setup_por_cor_pendente.sql @@ -0,0 +1,2 @@ +-- Migration 20260425165252 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425165305_pad_04_desativar_tecnicas_zumbi.sql b/supabase/migrations/20260425165305_pad_04_desativar_tecnicas_zumbi.sql new file mode 100644 index 000000000..3cb909e7b --- /dev/null +++ b/supabase/migrations/20260425165305_pad_04_desativar_tecnicas_zumbi.sql @@ -0,0 +1,2 @@ +-- Migration 20260425165305 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425165323_pad_05_drop_funcoes_quebradas.sql b/supabase/migrations/20260425165323_pad_05_drop_funcoes_quebradas.sql new file mode 100644 index 000000000..d5bcc3082 --- /dev/null +++ b/supabase/migrations/20260425165323_pad_05_drop_funcoes_quebradas.sql @@ -0,0 +1,2 @@ +-- Migration 20260425165323 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425165423_exp_01_documentar_gap_dimensional.sql b/supabase/migrations/20260425165423_exp_01_documentar_gap_dimensional.sql new file mode 100644 index 000000000..c5188a4ec --- /dev/null +++ b/supabase/migrations/20260425165423_exp_01_documentar_gap_dimensional.sql @@ -0,0 +1,2 @@ +-- Migration 20260425165423 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425165449_exp_02_categorizar_inativas.sql b/supabase/migrations/20260425165449_exp_02_categorizar_inativas.sql new file mode 100644 index 000000000..170efa920 --- /dev/null +++ b/supabase/migrations/20260425165449_exp_02_categorizar_inativas.sql @@ -0,0 +1,2 @@ +-- Migration 20260425165449 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425165830_exp_03_reativar_sublimacao_camiseta.sql b/supabase/migrations/20260425165830_exp_03_reativar_sublimacao_camiseta.sql new file mode 100644 index 000000000..84f1efdb6 --- /dev/null +++ b/supabase/migrations/20260425165830_exp_03_reativar_sublimacao_camiseta.sql @@ -0,0 +1,2 @@ +-- Migration 20260425165830 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425165923_exp_04_fn_recomendar_tecnica.sql b/supabase/migrations/20260425165923_exp_04_fn_recomendar_tecnica.sql new file mode 100644 index 000000000..fe6a44f5a --- /dev/null +++ b/supabase/migrations/20260425165923_exp_04_fn_recomendar_tecnica.sql @@ -0,0 +1,2 @@ +-- Migration 20260425165923 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425170004_gov_01_view_audit_paradoxos.sql b/supabase/migrations/20260425170004_gov_01_view_audit_paradoxos.sql new file mode 100644 index 000000000..9046862c9 --- /dev/null +++ b/supabase/migrations/20260425170004_gov_01_view_audit_paradoxos.sql @@ -0,0 +1,2 @@ +-- Migration 20260425170004 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425170029_gov_02_trigger_preco_minimo.sql b/supabase/migrations/20260425170029_gov_02_trigger_preco_minimo.sql new file mode 100644 index 000000000..8e23fcf84 --- /dev/null +++ b/supabase/migrations/20260425170029_gov_02_trigger_preco_minimo.sql @@ -0,0 +1,2 @@ +-- Migration 20260425170029 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425170056_gov_03_view_cobertura_tecnicas.sql b/supabase/migrations/20260425170056_gov_03_view_cobertura_tecnicas.sql new file mode 100644 index 000000000..4f6868755 --- /dev/null +++ b/supabase/migrations/20260425170056_gov_03_view_cobertura_tecnicas.sql @@ -0,0 +1,2 @@ +-- Migration 20260425170056 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425172528_a08671a6-52a2-4d70-acfe-45293eb64233.sql b/supabase/migrations/20260425172528_a08671a6-52a2-4d70-acfe-45293eb64233.sql index a50f7472f..1ba145e23 100644 --- a/supabase/migrations/20260425172528_a08671a6-52a2-4d70-acfe-45293eb64233.sql +++ b/supabase/migrations/20260425172528_a08671a6-52a2-4d70-acfe-45293eb64233.sql @@ -24,6 +24,7 @@ ALTER TABLE public.external_connections_sync_log ENABLE ROW LEVEL SECURITY; DROP POLICY IF EXISTS "Admins read external_connections_sync_log" ON public.external_connections_sync_log; +DROP POLICY IF EXISTS "Admins read external_connections_sync_log" ON public.external_connections_sync_log; CREATE POLICY "Admins read external_connections_sync_log" ON public.external_connections_sync_log FOR SELECT @@ -197,6 +198,7 @@ $$; DROP TRIGGER IF EXISTS sync_external_connections_on_credential_change ON public.integration_credentials; +DROP TRIGGER IF EXISTS sync_external_connections_on_credential_change ON public.integration_credentials; CREATE TRIGGER sync_external_connections_on_credential_change AFTER INSERT OR UPDATE OR DELETE ON public.integration_credentials FOR EACH ROW diff --git a/supabase/migrations/20260425172816_fix_06_materiais_aplicaveis_completos.sql b/supabase/migrations/20260425172816_fix_06_materiais_aplicaveis_completos.sql new file mode 100644 index 000000000..bcf5bb086 --- /dev/null +++ b/supabase/migrations/20260425172816_fix_06_materiais_aplicaveis_completos.sql @@ -0,0 +1,2 @@ +-- Migration 20260425172816 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425172840_fix_07_padronizar_faturamento_minimo.sql b/supabase/migrations/20260425172840_fix_07_padronizar_faturamento_minimo.sql new file mode 100644 index 000000000..4f7922b21 --- /dev/null +++ b/supabase/migrations/20260425172840_fix_07_padronizar_faturamento_minimo.sql @@ -0,0 +1,2 @@ +-- Migration 20260425172840 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425172911_fix_08_versao_modelo_universal.sql b/supabase/migrations/20260425172911_fix_08_versao_modelo_universal.sql new file mode 100644 index 000000000..c50ea8082 --- /dev/null +++ b/supabase/migrations/20260425172911_fix_08_versao_modelo_universal.sql @@ -0,0 +1,2 @@ +-- Migration 20260425172911 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425173013_fix_09_fn_simular_v11_com_diagnostico.sql b/supabase/migrations/20260425173013_fix_09_fn_simular_v11_com_diagnostico.sql new file mode 100644 index 000000000..008db1733 --- /dev/null +++ b/supabase/migrations/20260425173013_fix_09_fn_simular_v11_com_diagnostico.sql @@ -0,0 +1,2 @@ +-- Migration 20260425173013 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425173130_fix_10_cadastrar_subl_cam_em_produtos.sql b/supabase/migrations/20260425173130_fix_10_cadastrar_subl_cam_em_produtos.sql new file mode 100644 index 000000000..7722cc5ed --- /dev/null +++ b/supabase/migrations/20260425173130_fix_10_cadastrar_subl_cam_em_produtos.sql @@ -0,0 +1,2 @@ +-- Migration 20260425173130 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425173205_fix_10_documentar_subl_cam_no_jsonb.sql b/supabase/migrations/20260425173205_fix_10_documentar_subl_cam_no_jsonb.sql new file mode 100644 index 000000000..59b89b317 --- /dev/null +++ b/supabase/migrations/20260425173205_fix_10_documentar_subl_cam_no_jsonb.sql @@ -0,0 +1,2 @@ +-- Migration 20260425173205 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425173226_fix_11_documentar_divergencias_a3_a4.sql b/supabase/migrations/20260425173226_fix_11_documentar_divergencias_a3_a4.sql new file mode 100644 index 000000000..240727d15 --- /dev/null +++ b/supabase/migrations/20260425173226_fix_11_documentar_divergencias_a3_a4.sql @@ -0,0 +1,2 @@ +-- Migration 20260425173226 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425173621_fix_12_indice_composto_otimizado.sql b/supabase/migrations/20260425173621_fix_12_indice_composto_otimizado.sql new file mode 100644 index 000000000..f2626ad24 --- /dev/null +++ b/supabase/migrations/20260425173621_fix_12_indice_composto_otimizado.sql @@ -0,0 +1,2 @@ +-- Migration 20260425173621 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425173707_fix_13_consolidar_documentacao_jsonb.sql b/supabase/migrations/20260425173707_fix_13_consolidar_documentacao_jsonb.sql new file mode 100644 index 000000000..6e8c087c4 --- /dev/null +++ b/supabase/migrations/20260425173707_fix_13_consolidar_documentacao_jsonb.sql @@ -0,0 +1,2 @@ +-- Migration 20260425173707 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425173753_fix_14_resolver_exp_01_decisao_definitiva.sql b/supabase/migrations/20260425173753_fix_14_resolver_exp_01_decisao_definitiva.sql new file mode 100644 index 000000000..94d94ea86 --- /dev/null +++ b/supabase/migrations/20260425173753_fix_14_resolver_exp_01_decisao_definitiva.sql @@ -0,0 +1,2 @@ +-- Migration 20260425173753 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425173833_fix_15_resolver_pad_03_recomendacoes.sql b/supabase/migrations/20260425173833_fix_15_resolver_pad_03_recomendacoes.sql new file mode 100644 index 000000000..cc48d2311 --- /dev/null +++ b/supabase/migrations/20260425173833_fix_15_resolver_pad_03_recomendacoes.sql @@ -0,0 +1,2 @@ +-- Migration 20260425173833 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425173855_fix_16_audit_log_gravacao.sql b/supabase/migrations/20260425173855_fix_16_audit_log_gravacao.sql new file mode 100644 index 000000000..446b4b714 --- /dev/null +++ b/supabase/migrations/20260425173855_fix_16_audit_log_gravacao.sql @@ -0,0 +1,2 @@ +-- Migration 20260425173855 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425173947_fix_17_fn_health_check_gravacao.sql b/supabase/migrations/20260425173947_fix_17_fn_health_check_gravacao.sql new file mode 100644 index 000000000..62bf3ada7 --- /dev/null +++ b/supabase/migrations/20260425173947_fix_17_fn_health_check_gravacao.sql @@ -0,0 +1,2 @@ +-- Migration 20260425173947 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425174021_fix_18_documentacao_completa_comments.sql b/supabase/migrations/20260425174021_fix_18_documentacao_completa_comments.sql new file mode 100644 index 000000000..a3293f623 --- /dev/null +++ b/supabase/migrations/20260425174021_fix_18_documentacao_completa_comments.sql @@ -0,0 +1,2 @@ +-- Migration 20260425174021 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425174105_fix_19_promover_v10_como_canonica.sql b/supabase/migrations/20260425174105_fix_19_promover_v10_como_canonica.sql new file mode 100644 index 000000000..36742cdf1 --- /dev/null +++ b/supabase/migrations/20260425174105_fix_19_promover_v10_como_canonica.sql @@ -0,0 +1,2 @@ +-- Migration 20260425174105 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425174141_fix_20_documentar_funcoes_legacy.sql b/supabase/migrations/20260425174141_fix_20_documentar_funcoes_legacy.sql new file mode 100644 index 000000000..5792d4c26 --- /dev/null +++ b/supabase/migrations/20260425174141_fix_20_documentar_funcoes_legacy.sql @@ -0,0 +1,2 @@ +-- Migration 20260425174141 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260425192845_22e6aad7-836f-478e-bedc-98db7fc74778.sql b/supabase/migrations/20260425192845_22e6aad7-836f-478e-bedc-98db7fc74778.sql index f6211c664..2d3f297bf 100644 --- a/supabase/migrations/20260425192845_22e6aad7-836f-478e-bedc-98db7fc74778.sql +++ b/supabase/migrations/20260425192845_22e6aad7-836f-478e-bedc-98db7fc74778.sql @@ -8,6 +8,7 @@ CREATE POLICY "Admins read mcp_api_keys" TO authenticated USING (public.has_role(auth.uid(), 'admin'::public.app_role)); +DROP POLICY IF EXISTS "Admins update mcp_api_keys" ON public.mcp_api_keys; CREATE POLICY "Admins update mcp_api_keys" ON public.mcp_api_keys FOR UPDATE @@ -15,6 +16,7 @@ CREATE POLICY "Admins update mcp_api_keys" USING (public.has_role(auth.uid(), 'admin'::public.app_role)) WITH CHECK (public.has_role(auth.uid(), 'admin'::public.app_role)); +DROP POLICY IF EXISTS "Admins delete mcp_api_keys" ON public.mcp_api_keys; CREATE POLICY "Admins delete mcp_api_keys" ON public.mcp_api_keys FOR DELETE diff --git a/supabase/migrations/20260425203103_eec2662c-3ad4-48ca-8fcb-f3cbf6be16bc.sql b/supabase/migrations/20260425203103_eec2662c-3ad4-48ca-8fcb-f3cbf6be16bc.sql index 90269f2ba..2e907bb3a 100644 --- a/supabase/migrations/20260425203103_eec2662c-3ad4-48ca-8fcb-f3cbf6be16bc.sql +++ b/supabase/migrations/20260425203103_eec2662c-3ad4-48ca-8fcb-f3cbf6be16bc.sql @@ -4,6 +4,7 @@ -- ========================================================= -- Enum de ações que exigem step-up +DO $$ BEGIN CREATE TYPE public.step_up_action AS ENUM ( 'promote_dev', 'demote_dev', @@ -12,9 +13,11 @@ CREATE TYPE public.step_up_action AS ENUM ( 'secret_rotation', 'secret_revoke' ); +EXCEPTION WHEN duplicate_object THEN NULL; +END $$; -- Tabela de challenges (OTP enviado por e-mail) -CREATE TABLE public.step_up_challenges ( +CREATE TABLE IF NOT EXISTS public.step_up_challenges ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL, action public.step_up_action NOT NULL, @@ -31,18 +34,19 @@ CREATE TABLE public.step_up_challenges ( user_agent TEXT ); -CREATE INDEX idx_step_up_challenges_user ON public.step_up_challenges(user_id, created_at DESC); -CREATE INDEX idx_step_up_challenges_expires ON public.step_up_challenges(expires_at) WHERE consumed = false; +CREATE INDEX IF NOT EXISTS idx_step_up_challenges_user ON public.step_up_challenges(user_id, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_step_up_challenges_expires ON public.step_up_challenges(expires_at) WHERE consumed = false; ALTER TABLE public.step_up_challenges ENABLE ROW LEVEL SECURITY; -- Apenas o dono vê seus challenges; ninguém faz INSERT/UPDATE direto (apenas via RPC SECURITY DEFINER) +DROP POLICY IF EXISTS "Users can view own challenges" ON public.step_up_challenges; CREATE POLICY "Users can view own challenges" ON public.step_up_challenges FOR SELECT USING (auth.uid() = user_id); -- Tokens de uso único emitidos após verificação completa -CREATE TABLE public.step_up_tokens ( +CREATE TABLE IF NOT EXISTS public.step_up_tokens ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL, action public.step_up_action NOT NULL, @@ -55,17 +59,18 @@ CREATE TABLE public.step_up_tokens ( consumed_at TIMESTAMPTZ ); -CREATE INDEX idx_step_up_tokens_hash ON public.step_up_tokens(token_hash) WHERE consumed = false; -CREATE INDEX idx_step_up_tokens_user ON public.step_up_tokens(user_id, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_step_up_tokens_hash ON public.step_up_tokens(token_hash) WHERE consumed = false; +CREATE INDEX IF NOT EXISTS idx_step_up_tokens_user ON public.step_up_tokens(user_id, created_at DESC); ALTER TABLE public.step_up_tokens ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Users can view own tokens" ON public.step_up_tokens; CREATE POLICY "Users can view own tokens" ON public.step_up_tokens FOR SELECT USING (auth.uid() = user_id); -- Auditoria -CREATE TABLE public.step_up_audit_log ( +CREATE TABLE IF NOT EXISTS public.step_up_audit_log ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID, action public.step_up_action, @@ -79,15 +84,17 @@ CREATE TABLE public.step_up_audit_log ( created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); -CREATE INDEX idx_step_up_audit_user ON public.step_up_audit_log(user_id, created_at DESC); -CREATE INDEX idx_step_up_audit_action ON public.step_up_audit_log(action, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_step_up_audit_user ON public.step_up_audit_log(user_id, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_step_up_audit_action ON public.step_up_audit_log(action, created_at DESC); ALTER TABLE public.step_up_audit_log ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Devs can view all audit logs" ON public.step_up_audit_log; CREATE POLICY "Devs can view all audit logs" ON public.step_up_audit_log FOR SELECT USING (public.is_dev(auth.uid())); +DROP POLICY IF EXISTS "Users can view own audit logs" ON public.step_up_audit_log; CREATE POLICY "Users can view own audit logs" ON public.step_up_audit_log FOR SELECT USING (auth.uid() = user_id); diff --git a/supabase/migrations/20260425203612_2b1ed5ce-0518-4d5e-9041-3511b5c8ba13.sql b/supabase/migrations/20260425203612_2b1ed5ce-0518-4d5e-9041-3511b5c8ba13.sql index 4155ffd5e..1715708c2 100644 --- a/supabase/migrations/20260425203612_2b1ed5ce-0518-4d5e-9041-3511b5c8ba13.sql +++ b/supabase/migrations/20260425203612_2b1ed5ce-0518-4d5e-9041-3511b5c8ba13.sql @@ -12,18 +12,21 @@ DROP POLICY IF EXISTS "Admins delete mcp_api_keys" ON public.mcp_api_keys; -- 3. Policies explícitas com a nova hierarquia -- Leitura: apenas dev e supervisor (vendedor NUNCA vê chaves) +DROP POLICY IF EXISTS "Devs and supervisors read mcp_api_keys" ON public.mcp_api_keys; CREATE POLICY "Devs and supervisors read mcp_api_keys" ON public.mcp_api_keys FOR SELECT TO authenticated USING (public.is_supervisor_or_above(auth.uid())); -- Insert: SEMPRE negado para clientes JWT (apenas service_role via edge function) +DROP POLICY IF EXISTS "No direct insert via JWT" ON public.mcp_api_keys; CREATE POLICY "No direct insert via JWT" ON public.mcp_api_keys FOR INSERT TO authenticated WITH CHECK (false); -- Update: SEMPRE negado para clientes JWT (apenas service_role via edge function) +DROP POLICY IF EXISTS "No direct update via JWT" ON public.mcp_api_keys; CREATE POLICY "No direct update via JWT" ON public.mcp_api_keys FOR UPDATE TO authenticated @@ -31,6 +34,7 @@ CREATE POLICY "No direct update via JWT" WITH CHECK (false); -- Delete: SEMPRE negado para clientes JWT (apenas service_role via edge function) +DROP POLICY IF EXISTS "No direct delete via JWT" ON public.mcp_api_keys; CREATE POLICY "No direct delete via JWT" ON public.mcp_api_keys FOR DELETE TO authenticated diff --git a/supabase/migrations/20260425210505_1fc8fe0f-79ba-412d-81c3-cb95f3cec231.sql b/supabase/migrations/20260425210505_1fc8fe0f-79ba-412d-81c3-cb95f3cec231.sql index 19376c086..3d8e03f24 100644 --- a/supabase/migrations/20260425210505_1fc8fe0f-79ba-412d-81c3-cb95f3cec231.sql +++ b/supabase/migrations/20260425210505_1fc8fe0f-79ba-412d-81c3-cb95f3cec231.sql @@ -13,6 +13,7 @@ DROP POLICY IF EXISTS "Admins delete connection_test_history" ON public.connecti CREATE POLICY "Devs read connection_test_history" ON public.connection_test_history FOR SELECT TO authenticated USING (public.is_dev(auth.uid())); +DROP POLICY IF EXISTS "Devs delete connection_test_history" ON public.connection_test_history; CREATE POLICY "Devs delete connection_test_history" ON public.connection_test_history FOR DELETE TO authenticated USING (public.is_dev(auth.uid())); @@ -50,6 +51,7 @@ DROP POLICY IF EXISTS "Admins can delete telemetry" ON public.query_telemetry; CREATE POLICY "Devs can read telemetry" ON public.query_telemetry FOR SELECT TO authenticated USING (public.is_dev(auth.uid())); +DROP POLICY IF EXISTS "Devs can delete telemetry" ON public.query_telemetry; CREATE POLICY "Devs can delete telemetry" ON public.query_telemetry FOR DELETE TO authenticated USING (public.is_dev(auth.uid())); diff --git a/supabase/migrations/20260426122751_c0bc82e4-dc78-47da-8da4-74691b181d3d.sql b/supabase/migrations/20260426122751_c0bc82e4-dc78-47da-8da4-74691b181d3d.sql index 2c981dd98..6b698c776 100644 --- a/supabase/migrations/20260426122751_c0bc82e4-dc78-47da-8da4-74691b181d3d.sql +++ b/supabase/migrations/20260426122751_c0bc82e4-dc78-47da-8da4-74691b181d3d.sql @@ -17,6 +17,7 @@ CREATE INDEX IF NOT EXISTS idx_mcp_auto_rev_user ON public.mcp_key_auto_revocati ALTER TABLE public.mcp_key_auto_revocations ENABLE ROW LEVEL SECURITY; -- Apenas devs podem ver +DROP POLICY IF EXISTS "Devs can view auto-revocations" ON public.mcp_key_auto_revocations; CREATE POLICY "Devs can view auto-revocations" ON public.mcp_key_auto_revocations FOR SELECT diff --git a/supabase/migrations/20260426124539_2b89356b-7d6f-43eb-823e-5aadd4529460.sql b/supabase/migrations/20260426124539_2b89356b-7d6f-43eb-823e-5aadd4529460.sql index 7fd919bce..47ad9f0af 100644 --- a/supabase/migrations/20260426124539_2b89356b-7d6f-43eb-823e-5aadd4529460.sql +++ b/supabase/migrations/20260426124539_2b89356b-7d6f-43eb-823e-5aadd4529460.sql @@ -25,6 +25,7 @@ CREATE POLICY "Admins manage user_roles" USING (public.is_admin_strict(auth.uid())) WITH CHECK (public.is_admin_strict(auth.uid())); +DROP POLICY IF EXISTS "Supervisors can read user_roles" ON public.user_roles; CREATE POLICY "Supervisors can read user_roles" ON public.user_roles FOR SELECT @@ -41,6 +42,7 @@ CREATE POLICY "Admins manage mcp_full_grantors" USING (public.is_admin_strict(auth.uid())) WITH CHECK (public.is_admin_strict(auth.uid())); +DROP POLICY IF EXISTS "Devs read mcp_full_grantors" ON public.mcp_full_grantors; CREATE POLICY "Devs read mcp_full_grantors" ON public.mcp_full_grantors FOR SELECT diff --git a/supabase/migrations/20260426125603_b96b3daf-08f4-4edd-bf2f-835a6c673dbf.sql b/supabase/migrations/20260426125603_b96b3daf-08f4-4edd-bf2f-835a6c673dbf.sql index b7b76ef12..b46610168 100644 --- a/supabase/migrations/20260426125603_b96b3daf-08f4-4edd-bf2f-835a6c673dbf.sql +++ b/supabase/migrations/20260426125603_b96b3daf-08f4-4edd-bf2f-835a6c673dbf.sql @@ -67,12 +67,14 @@ FOR SELECT TO authenticated USING ( OR seller_id = auth.uid() ); +DROP POLICY IF EXISTS "quotes_insert_scope" ON public.quotes; CREATE POLICY "quotes_insert_scope" ON public.quotes FOR INSERT TO authenticated WITH CHECK ( public.can_view_all_sales() OR seller_id = auth.uid() ); +DROP POLICY IF EXISTS "quotes_update_scope" ON public.quotes; CREATE POLICY "quotes_update_scope" ON public.quotes FOR UPDATE TO authenticated USING ( @@ -90,6 +92,7 @@ WITH CHECK ( OR seller_id = auth.uid() ); +DROP POLICY IF EXISTS "quotes_delete_scope" ON public.quotes; CREATE POLICY "quotes_delete_scope" ON public.quotes FOR DELETE TO authenticated USING ( public.can_view_all_sales() @@ -111,12 +114,14 @@ FOR SELECT TO authenticated USING ( OR seller_id = auth.uid() ); +DROP POLICY IF EXISTS "orders_insert_scope" ON public.orders; CREATE POLICY "orders_insert_scope" ON public.orders FOR INSERT TO authenticated WITH CHECK ( public.can_view_all_sales() OR seller_id = auth.uid() ); +DROP POLICY IF EXISTS "orders_update_scope" ON public.orders; CREATE POLICY "orders_update_scope" ON public.orders FOR UPDATE TO authenticated USING ( @@ -134,6 +139,7 @@ WITH CHECK ( OR seller_id = auth.uid() ); +DROP POLICY IF EXISTS "orders_delete_scope" ON public.orders; CREATE POLICY "orders_delete_scope" ON public.orders FOR DELETE TO authenticated USING ( public.can_view_all_sales() @@ -161,6 +167,7 @@ FOR SELECT TO authenticated USING ( ) ); +DROP POLICY IF EXISTS "order_items_insert_scope" ON public.order_items; CREATE POLICY "order_items_insert_scope" ON public.order_items FOR INSERT TO authenticated WITH CHECK ( public.can_view_all_sales() @@ -171,6 +178,7 @@ FOR INSERT TO authenticated WITH CHECK ( ) ); +DROP POLICY IF EXISTS "order_items_update_scope" ON public.order_items; CREATE POLICY "order_items_update_scope" ON public.order_items FOR UPDATE TO authenticated USING ( @@ -196,6 +204,7 @@ WITH CHECK ( ) ); +DROP POLICY IF EXISTS "order_items_delete_scope" ON public.order_items; CREATE POLICY "order_items_delete_scope" ON public.order_items FOR DELETE TO authenticated USING ( public.can_view_all_sales() @@ -215,14 +224,17 @@ CREATE POLICY "qtemplates_select_scope" ON public.quote_templates FOR SELECT TO authenticated USING ( public.can_view_all_sales() OR seller_id = auth.uid() ); +DROP POLICY IF EXISTS "qtemplates_insert_scope" ON public.quote_templates; CREATE POLICY "qtemplates_insert_scope" ON public.quote_templates FOR INSERT TO authenticated WITH CHECK ( public.can_view_all_sales() OR seller_id = auth.uid() ); +DROP POLICY IF EXISTS "qtemplates_update_scope" ON public.quote_templates; CREATE POLICY "qtemplates_update_scope" ON public.quote_templates FOR UPDATE TO authenticated USING (public.can_view_all_sales() OR seller_id = auth.uid()) WITH CHECK (public.can_view_all_sales() OR seller_id = auth.uid()); +DROP POLICY IF EXISTS "qtemplates_delete_scope" ON public.quote_templates; CREATE POLICY "qtemplates_delete_scope" ON public.quote_templates FOR DELETE TO authenticated USING ( public.can_view_all_sales() OR seller_id = auth.uid() @@ -240,14 +252,17 @@ CREATE POLICY "qatokens_select_scope" ON public.quote_approval_tokens FOR SELECT TO authenticated USING ( public.can_view_all_sales() OR seller_id = auth.uid() ); +DROP POLICY IF EXISTS "qatokens_insert_scope" ON public.quote_approval_tokens; CREATE POLICY "qatokens_insert_scope" ON public.quote_approval_tokens FOR INSERT TO authenticated WITH CHECK ( public.can_view_all_sales() OR seller_id = auth.uid() ); +DROP POLICY IF EXISTS "qatokens_update_scope" ON public.quote_approval_tokens; CREATE POLICY "qatokens_update_scope" ON public.quote_approval_tokens FOR UPDATE TO authenticated USING (public.can_view_all_sales() OR seller_id = auth.uid()) WITH CHECK (public.can_view_all_sales() OR seller_id = auth.uid()); +DROP POLICY IF EXISTS "qatokens_delete_scope" ON public.quote_approval_tokens; CREATE POLICY "qatokens_delete_scope" ON public.quote_approval_tokens FOR DELETE TO authenticated USING ( public.can_view_all_sales() OR seller_id = auth.uid() @@ -269,10 +284,12 @@ FOR SELECT TO authenticated USING ( OR public.has_role(auth.uid(),'supervisor'::public.app_role) OR seller_id = auth.uid() ); +DROP POLICY IF EXISTS "dar_insert_scope" ON public.discount_approval_requests; CREATE POLICY "dar_insert_scope" ON public.discount_approval_requests FOR INSERT TO authenticated WITH CHECK ( seller_id = auth.uid() OR public.can_view_all_sales() ); +DROP POLICY IF EXISTS "dar_update_scope" ON public.discount_approval_requests; CREATE POLICY "dar_update_scope" ON public.discount_approval_requests FOR UPDATE TO authenticated USING ( @@ -283,6 +300,7 @@ WITH CHECK ( public.can_view_all_sales() OR public.has_role(auth.uid(),'supervisor'::public.app_role) ); +DROP POLICY IF EXISTS "dar_delete_scope" ON public.discount_approval_requests; CREATE POLICY "dar_delete_scope" ON public.discount_approval_requests FOR DELETE TO authenticated USING ( public.can_view_all_sales() diff --git a/supabase/migrations/20260426131442_16ccbfea-d95c-4715-9650-8fa00b4709e7.sql b/supabase/migrations/20260426131442_16ccbfea-d95c-4715-9650-8fa00b4709e7.sql index 3e764144d..b95bb4351 100644 --- a/supabase/migrations/20260426131442_16ccbfea-d95c-4715-9650-8fa00b4709e7.sql +++ b/supabase/migrations/20260426131442_16ccbfea-d95c-4715-9650-8fa00b4709e7.sql @@ -1,5 +1,5 @@ -- Tabela de log de tentativas negadas por RLS (defense-in-depth observability) -CREATE TABLE public.rls_denial_log ( +CREATE TABLE IF NOT EXISTS public.rls_denial_log ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL, user_email TEXT, @@ -18,28 +18,32 @@ CREATE TABLE public.rls_denial_log ( created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); -CREATE INDEX idx_rls_denial_user ON public.rls_denial_log (user_id, created_at DESC); -CREATE INDEX idx_rls_denial_table ON public.rls_denial_log (table_name, created_at DESC); -CREATE INDEX idx_rls_denial_created ON public.rls_denial_log (created_at DESC); +CREATE INDEX IF NOT EXISTS idx_rls_denial_user ON public.rls_denial_log (user_id, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_rls_denial_table ON public.rls_denial_log (table_name, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_rls_denial_created ON public.rls_denial_log (created_at DESC); ALTER TABLE public.rls_denial_log ENABLE ROW LEVEL SECURITY; -- Apenas admin/supervisor leem; ninguém faz INSERT direto (só via RPC security definer) +DROP POLICY IF EXISTS "Admins read rls denials" ON public.rls_denial_log; CREATE POLICY "Admins read rls denials" ON public.rls_denial_log FOR SELECT TO authenticated USING (is_supervisor_or_above(auth.uid())); +DROP POLICY IF EXISTS "Block direct insert" ON public.rls_denial_log; CREATE POLICY "Block direct insert" ON public.rls_denial_log FOR INSERT TO authenticated WITH CHECK (false); +DROP POLICY IF EXISTS "Block direct update" ON public.rls_denial_log; CREATE POLICY "Block direct update" ON public.rls_denial_log FOR UPDATE TO authenticated USING (false); +DROP POLICY IF EXISTS "Admins can delete old logs" ON public.rls_denial_log; CREATE POLICY "Admins can delete old logs" ON public.rls_denial_log FOR DELETE TO authenticated diff --git a/supabase/migrations/20260426134439_250c2db7-3e90-499a-a4b2-327964b65a55.sql b/supabase/migrations/20260426134439_250c2db7-3e90-499a-a4b2-327964b65a55.sql index eb63c88d1..a6f9531d8 100644 --- a/supabase/migrations/20260426134439_250c2db7-3e90-499a-a4b2-327964b65a55.sql +++ b/supabase/migrations/20260426134439_250c2db7-3e90-499a-a4b2-327964b65a55.sql @@ -24,6 +24,7 @@ USING ( ) ); +DROP POLICY IF EXISTS "quote_items_insert_scope" ON public.quote_items; CREATE POLICY "quote_items_insert_scope" ON public.quote_items FOR INSERT @@ -36,6 +37,7 @@ WITH CHECK ( ) ); +DROP POLICY IF EXISTS "quote_items_update_scope" ON public.quote_items; CREATE POLICY "quote_items_update_scope" ON public.quote_items FOR UPDATE @@ -68,6 +70,7 @@ WITH CHECK ( ) ); +DROP POLICY IF EXISTS "quote_items_delete_scope" ON public.quote_items; CREATE POLICY "quote_items_delete_scope" ON public.quote_items FOR DELETE @@ -103,6 +106,7 @@ USING ( ) ); +DROP POLICY IF EXISTS "quote_item_personalizations_insert_scope" ON public.quote_item_personalizations; CREATE POLICY "quote_item_personalizations_insert_scope" ON public.quote_item_personalizations FOR INSERT @@ -117,6 +121,7 @@ WITH CHECK ( ) ); +DROP POLICY IF EXISTS "quote_item_personalizations_update_scope" ON public.quote_item_personalizations; CREATE POLICY "quote_item_personalizations_update_scope" ON public.quote_item_personalizations FOR UPDATE @@ -153,6 +158,7 @@ WITH CHECK ( ) ); +DROP POLICY IF EXISTS "quote_item_personalizations_delete_scope" ON public.quote_item_personalizations; CREATE POLICY "quote_item_personalizations_delete_scope" ON public.quote_item_personalizations FOR DELETE diff --git a/supabase/migrations/20260426134707_1f690442-88ff-4f4f-bbaa-67265a490088.sql b/supabase/migrations/20260426134707_1f690442-88ff-4f4f-bbaa-67265a490088.sql index d99a9f65b..df9dcd6e2 100644 --- a/supabase/migrations/20260426134707_1f690442-88ff-4f4f-bbaa-67265a490088.sql +++ b/supabase/migrations/20260426134707_1f690442-88ff-4f4f-bbaa-67265a490088.sql @@ -16,14 +16,17 @@ CREATE INDEX IF NOT EXISTS idx_ownership_audit_reports_generated_at ALTER TABLE public.ownership_audit_reports ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "ownership_audit_reports_admin_select" ON public.ownership_audit_reports; CREATE POLICY "ownership_audit_reports_admin_select" ON public.ownership_audit_reports FOR SELECT USING (has_role(auth.uid(), 'admin'::app_role) OR has_role(auth.uid(), 'dev'::app_role)); +DROP POLICY IF EXISTS "ownership_audit_reports_admin_insert" ON public.ownership_audit_reports; CREATE POLICY "ownership_audit_reports_admin_insert" ON public.ownership_audit_reports FOR INSERT WITH CHECK (has_role(auth.uid(), 'admin'::app_role) OR has_role(auth.uid(), 'dev'::app_role)); +DROP POLICY IF EXISTS "ownership_audit_reports_admin_delete" ON public.ownership_audit_reports; CREATE POLICY "ownership_audit_reports_admin_delete" ON public.ownership_audit_reports FOR DELETE USING (has_role(auth.uid(), 'admin'::app_role) OR has_role(auth.uid(), 'dev'::app_role)); diff --git a/supabase/migrations/20260426143226_aggressive_autovacuum_color_equivalences.sql b/supabase/migrations/20260426143226_aggressive_autovacuum_color_equivalences.sql new file mode 100644 index 000000000..5d07a4533 --- /dev/null +++ b/supabase/migrations/20260426143226_aggressive_autovacuum_color_equivalences.sql @@ -0,0 +1,2 @@ +-- Migration 20260426143226 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260426145642_948756c0-6c4a-4be4-8757-9533bd4e291a.sql b/supabase/migrations/20260426145642_948756c0-6c4a-4be4-8757-9533bd4e291a.sql index 182b8980a..31a8cdb1a 100644 --- a/supabase/migrations/20260426145642_948756c0-6c4a-4be4-8757-9533bd4e291a.sql +++ b/supabase/migrations/20260426145642_948756c0-6c4a-4be4-8757-9533bd4e291a.sql @@ -1,5 +1,5 @@ -- Tabela de logs de reparo (auditoria completa) -CREATE TABLE public.ownership_repair_logs ( +CREATE TABLE IF NOT EXISTS public.ownership_repair_logs ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), report_id uuid REFERENCES public.ownership_audit_reports(id) ON DELETE SET NULL, table_name text NOT NULL, @@ -15,11 +15,12 @@ CREATE TABLE public.ownership_repair_logs ( created_at timestamptz NOT NULL DEFAULT now() ); -CREATE INDEX idx_ownership_repair_logs_report ON public.ownership_repair_logs(report_id); -CREATE INDEX idx_ownership_repair_logs_created_at ON public.ownership_repair_logs(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_ownership_repair_logs_report ON public.ownership_repair_logs(report_id); +CREATE INDEX IF NOT EXISTS idx_ownership_repair_logs_created_at ON public.ownership_repair_logs(created_at DESC); ALTER TABLE public.ownership_repair_logs ENABLE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS "Admins/devs read repair logs" ON public.ownership_repair_logs; CREATE POLICY "Admins/devs read repair logs" ON public.ownership_repair_logs FOR SELECT TO authenticated diff --git a/supabase/migrations/20260427122230_9848331f-fc90-4721-bf9e-caf78ba9cbfd.sql b/supabase/migrations/20260427122230_9848331f-fc90-4721-bf9e-caf78ba9cbfd.sql index cab7bcd56..aa73328da 100644 --- a/supabase/migrations/20260427122230_9848331f-fc90-4721-bf9e-caf78ba9cbfd.sql +++ b/supabase/migrations/20260427122230_9848331f-fc90-4721-bf9e-caf78ba9cbfd.sql @@ -36,24 +36,32 @@ CREATE INDEX IF NOT EXISTS idx_webhook_metrics_request_id ALTER TABLE public.webhook_delivery_metrics ENABLE ROW LEVEL SECURITY; -- Apenas dev/supervisor pode inspecionar; service_role escreve. Anon/auth bloqueados. +DROP POLICY IF EXISTS "deny anon select webhook_metrics" ON public.webhook_delivery_metrics; CREATE POLICY "deny anon select webhook_metrics" ON public.webhook_delivery_metrics FOR SELECT TO anon USING (false); +DROP POLICY IF EXISTS "deny anon insert webhook_metrics" ON public.webhook_delivery_metrics; CREATE POLICY "deny anon insert webhook_metrics" ON public.webhook_delivery_metrics FOR INSERT TO anon WITH CHECK (false); +DROP POLICY IF EXISTS "deny anon update webhook_metrics" ON public.webhook_delivery_metrics; CREATE POLICY "deny anon update webhook_metrics" ON public.webhook_delivery_metrics FOR UPDATE TO anon USING (false); +DROP POLICY IF EXISTS "deny anon delete webhook_metrics" ON public.webhook_delivery_metrics; CREATE POLICY "deny anon delete webhook_metrics" ON public.webhook_delivery_metrics FOR DELETE TO anon USING (false); +DROP POLICY IF EXISTS "supervisors view webhook_metrics" ON public.webhook_delivery_metrics; CREATE POLICY "supervisors view webhook_metrics" ON public.webhook_delivery_metrics FOR SELECT TO authenticated USING (public.has_role(auth.uid(), 'dev'::app_role) OR public.has_role(auth.uid(), 'supervisor'::app_role)); +DROP POLICY IF EXISTS "deny auth insert webhook_metrics" ON public.webhook_delivery_metrics; CREATE POLICY "deny auth insert webhook_metrics" ON public.webhook_delivery_metrics FOR INSERT TO authenticated WITH CHECK (false); +DROP POLICY IF EXISTS "deny auth update webhook_metrics" ON public.webhook_delivery_metrics; CREATE POLICY "deny auth update webhook_metrics" ON public.webhook_delivery_metrics FOR UPDATE TO authenticated USING (false); +DROP POLICY IF EXISTS "deny auth delete webhook_metrics" ON public.webhook_delivery_metrics; CREATE POLICY "deny auth delete webhook_metrics" ON public.webhook_delivery_metrics FOR DELETE TO authenticated USING (false); diff --git a/supabase/migrations/20260427211500_8777082c-1c62-4d74-9cb7-03070c975d7f.sql b/supabase/migrations/20260427211500_8777082c-1c62-4d74-9cb7-03070c975d7f.sql index 76383737c..01d0c2f18 100644 --- a/supabase/migrations/20260427211500_8777082c-1c62-4d74-9cb7-03070c975d7f.sql +++ b/supabase/migrations/20260427211500_8777082c-1c62-4d74-9cb7-03070c975d7f.sql @@ -18,16 +18,19 @@ WHERE id = 'supplier-logos'; -- ... -- 3. Políticas para 'personalization-images' (Áreas de gravação e referências) +DROP POLICY IF EXISTS "Authenticated users can upload personalization images" ON storage.objects; CREATE POLICY "Authenticated users can upload personalization images" ON storage.objects FOR INSERT TO authenticated WITH CHECK (bucket_id = 'personalization-images'); +DROP POLICY IF EXISTS "Authenticated users can view personalization images" ON storage.objects; CREATE POLICY "Authenticated users can view personalization images" ON storage.objects FOR SELECT TO authenticated USING (bucket_id = 'personalization-images'); +DROP POLICY IF EXISTS "Admins can delete personalization images" ON storage.objects; CREATE POLICY "Admins can delete personalization images" ON storage.objects FOR DELETE TO authenticated @@ -35,6 +38,7 @@ USING (bucket_id = 'personalization-images' AND is_supervisor_or_above(auth.uid( -- 4. Políticas para 'mockup-art-files' (Arquivos de arte enviados por clientes/vendedores) -- Padrão: path/id_usuario/arquivo.ext +DROP POLICY IF EXISTS "Users can upload their own art files" ON storage.objects; CREATE POLICY "Users can upload their own art files" ON storage.objects FOR INSERT TO authenticated @@ -43,6 +47,7 @@ WITH CHECK ( AND (storage.foldername(name))[1] = auth.uid()::text ); +DROP POLICY IF EXISTS "Users can view their own or shared art files" ON storage.objects; CREATE POLICY "Users can view their own or shared art files" ON storage.objects FOR SELECT TO authenticated @@ -54,6 +59,7 @@ USING ( ) ); +DROP POLICY IF EXISTS "Users can delete their own art files" ON storage.objects; CREATE POLICY "Users can delete their own art files" ON storage.objects FOR DELETE TO authenticated @@ -63,11 +69,13 @@ USING ( ); -- 5. Políticas para 'supplier-logos' (Apenas administradores/devs) +DROP POLICY IF EXISTS "Public can view supplier logos" ON storage.objects; CREATE POLICY "Public can view supplier logos" ON storage.objects FOR SELECT TO public USING (bucket_id = 'supplier-logos'); +DROP POLICY IF EXISTS "Only admins can manage supplier logos" ON storage.objects; CREATE POLICY "Only admins can manage supplier logos" ON storage.objects FOR ALL TO authenticated diff --git a/supabase/migrations/20260427212820_2fca7f6f-1fce-428a-b135-236d6f22135b.sql b/supabase/migrations/20260427212820_2fca7f6f-1fce-428a-b135-236d6f22135b.sql index b85d8eca2..0a407abcd 100644 --- a/supabase/migrations/20260427212820_2fca7f6f-1fce-428a-b135-236d6f22135b.sql +++ b/supabase/migrations/20260427212820_2fca7f6f-1fce-428a-b135-236d6f22135b.sql @@ -8,17 +8,20 @@ UPDATE storage.buckets SET public = false WHERE id = 'personalization-images'; -- Habilitar RLS (Storage utiliza RLS na tabela storage.objects) -- Políticas para 'personalization-images' +DROP POLICY IF EXISTS "Acesso de leitura para usuários autenticados em personalization-images" ON storage.objects; CREATE POLICY "Acesso de leitura para usuários autenticados em personalization-images" ON storage.objects FOR SELECT TO authenticated USING (bucket_id = 'personalization-images'); +DROP POLICY IF EXISTS "Acesso de inserção para usuários autenticados em personalization-images" ON storage.objects; CREATE POLICY "Acesso de inserção para usuários autenticados em personalization-images" ON storage.objects FOR INSERT TO authenticated WITH CHECK (bucket_id = 'personalization-images'); -- Políticas para 'quarantine' (Apenas leitura/gestão por admins ou sistema) +DROP POLICY IF EXISTS "Acesso restrito ao bucket de quarentena" ON storage.objects; CREATE POLICY "Acesso restrito ao bucket de quarentena" ON storage.objects FOR ALL TO authenticated diff --git a/supabase/migrations/20260427213016_bce59025-f18c-4ad2-a056-23de8ca5d9a8.sql b/supabase/migrations/20260427213016_bce59025-f18c-4ad2-a056-23de8ca5d9a8.sql index 81d983646..7731d4dc9 100644 --- a/supabase/migrations/20260427213016_bce59025-f18c-4ad2-a056-23de8ca5d9a8.sql +++ b/supabase/migrations/20260427213016_bce59025-f18c-4ad2-a056-23de8ca5d9a8.sql @@ -18,6 +18,7 @@ CREATE INDEX IF NOT EXISTS idx_file_scan_logs_hash ON public.file_scan_logs(hash ALTER TABLE public.file_scan_logs ENABLE ROW LEVEL SECURITY; -- Políticas de segurança +DROP POLICY IF EXISTS "Apenas administradores podem visualizar logs de scan" ON public.file_scan_logs; CREATE POLICY "Apenas administradores podem visualizar logs de scan" ON public.file_scan_logs FOR SELECT TO authenticated diff --git a/supabase/migrations/20260427213832_b99669ff-b393-4329-b140-0acca3b894b3.sql b/supabase/migrations/20260427213832_b99669ff-b393-4329-b140-0acca3b894b3.sql index f81c9f2ca..713cbcaa1 100644 --- a/supabase/migrations/20260427213832_b99669ff-b393-4329-b140-0acca3b894b3.sql +++ b/supabase/migrations/20260427213832_b99669ff-b393-4329-b140-0acca3b894b3.sql @@ -7,6 +7,7 @@ DROP POLICY IF EXISTS "Sistema pode gerenciar quarentena" ON storage.objects; DROP POLICY IF EXISTS "Admins podem visualizar quarentena" ON storage.objects; -- Política 1: O sistema (service_role) tem acesso total para mover arquivos para cá +DROP POLICY IF EXISTS "Sistema pode gerenciar quarentena" ON storage.objects; CREATE POLICY "Sistema pode gerenciar quarentena" ON storage.objects FOR ALL TO service_role @@ -14,6 +15,7 @@ USING (bucket_id = 'quarantine') WITH CHECK (bucket_id = 'quarantine'); -- Política 2: Administradores podem visualizar os arquivos para auditoria +DROP POLICY IF EXISTS "Admins podem visualizar quarentena" ON storage.objects; CREATE POLICY "Admins podem visualizar quarentena" ON storage.objects FOR SELECT TO authenticated diff --git a/supabase/migrations/20260427213920_ba27ed4a-7f07-428b-9570-3d9fd5f4b14c.sql b/supabase/migrations/20260427213920_ba27ed4a-7f07-428b-9570-3d9fd5f4b14c.sql index d3ce870d8..a9ef02d1d 100644 --- a/supabase/migrations/20260427213920_ba27ed4a-7f07-428b-9570-3d9fd5f4b14c.sql +++ b/supabase/migrations/20260427213920_ba27ed4a-7f07-428b-9570-3d9fd5f4b14c.sql @@ -2,7 +2,7 @@ UPDATE storage.buckets SET public = false; -- 2. Remover explicitamente políticas que possam ser muito permissivas para o bucket de quarentena --- Como não podemos deletar diretamente de storage.policies, usamos DROP POLICY nominalmente +-- Como não podemos deletar diretamente de storage.policies, usamos DROP POLICY IF EXISTS nominalmente DROP POLICY IF EXISTS "Acesso restrito ao bucket de quarentena" ON storage.objects; DROP POLICY IF EXISTS "Public access to quarantine" ON storage.objects; DROP POLICY IF EXISTS "Authenticated read quarantine" ON storage.objects; diff --git a/supabase/migrations/20260429140300_kit_component_types_add_is_personalizable_by_default.sql b/supabase/migrations/20260429140300_kit_component_types_add_is_personalizable_by_default.sql new file mode 100644 index 000000000..0449906b4 --- /dev/null +++ b/supabase/migrations/20260429140300_kit_component_types_add_is_personalizable_by_default.sql @@ -0,0 +1,2 @@ +-- Migration 20260429140300 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260429140944_kit_component_inherit_personalization_trigger.sql b/supabase/migrations/20260429140944_kit_component_inherit_personalization_trigger.sql new file mode 100644 index 000000000..7160fe5de --- /dev/null +++ b/supabase/migrations/20260429140944_kit_component_inherit_personalization_trigger.sql @@ -0,0 +1,2 @@ +-- Migration 20260429140944 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260429152520_gap10_normalizar_eixos_kit_print_areas.sql b/supabase/migrations/20260429152520_gap10_normalizar_eixos_kit_print_areas.sql new file mode 100644 index 000000000..1df4fa670 --- /dev/null +++ b/supabase/migrations/20260429152520_gap10_normalizar_eixos_kit_print_areas.sql @@ -0,0 +1,2 @@ +-- Migration 20260429152520 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260429152626_gap3_fn_simular_combo_gravacao_kit_v1.sql b/supabase/migrations/20260429152626_gap3_fn_simular_combo_gravacao_kit_v1.sql new file mode 100644 index 000000000..b11a67a47 --- /dev/null +++ b/supabase/migrations/20260429152626_gap3_fn_simular_combo_gravacao_kit_v1.sql @@ -0,0 +1,2 @@ +-- Migration 20260429152626 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260429152745_gap7_check_constraints_dimensoes_e_precos.sql b/supabase/migrations/20260429152745_gap7_check_constraints_dimensoes_e_precos.sql new file mode 100644 index 000000000..0dc23213b --- /dev/null +++ b/supabase/migrations/20260429152745_gap7_check_constraints_dimensoes_e_precos.sql @@ -0,0 +1,2 @@ +-- Migration 20260429152745 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260429152833_gap6_arredondar_dimensoes_kit_print_area.sql b/supabase/migrations/20260429152833_gap6_arredondar_dimensoes_kit_print_area.sql new file mode 100644 index 000000000..3a1ce05d2 --- /dev/null +++ b/supabase/migrations/20260429152833_gap6_arredondar_dimensoes_kit_print_area.sql @@ -0,0 +1,2 @@ +-- Migration 20260429152833 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260429155414_9983e53b-dda7-4f5e-a0e4-ae89f4c59839.sql b/supabase/migrations/20260429155414_9983e53b-dda7-4f5e-a0e4-ae89f4c59839.sql index 4a06defcb..9b5826e9c 100644 --- a/supabase/migrations/20260429155414_9983e53b-dda7-4f5e-a0e4-ae89f4c59839.sql +++ b/supabase/migrations/20260429155414_9983e53b-dda7-4f5e-a0e4-ae89f4c59839.sql @@ -11,6 +11,7 @@ DROP POLICY IF EXISTS "Admins can view all roles" ON public.user_roles; DROP POLICY IF EXISTS "Admins can manage roles" ON public.user_roles; -- Leitura: o próprio usuário sempre vê suas roles +DROP POLICY IF EXISTS "Users read own roles" ON public.user_roles; CREATE POLICY "Users read own roles" ON public.user_roles FOR SELECT @@ -18,6 +19,7 @@ CREATE POLICY "Users read own roles" USING (auth.uid() = user_id); -- Leitura ampla: supervisor/dev veem todas +DROP POLICY IF EXISTS "Supervisors read all roles" ON public.user_roles; CREATE POLICY "Supervisors read all roles" ON public.user_roles FOR SELECT @@ -25,12 +27,14 @@ CREATE POLICY "Supervisors read all roles" USING (public.is_supervisor_or_above(auth.uid())); -- Escrita estrita: apenas admin estrito (dev) pode INSERIR/ALTERAR/DELETAR papéis +DROP POLICY IF EXISTS "Admins insert roles" ON public.user_roles; CREATE POLICY "Admins insert roles" ON public.user_roles FOR INSERT TO authenticated WITH CHECK (public.is_admin_strict(auth.uid())); +DROP POLICY IF EXISTS "Admins update roles" ON public.user_roles; CREATE POLICY "Admins update roles" ON public.user_roles FOR UPDATE @@ -38,6 +42,7 @@ CREATE POLICY "Admins update roles" USING (public.is_admin_strict(auth.uid())) WITH CHECK (public.is_admin_strict(auth.uid())); +DROP POLICY IF EXISTS "Admins delete roles" ON public.user_roles; CREATE POLICY "Admins delete roles" ON public.user_roles FOR DELETE diff --git a/supabase/migrations/20260429155753_gap_dim_zero_negativa_rejeicao.sql b/supabase/migrations/20260429155753_gap_dim_zero_negativa_rejeicao.sql new file mode 100644 index 000000000..8cae060ef --- /dev/null +++ b/supabase/migrations/20260429155753_gap_dim_zero_negativa_rejeicao.sql @@ -0,0 +1,2 @@ +-- Migration 20260429155753 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260429163441_align_integration_credentials_rls_with_dev.sql b/supabase/migrations/20260429163441_align_integration_credentials_rls_with_dev.sql index bab5a286e..905549f6b 100644 --- a/supabase/migrations/20260429163441_align_integration_credentials_rls_with_dev.sql +++ b/supabase/migrations/20260429163441_align_integration_credentials_rls_with_dev.sql @@ -22,6 +22,7 @@ DROP POLICY IF EXISTS "Admins can update integration credentials" DROP POLICY IF EXISTS "Admins can delete integration credentials" ON public.integration_credentials; +DROP POLICY IF EXISTS "Admins and devs can view integration credentials" ON public.integration_credentials; CREATE POLICY "Admins and devs can view integration credentials" ON public.integration_credentials FOR SELECT @@ -31,6 +32,7 @@ CREATE POLICY "Admins and devs can view integration credentials" OR public.has_role(auth.uid(), 'dev'::public.app_role) ); +DROP POLICY IF EXISTS "Admins and devs can insert integration credentials" ON public.integration_credentials; CREATE POLICY "Admins and devs can insert integration credentials" ON public.integration_credentials FOR INSERT @@ -40,6 +42,7 @@ CREATE POLICY "Admins and devs can insert integration credentials" OR public.has_role(auth.uid(), 'dev'::public.app_role) ); +DROP POLICY IF EXISTS "Admins and devs can update integration credentials" ON public.integration_credentials; CREATE POLICY "Admins and devs can update integration credentials" ON public.integration_credentials FOR UPDATE @@ -53,6 +56,7 @@ CREATE POLICY "Admins and devs can update integration credentials" OR public.has_role(auth.uid(), 'dev'::public.app_role) ); +DROP POLICY IF EXISTS "Admins and devs can delete integration credentials" ON public.integration_credentials; CREATE POLICY "Admins and devs can delete integration credentials" ON public.integration_credentials FOR DELETE diff --git a/supabase/migrations/20260502005139_check_contacts_table.sql b/supabase/migrations/20260502005139_check_contacts_table.sql new file mode 100644 index 000000000..3f429697a --- /dev/null +++ b/supabase/migrations/20260502005139_check_contacts_table.sql @@ -0,0 +1,2 @@ +-- Migration 20260502005139 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260503133538_3f1b974c-d44e-4eae-96da-4464022917fd.sql b/supabase/migrations/20260503133538_3f1b974c-d44e-4eae-96da-4464022917fd.sql index 15cc7f71a..026267a43 100644 --- a/supabase/migrations/20260503133538_3f1b974c-d44e-4eae-96da-4464022917fd.sql +++ b/supabase/migrations/20260503133538_3f1b974c-d44e-4eae-96da-4464022917fd.sql @@ -8,9 +8,11 @@ CREATE TABLE IF NOT EXISTS public.user_token_revocations ( ALTER TABLE public.user_token_revocations ENABLE ROW LEVEL SECURITY; -- Política: Usuários podem ver apenas sua própria revogação, supervisores veem tudo +DROP POLICY IF EXISTS "Users can view own revocation" ON public.user_token_revocations; CREATE POLICY "Users can view own revocation" ON public.user_token_revocations FOR SELECT TO authenticated USING (auth.uid() = user_id); +DROP POLICY IF EXISTS "Supervisors can manage revocations" ON public.user_token_revocations; CREATE POLICY "Supervisors can manage revocations" ON public.user_token_revocations FOR ALL TO authenticated USING (public.is_supervisor_or_above(auth.uid())); diff --git a/supabase/migrations/20260509202015_etapa1_rls_audit_log_gravacao.sql b/supabase/migrations/20260509202015_etapa1_rls_audit_log_gravacao.sql new file mode 100644 index 000000000..29e4ecead --- /dev/null +++ b/supabase/migrations/20260509202015_etapa1_rls_audit_log_gravacao.sql @@ -0,0 +1,2 @@ +-- Migration 20260509202015 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509203321_etapa3a_rbac_foundation.sql b/supabase/migrations/20260509203321_etapa3a_rbac_foundation.sql new file mode 100644 index 000000000..d703b9e1f --- /dev/null +++ b/supabase/migrations/20260509203321_etapa3a_rbac_foundation.sql @@ -0,0 +1,2 @@ +-- Migration 20260509203321 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509204340_etapa3b_rbac_infrastructure_tables.sql b/supabase/migrations/20260509204340_etapa3b_rbac_infrastructure_tables.sql new file mode 100644 index 000000000..e0d8fc9fb --- /dev/null +++ b/supabase/migrations/20260509204340_etapa3b_rbac_infrastructure_tables.sql @@ -0,0 +1,2 @@ +-- Migration 20260509204340 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509210236_etapa3c_workflow_orcamento_e_permissions.sql b/supabase/migrations/20260509210236_etapa3c_workflow_orcamento_e_permissions.sql new file mode 100644 index 000000000..3fbcc8129 --- /dev/null +++ b/supabase/migrations/20260509210236_etapa3c_workflow_orcamento_e_permissions.sql @@ -0,0 +1,2 @@ +-- Migration 20260509210236 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509223417_etapa4_kits_alinhamento_e_seguranca.sql b/supabase/migrations/20260509223417_etapa4_kits_alinhamento_e_seguranca.sql new file mode 100644 index 000000000..136b26521 --- /dev/null +++ b/supabase/migrations/20260509223417_etapa4_kits_alinhamento_e_seguranca.sql @@ -0,0 +1,2 @@ +-- Migration 20260509223417 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509224036_etapa5_mockups_ia_completo.sql b/supabase/migrations/20260509224036_etapa5_mockups_ia_completo.sql new file mode 100644 index 000000000..81330a3ef --- /dev/null +++ b/supabase/migrations/20260509224036_etapa5_mockups_ia_completo.sql @@ -0,0 +1,2 @@ +-- Migration 20260509224036 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509225204_etapa6_catalogo_favoritos_sistema_completo.sql b/supabase/migrations/20260509225204_etapa6_catalogo_favoritos_sistema_completo.sql new file mode 100644 index 000000000..2773d3305 --- /dev/null +++ b/supabase/migrations/20260509225204_etapa6_catalogo_favoritos_sistema_completo.sql @@ -0,0 +1,2 @@ +-- Migration 20260509225204 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509225212_etapa6_taxonomia_hardening_rls.sql b/supabase/migrations/20260509225212_etapa6_taxonomia_hardening_rls.sql new file mode 100644 index 000000000..e4135101c --- /dev/null +++ b/supabase/migrations/20260509225212_etapa6_taxonomia_hardening_rls.sql @@ -0,0 +1,2 @@ +-- Migration 20260509225212 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509225728_etapa7_bi_seller_scope_e_analytics_fix.sql b/supabase/migrations/20260509225728_etapa7_bi_seller_scope_e_analytics_fix.sql new file mode 100644 index 000000000..57c254cc2 --- /dev/null +++ b/supabase/migrations/20260509225728_etapa7_bi_seller_scope_e_analytics_fix.sql @@ -0,0 +1,2 @@ +-- Migration 20260509225728 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509225904_etapa7_bi_rpcs_stateless.sql b/supabase/migrations/20260509225904_etapa7_bi_rpcs_stateless.sql new file mode 100644 index 000000000..4aaa244f8 --- /dev/null +++ b/supabase/migrations/20260509225904_etapa7_bi_rpcs_stateless.sql @@ -0,0 +1,2 @@ +-- Migration 20260509225904 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509232301_etapa3d_drifts_quotes_orders_compat.sql b/supabase/migrations/20260509232301_etapa3d_drifts_quotes_orders_compat.sql new file mode 100644 index 000000000..34b6d20e5 --- /dev/null +++ b/supabase/migrations/20260509232301_etapa3d_drifts_quotes_orders_compat.sql @@ -0,0 +1,2 @@ +-- Migration 20260509232301 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509232350_etapa3d_consolidar_drifts_quotes_orders.sql b/supabase/migrations/20260509232350_etapa3d_consolidar_drifts_quotes_orders.sql new file mode 100644 index 000000000..22e44e08a --- /dev/null +++ b/supabase/migrations/20260509232350_etapa3d_consolidar_drifts_quotes_orders.sql @@ -0,0 +1,2 @@ +-- Migration 20260509232350 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509232509_etapa3d_complete_drifts_shipping_method.sql b/supabase/migrations/20260509232509_etapa3d_complete_drifts_shipping_method.sql new file mode 100644 index 000000000..8962d936f --- /dev/null +++ b/supabase/migrations/20260509232509_etapa3d_complete_drifts_shipping_method.sql @@ -0,0 +1,2 @@ +-- Migration 20260509232509 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509232650_etapa3d_check_constraints_negotiation_markup.sql b/supabase/migrations/20260509232650_etapa3d_check_constraints_negotiation_markup.sql new file mode 100644 index 000000000..4d51a9b50 --- /dev/null +++ b/supabase/migrations/20260509232650_etapa3d_check_constraints_negotiation_markup.sql @@ -0,0 +1,2 @@ +-- Migration 20260509232650 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509232813_etapa3d_consolidar_drifts_v4_final.sql b/supabase/migrations/20260509232813_etapa3d_consolidar_drifts_v4_final.sql new file mode 100644 index 000000000..de3fcbe4a --- /dev/null +++ b/supabase/migrations/20260509232813_etapa3d_consolidar_drifts_v4_final.sql @@ -0,0 +1,2 @@ +-- Migration 20260509232813 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509233305_etapa8_edge_functions_vault_credentials.sql b/supabase/migrations/20260509233305_etapa8_edge_functions_vault_credentials.sql new file mode 100644 index 000000000..cf692096c --- /dev/null +++ b/supabase/migrations/20260509233305_etapa8_edge_functions_vault_credentials.sql @@ -0,0 +1,2 @@ +-- Migration 20260509233305 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509233418_etapa8_vault_rpcs_use_official_api.sql b/supabase/migrations/20260509233418_etapa8_vault_rpcs_use_official_api.sql new file mode 100644 index 000000000..4a446576c --- /dev/null +++ b/supabase/migrations/20260509233418_etapa8_vault_rpcs_use_official_api.sql @@ -0,0 +1,2 @@ +-- Migration 20260509233418 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509235242_etapa10_a_order_items_calc_subtotal.sql b/supabase/migrations/20260509235242_etapa10_a_order_items_calc_subtotal.sql new file mode 100644 index 000000000..349782584 --- /dev/null +++ b/supabase/migrations/20260509235242_etapa10_a_order_items_calc_subtotal.sql @@ -0,0 +1,2 @@ +-- Migration 20260509235242 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509235345_etapa10_b_rls_unif_internal_tables.sql b/supabase/migrations/20260509235345_etapa10_b_rls_unif_internal_tables.sql new file mode 100644 index 000000000..315305fbe --- /dev/null +++ b/supabase/migrations/20260509235345_etapa10_b_rls_unif_internal_tables.sql @@ -0,0 +1,2 @@ +-- Migration 20260509235345 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509235640_etapa10_c_rls_insert_with_check.sql b/supabase/migrations/20260509235640_etapa10_c_rls_insert_with_check.sql new file mode 100644 index 000000000..a42d172de --- /dev/null +++ b/supabase/migrations/20260509235640_etapa10_c_rls_insert_with_check.sql @@ -0,0 +1,2 @@ +-- Migration 20260509235640 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260509235732_etapa10_d_indices_fk_criticos.sql b/supabase/migrations/20260509235732_etapa10_d_indices_fk_criticos.sql new file mode 100644 index 000000000..fa6074da6 --- /dev/null +++ b/supabase/migrations/20260509235732_etapa10_d_indices_fk_criticos.sql @@ -0,0 +1,2 @@ +-- Migration 20260509235732 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260510011734_ai_router_schema_v1.sql b/supabase/migrations/20260510011734_ai_router_schema_v1.sql new file mode 100644 index 000000000..353fdba55 --- /dev/null +++ b/supabase/migrations/20260510011734_ai_router_schema_v1.sql @@ -0,0 +1,2 @@ +-- Migration 20260510011734 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260510011909_ai_router_seed_initial_providers_models_routing.sql b/supabase/migrations/20260510011909_ai_router_seed_initial_providers_models_routing.sql new file mode 100644 index 000000000..4c9bd9be6 --- /dev/null +++ b/supabase/migrations/20260510011909_ai_router_seed_initial_providers_models_routing.sql @@ -0,0 +1,2 @@ +-- Migration 20260510011909 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260510014559_ai_usage_schema_alignment_v1.sql b/supabase/migrations/20260510014559_ai_usage_schema_alignment_v1.sql new file mode 100644 index 000000000..3586a2cf0 --- /dev/null +++ b/supabase/migrations/20260510014559_ai_usage_schema_alignment_v1.sql @@ -0,0 +1,2 @@ +-- Migration 20260510014559 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260510020321_integration_credentials_schema_alignment_v1.sql b/supabase/migrations/20260510020321_integration_credentials_schema_alignment_v1.sql new file mode 100644 index 000000000..c00e52a7b --- /dev/null +++ b/supabase/migrations/20260510020321_integration_credentials_schema_alignment_v1.sql @@ -0,0 +1,2 @@ +-- Migration 20260510020321 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260510133132_ai_router_magicup_pro_fast_routing_v1.sql b/supabase/migrations/20260510133132_ai_router_magicup_pro_fast_routing_v1.sql new file mode 100644 index 000000000..e8faeb675 --- /dev/null +++ b/supabase/migrations/20260510133132_ai_router_magicup_pro_fast_routing_v1.sql @@ -0,0 +1,2 @@ +-- Migration 20260510133132 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260510152131_cleanup_orphan_routing_generate_mockup_nanobanana.sql b/supabase/migrations/20260510152131_cleanup_orphan_routing_generate_mockup_nanobanana.sql new file mode 100644 index 000000000..caac99856 --- /dev/null +++ b/supabase/migrations/20260510152131_cleanup_orphan_routing_generate_mockup_nanobanana.sql @@ -0,0 +1,2 @@ +-- Migration 20260510152131 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260510153208_a1_1a_step1_add_enum_values.sql b/supabase/migrations/20260510153208_a1_1a_step1_add_enum_values.sql new file mode 100644 index 000000000..b49ebdd50 --- /dev/null +++ b/supabase/migrations/20260510153208_a1_1a_step1_add_enum_values.sql @@ -0,0 +1,2 @@ +-- Migration 20260510153208 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260510153241_a1_1a_step2_create_helpers.sql b/supabase/migrations/20260510153241_a1_1a_step2_create_helpers.sql new file mode 100644 index 000000000..b8c1ce6d9 --- /dev/null +++ b/supabase/migrations/20260510153241_a1_1a_step2_create_helpers.sql @@ -0,0 +1,2 @@ +-- Migration 20260510153241 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260510155042_a1_1b_backfill_user_roles_4_levels.sql b/supabase/migrations/20260510155042_a1_1b_backfill_user_roles_4_levels.sql new file mode 100644 index 000000000..ca346270f --- /dev/null +++ b/supabase/migrations/20260510155042_a1_1b_backfill_user_roles_4_levels.sql @@ -0,0 +1,2 @@ +-- Migration 20260510155042 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260510171315_a1_1c_rewrite_policies_and_helpers.sql b/supabase/migrations/20260510171315_a1_1c_rewrite_policies_and_helpers.sql new file mode 100644 index 000000000..2e0eb8d92 --- /dev/null +++ b/supabase/migrations/20260510171315_a1_1c_rewrite_policies_and_helpers.sql @@ -0,0 +1,2 @@ +-- Migration 20260510171315 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260510172138_a1_4_fix_overly_permissive_rls_audit_search.sql b/supabase/migrations/20260510172138_a1_4_fix_overly_permissive_rls_audit_search.sql new file mode 100644 index 000000000..da8bed85a --- /dev/null +++ b/supabase/migrations/20260510172138_a1_4_fix_overly_permissive_rls_audit_search.sql @@ -0,0 +1,2 @@ +-- Migration 20260510172138 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260510175847_a1_2_and_a1_6_discount_validation_and_subtotal_recalc.sql b/supabase/migrations/20260510175847_a1_2_and_a1_6_discount_validation_and_subtotal_recalc.sql new file mode 100644 index 000000000..d9d5a5702 --- /dev/null +++ b/supabase/migrations/20260510175847_a1_2_and_a1_6_discount_validation_and_subtotal_recalc.sql @@ -0,0 +1,2 @@ +-- Migration 20260510175847 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512000002_t26_consolidate_permissive_policies.sql b/supabase/migrations/20260512000002_t26_consolidate_permissive_policies.sql index 78ce27f4b..51bc6ef70 100644 --- a/supabase/migrations/20260512000002_t26_consolidate_permissive_policies.sql +++ b/supabase/migrations/20260512000002_t26_consolidate_permissive_policies.sql @@ -58,8 +58,10 @@ ALTER POLICY "Users read own file_scan_logs" ON public.file_scan_logs DROP POLICY IF EXISTS "Admins manage mcp_full_grantors" ON public.mcp_full_grantors; CREATE POLICY "mcp_full_grantors_admin_write" ON public.mcp_full_grantors FOR INSERT WITH CHECK (is_admin_strict((SELECT auth.uid()))); +DROP POLICY IF EXISTS "mcp_full_grantors_admin_update" ON public.mcp_full_grantors; CREATE POLICY "mcp_full_grantors_admin_update" ON public.mcp_full_grantors FOR UPDATE USING (is_admin_strict((SELECT auth.uid()))) WITH CHECK (is_admin_strict((SELECT auth.uid()))); +DROP POLICY IF EXISTS "mcp_full_grantors_admin_delete" ON public.mcp_full_grantors; CREATE POLICY "mcp_full_grantors_admin_delete" ON public.mcp_full_grantors FOR DELETE USING (is_admin_strict((SELECT auth.uid()))); -- Existing "Devs read mcp_full_grantors" SELECT policy kept as sole SELECT policy @@ -70,8 +72,10 @@ CREATE POLICY "mcp_full_grantors_admin_delete" ON public.mcp_full_grantors DROP POLICY IF EXISTS "mc_admin_manage" ON public.mockup_credits; CREATE POLICY "mc_admin_insert" ON public.mockup_credits FOR INSERT WITH CHECK (is_admin_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "mc_admin_update" ON public.mockup_credits; CREATE POLICY "mc_admin_update" ON public.mockup_credits FOR UPDATE USING (is_admin_or_above((SELECT auth.uid()))) WITH CHECK (is_admin_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "mc_admin_delete" ON public.mockup_credits; CREATE POLICY "mc_admin_delete" ON public.mockup_credits FOR DELETE USING (is_admin_or_above((SELECT auth.uid()))); -- mc_select_own_or_coord kept as sole SELECT policy @@ -82,8 +86,10 @@ CREATE POLICY "mc_admin_delete" ON public.mockup_credits DROP POLICY IF EXISTS "mt_admin_manage" ON public.mockup_templates; CREATE POLICY "mt_admin_insert" ON public.mockup_templates FOR INSERT WITH CHECK (is_admin_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "mt_admin_update" ON public.mockup_templates; CREATE POLICY "mt_admin_update" ON public.mockup_templates FOR UPDATE USING (is_admin_or_above((SELECT auth.uid()))) WITH CHECK (is_admin_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "mt_admin_delete" ON public.mockup_templates; CREATE POLICY "mt_admin_delete" ON public.mockup_templates FOR DELETE USING (is_admin_or_above((SELECT auth.uid()))); -- mt_select_active_or_admin kept as sole SELECT policy @@ -94,8 +100,10 @@ CREATE POLICY "mt_admin_delete" ON public.mockup_templates DROP POLICY IF EXISTS "Admins manage org members" ON public.organization_members; CREATE POLICY "org_members_admin_insert" ON public.organization_members FOR INSERT WITH CHECK (is_admin((SELECT auth.uid()))); +DROP POLICY IF EXISTS "org_members_admin_update" ON public.organization_members; CREATE POLICY "org_members_admin_update" ON public.organization_members FOR UPDATE USING (is_admin((SELECT auth.uid()))) WITH CHECK (is_admin((SELECT auth.uid()))); +DROP POLICY IF EXISTS "org_members_admin_delete" ON public.organization_members; CREATE POLICY "org_members_admin_delete" ON public.organization_members FOR DELETE USING (is_admin((SELECT auth.uid()))); -- "Members view own org memberships" SELECT kept as sole SELECT policy @@ -106,8 +114,10 @@ CREATE POLICY "org_members_admin_delete" ON public.organization_members DROP POLICY IF EXISTS "Devs manage permissions" ON public.permissions; CREATE POLICY "permissions_dev_insert" ON public.permissions FOR INSERT WITH CHECK (is_dev((SELECT auth.uid()))); +DROP POLICY IF EXISTS "permissions_dev_update" ON public.permissions; CREATE POLICY "permissions_dev_update" ON public.permissions FOR UPDATE USING (is_dev((SELECT auth.uid()))) WITH CHECK (is_dev((SELECT auth.uid()))); +DROP POLICY IF EXISTS "permissions_dev_delete" ON public.permissions; CREATE POLICY "permissions_dev_delete" ON public.permissions FOR DELETE USING (is_dev((SELECT auth.uid()))); -- "Authenticated read permissions" SELECT kept as sole SELECT policy @@ -118,8 +128,10 @@ CREATE POLICY "permissions_dev_delete" ON public.permissions DROP POLICY IF EXISTS "pt_admin_manage" ON public.personalization_techniques; CREATE POLICY "pt_admin_insert" ON public.personalization_techniques FOR INSERT WITH CHECK (is_admin_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "pt_admin_update" ON public.personalization_techniques; CREATE POLICY "pt_admin_update" ON public.personalization_techniques FOR UPDATE USING (is_admin_or_above((SELECT auth.uid()))) WITH CHECK (is_admin_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "pt_admin_delete" ON public.personalization_techniques; CREATE POLICY "pt_admin_delete" ON public.personalization_techniques FOR DELETE USING (is_admin_or_above((SELECT auth.uid()))); -- pt_select_active_or_admin kept as sole SELECT policy @@ -168,8 +180,10 @@ DROP POLICY IF EXISTS "products_select" ON public.products; DROP POLICY IF EXISTS "ra_admin_manage" ON public.ramo_atividade; CREATE POLICY "ra_admin_insert" ON public.ramo_atividade FOR INSERT WITH CHECK (is_admin_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "ra_admin_update" ON public.ramo_atividade; CREATE POLICY "ra_admin_update" ON public.ramo_atividade FOR UPDATE USING (is_admin_or_above((SELECT auth.uid()))) WITH CHECK (is_admin_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "ra_admin_delete" ON public.ramo_atividade; CREATE POLICY "ra_admin_delete" ON public.ramo_atividade FOR DELETE USING (is_admin_or_above((SELECT auth.uid()))); -- ra_select_authenticated (true) kept @@ -180,8 +194,10 @@ CREATE POLICY "ra_admin_delete" ON public.ramo_atividade DROP POLICY IF EXISTS "raf_admin_manage" ON public.ramo_atividade_filho; CREATE POLICY "raf_admin_insert" ON public.ramo_atividade_filho FOR INSERT WITH CHECK (is_admin_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "raf_admin_update" ON public.ramo_atividade_filho; CREATE POLICY "raf_admin_update" ON public.ramo_atividade_filho FOR UPDATE USING (is_admin_or_above((SELECT auth.uid()))) WITH CHECK (is_admin_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "raf_admin_delete" ON public.ramo_atividade_filho; CREATE POLICY "raf_admin_delete" ON public.ramo_atividade_filho FOR DELETE USING (is_admin_or_above((SELECT auth.uid()))); -- raf_select_authenticated (true) kept @@ -198,8 +214,10 @@ DROP POLICY IF EXISTS "rls_denial_log_select_policy" ON public.rls_denial_log; DROP POLICY IF EXISTS "Devs manage role_permissions" ON public.role_permissions; CREATE POLICY "role_permissions_dev_insert" ON public.role_permissions FOR INSERT WITH CHECK (is_dev((SELECT auth.uid()))); +DROP POLICY IF EXISTS "role_permissions_dev_update" ON public.role_permissions; CREATE POLICY "role_permissions_dev_update" ON public.role_permissions FOR UPDATE USING (is_dev((SELECT auth.uid()))) WITH CHECK (is_dev((SELECT auth.uid()))); +DROP POLICY IF EXISTS "role_permissions_dev_delete" ON public.role_permissions; CREATE POLICY "role_permissions_dev_delete" ON public.role_permissions FOR DELETE USING (is_dev((SELECT auth.uid()))); -- "Authenticated read role_permissions" SELECT kept @@ -250,8 +268,10 @@ ALTER POLICY "Users read own roles" ON public.user_roles DROP POLICY IF EXISTS "Supervisors can manage revocations" ON public.user_token_revocations; CREATE POLICY "revocations_supervisor_insert" ON public.user_token_revocations FOR INSERT WITH CHECK (is_supervisor_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "revocations_supervisor_update" ON public.user_token_revocations; CREATE POLICY "revocations_supervisor_update" ON public.user_token_revocations FOR UPDATE USING (is_supervisor_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "revocations_supervisor_delete" ON public.user_token_revocations; CREATE POLICY "revocations_supervisor_delete" ON public.user_token_revocations FOR DELETE USING (is_supervisor_or_above((SELECT auth.uid()))); -- "Users can view own revocation" SELECT kept @@ -262,8 +282,10 @@ CREATE POLICY "revocations_supervisor_delete" ON public.user_token_revocations DROP POLICY IF EXISTS "Admins can manage video variant links" ON public.video_variant_links; CREATE POLICY "vvl_admin_insert" ON public.video_variant_links FOR INSERT WITH CHECK (is_admin((SELECT auth.uid()))); +DROP POLICY IF EXISTS "vvl_admin_update" ON public.video_variant_links; CREATE POLICY "vvl_admin_update" ON public.video_variant_links FOR UPDATE USING (is_admin((SELECT auth.uid()))) WITH CHECK (is_admin((SELECT auth.uid()))); +DROP POLICY IF EXISTS "vvl_admin_delete" ON public.video_variant_links; CREATE POLICY "vvl_admin_delete" ON public.video_variant_links FOR DELETE USING (is_admin((SELECT auth.uid()))); -- "Authenticated users can read video variant links" SELECT kept diff --git a/supabase/migrations/20260512000007_t31_fix_multiple_permissive_policies.sql b/supabase/migrations/20260512000007_t31_fix_multiple_permissive_policies.sql index 45eaa1e06..03cb98e13 100644 --- a/supabase/migrations/20260512000007_t31_fix_multiple_permissive_policies.sql +++ b/supabase/migrations/20260512000007_t31_fix_multiple_permissive_policies.sql @@ -7,37 +7,41 @@ -- ── Drop service_role policies (redundant — service_role has bypassrls) ───── -DROP POLICY "color_groups_service_role" ON public.color_groups; -DROP POLICY "material_groups_service_role" ON public.material_groups; -DROP POLICY "pi_all_service" ON public.product_images; -DROP POLICY "pv_all_service" ON public.product_videos; +DROP POLICY IF EXISTS "color_groups_service_role" ON public.color_groups; +DROP POLICY IF EXISTS "material_groups_service_role" ON public.material_groups; +DROP POLICY IF EXISTS "pi_all_service" ON public.product_images; +DROP POLICY IF EXISTS "pv_all_service" ON public.product_videos; -- ── ai_usage_quotas: split admin_write ALL → INSERT + UPDATE + DELETE ─────── -DROP POLICY "ai_usage_quotas_admin_write" ON public.ai_usage_quotas; +DROP POLICY IF EXISTS "ai_usage_quotas_admin_write" ON public.ai_usage_quotas; CREATE POLICY "ai_usage_quotas_admin_insert" ON public.ai_usage_quotas FOR INSERT WITH CHECK (is_dev() OR has_role((SELECT auth.uid()), 'admin'::app_role)); +DROP POLICY IF EXISTS "ai_usage_quotas_admin_update" ON public.ai_usage_quotas; CREATE POLICY "ai_usage_quotas_admin_update" ON public.ai_usage_quotas FOR UPDATE USING (is_dev() OR has_role((SELECT auth.uid()), 'admin'::app_role)) WITH CHECK (is_dev() OR has_role((SELECT auth.uid()), 'admin'::app_role)); +DROP POLICY IF EXISTS "ai_usage_quotas_admin_delete" ON public.ai_usage_quotas; CREATE POLICY "ai_usage_quotas_admin_delete" ON public.ai_usage_quotas FOR DELETE USING (is_dev() OR has_role((SELECT auth.uid()), 'admin'::app_role)); -- ── collection_items: split manage ALL → INSERT + UPDATE + DELETE ──────────── -DROP POLICY "Users can manage own collection items" ON public.collection_items; +DROP POLICY IF EXISTS "Users can manage own collection items" ON public.collection_items; CREATE POLICY "collection_items_own_insert" ON public.collection_items FOR INSERT TO authenticated WITH CHECK ( EXISTS (SELECT 1 FROM collections WHERE collections.id = collection_items.collection_id AND collections.user_id = (SELECT auth.uid())) ); +DROP POLICY IF EXISTS "collection_items_own_update" ON public.collection_items; CREATE POLICY "collection_items_own_update" ON public.collection_items FOR UPDATE TO authenticated USING (EXISTS (SELECT 1 FROM collections WHERE collections.id = collection_items.collection_id AND collections.user_id = (SELECT auth.uid()))) WITH CHECK (EXISTS (SELECT 1 FROM collections WHERE collections.id = collection_items.collection_id AND collections.user_id = (SELECT auth.uid()))); +DROP POLICY IF EXISTS "collection_items_own_delete" ON public.collection_items; CREATE POLICY "collection_items_own_delete" ON public.collection_items FOR DELETE TO authenticated USING ( EXISTS (SELECT 1 FROM collections WHERE collections.id = collection_items.collection_id @@ -46,27 +50,31 @@ CREATE POLICY "collection_items_own_delete" ON public.collection_items -- ── collections: split manage ALL → INSERT + UPDATE + DELETE ──────────────── -DROP POLICY "Users can manage own collections" ON public.collections; +DROP POLICY IF EXISTS "Users can manage own collections" ON public.collections; CREATE POLICY "collections_own_insert" ON public.collections FOR INSERT TO authenticated WITH CHECK (user_id = (SELECT auth.uid())); +DROP POLICY IF EXISTS "collections_own_update" ON public.collections; CREATE POLICY "collections_own_update" ON public.collections FOR UPDATE TO authenticated USING (user_id = (SELECT auth.uid())) WITH CHECK (user_id = (SELECT auth.uid())); +DROP POLICY IF EXISTS "collections_own_delete" ON public.collections; CREATE POLICY "collections_own_delete" ON public.collections FOR DELETE TO authenticated USING (user_id = (SELECT auth.uid())); -- ── color_groups: split isolation ALL → INSERT + UPDATE + DELETE ───────────── -DROP POLICY "color_groups_isolation" ON public.color_groups; +DROP POLICY IF EXISTS "color_groups_isolation" ON public.color_groups; CREATE POLICY "color_groups_isolation_insert" ON public.color_groups FOR INSERT WITH CHECK ( organization_id = (SELECT current_setting('app.current_org_id'::text, true))::uuid ); +DROP POLICY IF EXISTS "color_groups_isolation_update" ON public.color_groups; CREATE POLICY "color_groups_isolation_update" ON public.color_groups FOR UPDATE USING (organization_id = (SELECT current_setting('app.current_org_id'::text, true))::uuid) WITH CHECK (organization_id = (SELECT current_setting('app.current_org_id'::text, true))::uuid); +DROP POLICY IF EXISTS "color_groups_isolation_delete" ON public.color_groups; CREATE POLICY "color_groups_isolation_delete" ON public.color_groups FOR DELETE USING ( organization_id = (SELECT current_setting('app.current_org_id'::text, true))::uuid @@ -74,74 +82,82 @@ CREATE POLICY "color_groups_isolation_delete" ON public.color_groups -- ── commemorative_date_colors: split admin ALL → INSERT + UPDATE + DELETE ──── -DROP POLICY "cdc_admin_or_above" ON public.commemorative_date_colors; +DROP POLICY IF EXISTS "cdc_admin_or_above" ON public.commemorative_date_colors; CREATE POLICY "cdc_admin_insert" ON public.commemorative_date_colors FOR INSERT WITH CHECK (is_admin_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "cdc_admin_update" ON public.commemorative_date_colors; CREATE POLICY "cdc_admin_update" ON public.commemorative_date_colors FOR UPDATE USING (is_admin_or_above((SELECT auth.uid()))) WITH CHECK (is_admin_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "cdc_admin_delete" ON public.commemorative_date_colors; CREATE POLICY "cdc_admin_delete" ON public.commemorative_date_colors FOR DELETE USING (is_admin_or_above((SELECT auth.uid()))); -- ── commemorative_date_exclusions: split admin ALL → INSERT + UPDATE + DELETE ─ -DROP POLICY "cde_admin_or_above" ON public.commemorative_date_exclusions; +DROP POLICY IF EXISTS "cde_admin_or_above" ON public.commemorative_date_exclusions; CREATE POLICY "cde_admin_insert" ON public.commemorative_date_exclusions FOR INSERT WITH CHECK (is_admin_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "cde_admin_update" ON public.commemorative_date_exclusions; CREATE POLICY "cde_admin_update" ON public.commemorative_date_exclusions FOR UPDATE USING (is_admin_or_above((SELECT auth.uid()))) WITH CHECK (is_admin_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "cde_admin_delete" ON public.commemorative_date_exclusions; CREATE POLICY "cde_admin_delete" ON public.commemorative_date_exclusions FOR DELETE USING (is_admin_or_above((SELECT auth.uid()))); -- ── commemorative_dates: split admin ALL → INSERT + UPDATE + DELETE ────────── -DROP POLICY "Admins can manage commemorative dates" ON public.commemorative_dates; +DROP POLICY IF EXISTS "Admins can manage commemorative dates" ON public.commemorative_dates; CREATE POLICY "commemorative_dates_admin_insert" ON public.commemorative_dates FOR INSERT WITH CHECK (is_admin_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "commemorative_dates_admin_update" ON public.commemorative_dates; CREATE POLICY "commemorative_dates_admin_update" ON public.commemorative_dates FOR UPDATE USING (is_admin_or_above((SELECT auth.uid()))) WITH CHECK (is_admin_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "commemorative_dates_admin_delete" ON public.commemorative_dates; CREATE POLICY "commemorative_dates_admin_delete" ON public.commemorative_dates FOR DELETE USING (is_admin_or_above((SELECT auth.uid()))); -- ── material_groups: drop overlapping ALL policy (mg_* policies already cover) ─ -DROP POLICY "material_groups_isolation" ON public.material_groups; +DROP POLICY IF EXISTS "material_groups_isolation" ON public.material_groups; -- ── variant_commemorative_dates: split admin ALL → INSERT + UPDATE + DELETE ── -DROP POLICY "Admins or above manage variant commemorative dates" ON public.variant_commemorative_dates; +DROP POLICY IF EXISTS "Admins or above manage variant commemorative dates" ON public.variant_commemorative_dates; CREATE POLICY "vcd_admin_insert" ON public.variant_commemorative_dates FOR INSERT WITH CHECK (is_admin_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "vcd_admin_update" ON public.variant_commemorative_dates; CREATE POLICY "vcd_admin_update" ON public.variant_commemorative_dates FOR UPDATE USING (is_admin_or_above((SELECT auth.uid()))) WITH CHECK (is_admin_or_above((SELECT auth.uid()))); +DROP POLICY IF EXISTS "vcd_admin_delete" ON public.variant_commemorative_dates; CREATE POLICY "vcd_admin_delete" ON public.variant_commemorative_dates FOR DELETE USING (is_admin_or_above((SELECT auth.uid()))); -- ── product_images: merge two SELECT policies into one ─────────────────────── -DROP POLICY "pi_select_auth" ON public.product_images; -DROP POLICY "product_images_select_public" ON public.product_images; +DROP POLICY IF EXISTS "pi_select_auth" ON public.product_images; +DROP POLICY IF EXISTS "product_images_select_public" ON public.product_images; CREATE POLICY "product_images_select" ON public.product_images FOR SELECT USING ((is_active = true) OR ((SELECT auth.uid()) IS NOT NULL)); -- ── product_videos: merge two SELECT policies into one ─────────────────────── -DROP POLICY "pv_select_auth" ON public.product_videos; -DROP POLICY "product_videos_select_public" ON public.product_videos; +DROP POLICY IF EXISTS "pv_select_auth" ON public.product_videos; +DROP POLICY IF EXISTS "product_videos_select_public" ON public.product_videos; CREATE POLICY "product_videos_select" ON public.product_videos FOR SELECT USING ((is_active = true) OR ((SELECT auth.uid()) IS NOT NULL)); -- ── profiles: merge two SELECT policies into one ───────────────────────────── -DROP POLICY "Admins can read all profiles" ON public.profiles; -DROP POLICY "Users can read own profile" ON public.profiles; +DROP POLICY IF EXISTS "Admins can read all profiles" ON public.profiles; +DROP POLICY IF EXISTS "Users can read own profile" ON public.profiles; CREATE POLICY "profiles_select" ON public.profiles FOR SELECT USING ( ((SELECT auth.uid()) = id) OR is_admin_or_above((SELECT auth.uid())) diff --git a/supabase/migrations/20260512000008_t32_backup_schema_primary_keys.sql b/supabase/migrations/20260512000008_t32_backup_schema_primary_keys.sql index 64045c895..0793d7b19 100644 --- a/supabase/migrations/20260512000008_t32_backup_schema_primary_keys.sql +++ b/supabase/migrations/20260512000008_t32_backup_schema_primary_keys.sql @@ -36,13 +36,13 @@ ALTER TABLE backup._backup_20260425_tecnicas_gravacao -- ── Surrogate id (no unique natural key) ──────────────────────────────────── ALTER TABLE backup._backup_collections_policies_b2b_20260511 - ADD COLUMN id bigserial PRIMARY KEY; + ADD COLUMN IF NOT EXISTS id bigserial PRIMARY KEY; ALTER TABLE backup._backup_functions_d12 - ADD COLUMN id bigserial PRIMARY KEY; + ADD COLUMN IF NOT EXISTS id bigserial PRIMARY KEY; ALTER TABLE backup._backup_storage_policies_20260511_d11 - ADD COLUMN id bigserial PRIMARY KEY; + ADD COLUMN IF NOT EXISTS id bigserial PRIMARY KEY; ALTER TABLE backup._backup_unif_funcoes_20260425 - ADD COLUMN id bigserial PRIMARY KEY; + ADD COLUMN IF NOT EXISTS id bigserial PRIMARY KEY; diff --git a/supabase/migrations/20260512201700_t17_fix_function_search_path_mutable_22_funcs.sql b/supabase/migrations/20260512201700_t17_fix_function_search_path_mutable_22_funcs.sql new file mode 100644 index 000000000..71ca04922 --- /dev/null +++ b/supabase/migrations/20260512201700_t17_fix_function_search_path_mutable_22_funcs.sql @@ -0,0 +1,2 @@ +-- Migration 20260512201700 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512211010_t19_security_invoker_non_public_views.sql b/supabase/migrations/20260512211010_t19_security_invoker_non_public_views.sql new file mode 100644 index 000000000..fa9df4b34 --- /dev/null +++ b/supabase/migrations/20260512211010_t19_security_invoker_non_public_views.sql @@ -0,0 +1,2 @@ +-- Migration 20260512211010 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512211015_t20_revoke_matview_wrappers_from_api.sql b/supabase/migrations/20260512211015_t20_revoke_matview_wrappers_from_api.sql new file mode 100644 index 000000000..7053cce93 --- /dev/null +++ b/supabase/migrations/20260512211015_t20_revoke_matview_wrappers_from_api.sql @@ -0,0 +1,2 @@ +-- Migration 20260512211015 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512211025_t21_fix_rls_always_true_policies.sql b/supabase/migrations/20260512211025_t21_fix_rls_always_true_policies.sql new file mode 100644 index 000000000..768a3bea7 --- /dev/null +++ b/supabase/migrations/20260512211025_t21_fix_rls_always_true_policies.sql @@ -0,0 +1,2 @@ +-- Migration 20260512211025 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512211737_t28_pk_and_fk_indexes.sql b/supabase/migrations/20260512211737_t28_pk_and_fk_indexes.sql new file mode 100644 index 000000000..6b1d8f58b --- /dev/null +++ b/supabase/migrations/20260512211737_t28_pk_and_fk_indexes.sql @@ -0,0 +1,2 @@ +-- Migration 20260512211737 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512212230_t25_fix_auth_rls_initplan.sql b/supabase/migrations/20260512212230_t25_fix_auth_rls_initplan.sql new file mode 100644 index 000000000..07c6b9b93 --- /dev/null +++ b/supabase/migrations/20260512212230_t25_fix_auth_rls_initplan.sql @@ -0,0 +1,2 @@ +-- Migration 20260512212230 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512212314_t26_consolidate_permissive_policies.sql b/supabase/migrations/20260512212314_t26_consolidate_permissive_policies.sql new file mode 100644 index 000000000..a65ed04bb --- /dev/null +++ b/supabase/migrations/20260512212314_t26_consolidate_permissive_policies.sql @@ -0,0 +1,2 @@ +-- Migration 20260512212314 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512212623_t28b_fk_indexes_remaining.sql b/supabase/migrations/20260512212623_t28b_fk_indexes_remaining.sql new file mode 100644 index 000000000..5e67eaea7 --- /dev/null +++ b/supabase/migrations/20260512212623_t28b_fk_indexes_remaining.sql @@ -0,0 +1,2 @@ +-- Migration 20260512212623 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512212708_t25b_material_groups_rls.sql b/supabase/migrations/20260512212708_t25b_material_groups_rls.sql new file mode 100644 index 000000000..3508ae0ae --- /dev/null +++ b/supabase/migrations/20260512212708_t25b_material_groups_rls.sql @@ -0,0 +1,2 @@ +-- Migration 20260512212708 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512213513_t21b_fix_workspace_notifications_policy.sql b/supabase/migrations/20260512213513_t21b_fix_workspace_notifications_policy.sql new file mode 100644 index 000000000..b67f4fe7c --- /dev/null +++ b/supabase/migrations/20260512213513_t21b_fix_workspace_notifications_policy.sql @@ -0,0 +1,2 @@ +-- Migration 20260512213513 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512220720_t30_fix_auth_rls_initplan_all_schemas.sql b/supabase/migrations/20260512220720_t30_fix_auth_rls_initplan_all_schemas.sql new file mode 100644 index 000000000..628a91ca2 --- /dev/null +++ b/supabase/migrations/20260512220720_t30_fix_auth_rls_initplan_all_schemas.sql @@ -0,0 +1,2 @@ +-- Migration 20260512220720 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512220756_t30b_test_profiles_policy.sql b/supabase/migrations/20260512220756_t30b_test_profiles_policy.sql new file mode 100644 index 000000000..edf92dce6 --- /dev/null +++ b/supabase/migrations/20260512220756_t30b_test_profiles_policy.sql @@ -0,0 +1,2 @@ +-- Migration 20260512220756 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512220821_t30c_test_index_creation.sql b/supabase/migrations/20260512220821_t30c_test_index_creation.sql new file mode 100644 index 000000000..1674765d8 --- /dev/null +++ b/supabase/migrations/20260512220821_t30c_test_index_creation.sql @@ -0,0 +1,2 @@ +-- Migration 20260512220821 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512221227_t30d_test_current_setting_policy.sql b/supabase/migrations/20260512221227_t30d_test_current_setting_policy.sql new file mode 100644 index 000000000..92c5e1afe --- /dev/null +++ b/supabase/migrations/20260512221227_t30d_test_current_setting_policy.sql @@ -0,0 +1,2 @@ +-- Migration 20260512221227 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512221328_t30_fix_initplan_remaining.sql b/supabase/migrations/20260512221328_t30_fix_initplan_remaining.sql new file mode 100644 index 000000000..8b8469a12 --- /dev/null +++ b/supabase/migrations/20260512221328_t30_fix_initplan_remaining.sql @@ -0,0 +1,2 @@ +-- Migration 20260512221328 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512221846_t31_fix_multiple_permissive_policies.sql b/supabase/migrations/20260512221846_t31_fix_multiple_permissive_policies.sql new file mode 100644 index 000000000..b6cb292a9 --- /dev/null +++ b/supabase/migrations/20260512221846_t31_fix_multiple_permissive_policies.sql @@ -0,0 +1,2 @@ +-- Migration 20260512221846 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512222200_t28_pilot_revoke_admin_security_definer_from_anon_authenticated.sql b/supabase/migrations/20260512222200_t28_pilot_revoke_admin_security_definer_from_anon_authenticated.sql new file mode 100644 index 000000000..18a6a3a58 --- /dev/null +++ b/supabase/migrations/20260512222200_t28_pilot_revoke_admin_security_definer_from_anon_authenticated.sql @@ -0,0 +1,2 @@ +-- Migration 20260512222200 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512222301_t28_pilot_revoke_admin_security_definer_batch2.sql b/supabase/migrations/20260512222301_t28_pilot_revoke_admin_security_definer_batch2.sql new file mode 100644 index 000000000..d9b177f02 --- /dev/null +++ b/supabase/migrations/20260512222301_t28_pilot_revoke_admin_security_definer_batch2.sql @@ -0,0 +1,2 @@ +-- Migration 20260512222301 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512222316_t32_backup_schema_primary_keys.sql b/supabase/migrations/20260512222316_t32_backup_schema_primary_keys.sql new file mode 100644 index 000000000..92787abf4 --- /dev/null +++ b/supabase/migrations/20260512222316_t32_backup_schema_primary_keys.sql @@ -0,0 +1,2 @@ +-- Migration 20260512222316 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512222335_t33_revoke_anon_execute_public_functions.sql b/supabase/migrations/20260512222335_t33_revoke_anon_execute_public_functions.sql new file mode 100644 index 000000000..7b6789dcc --- /dev/null +++ b/supabase/migrations/20260512222335_t33_revoke_anon_execute_public_functions.sql @@ -0,0 +1,2 @@ +-- Migration 20260512222335 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512222835_t34_move_unaccent_to_extensions_schema.sql b/supabase/migrations/20260512222835_t34_move_unaccent_to_extensions_schema.sql new file mode 100644 index 000000000..098aa3a23 --- /dev/null +++ b/supabase/migrations/20260512222835_t34_move_unaccent_to_extensions_schema.sql @@ -0,0 +1,2 @@ +-- Migration 20260512222835 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512222956_t34b_set_views_security_invoker.sql b/supabase/migrations/20260512222956_t34b_set_views_security_invoker.sql new file mode 100644 index 000000000..d249b3bb2 --- /dev/null +++ b/supabase/migrations/20260512222956_t34b_set_views_security_invoker.sql @@ -0,0 +1,2 @@ +-- Migration 20260512222956 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260512223054_t33b_revoke_public_grant_authenticated.sql b/supabase/migrations/20260512223054_t33b_revoke_public_grant_authenticated.sql new file mode 100644 index 000000000..063bbe799 --- /dev/null +++ b/supabase/migrations/20260512223054_t33b_revoke_public_grant_authenticated.sql @@ -0,0 +1,2 @@ +-- Migration 20260512223054 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513004536_t35_fix_material_groups_rls_broken_subquery.sql b/supabase/migrations/20260513004536_t35_fix_material_groups_rls_broken_subquery.sql new file mode 100644 index 000000000..39f8da8bb --- /dev/null +++ b/supabase/migrations/20260513004536_t35_fix_material_groups_rls_broken_subquery.sql @@ -0,0 +1,2 @@ +-- Migration 20260513004536 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513004549_t36_alter_default_privileges_functions.sql b/supabase/migrations/20260513004549_t36_alter_default_privileges_functions.sql new file mode 100644 index 000000000..ee556a243 --- /dev/null +++ b/supabase/migrations/20260513004549_t36_alter_default_privileges_functions.sql @@ -0,0 +1,2 @@ +-- Migration 20260513004549 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513005049_t29_revoke_auth_from_service_only_fns.sql b/supabase/migrations/20260513005049_t29_revoke_auth_from_service_only_fns.sql new file mode 100644 index 000000000..54fb581d6 --- /dev/null +++ b/supabase/migrations/20260513005049_t29_revoke_auth_from_service_only_fns.sql @@ -0,0 +1,2 @@ +-- Migration 20260513005049 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513012236_t37a_security_invoker_safe_batch.sql b/supabase/migrations/20260513012236_t37a_security_invoker_safe_batch.sql new file mode 100644 index 000000000..43610c3fe --- /dev/null +++ b/supabase/migrations/20260513012236_t37a_security_invoker_safe_batch.sql @@ -0,0 +1,2 @@ +-- Migration 20260513012236 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513012738_fix_cotacoes_select_isolation.sql b/supabase/migrations/20260513012738_fix_cotacoes_select_isolation.sql new file mode 100644 index 000000000..c27abce80 --- /dev/null +++ b/supabase/migrations/20260513012738_fix_cotacoes_select_isolation.sql @@ -0,0 +1,2 @@ +-- Migration 20260513012738 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513012752_fix_cotacoes_update_stale_jwt_role.sql b/supabase/migrations/20260513012752_fix_cotacoes_update_stale_jwt_role.sql new file mode 100644 index 000000000..c8ca483b6 --- /dev/null +++ b/supabase/migrations/20260513012752_fix_cotacoes_update_stale_jwt_role.sql @@ -0,0 +1,2 @@ +-- Migration 20260513012752 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513012807_fix_role_permissions_policy_roles.sql b/supabase/migrations/20260513012807_fix_role_permissions_policy_roles.sql new file mode 100644 index 000000000..ec6ba1f0d --- /dev/null +++ b/supabase/migrations/20260513012807_fix_role_permissions_policy_roles.sql @@ -0,0 +1,2 @@ +-- Migration 20260513012807 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513014221_t37c_revoke_authenticated_trigger_vault.sql b/supabase/migrations/20260513014221_t37c_revoke_authenticated_trigger_vault.sql new file mode 100644 index 000000000..49f9e5024 --- /dev/null +++ b/supabase/migrations/20260513014221_t37c_revoke_authenticated_trigger_vault.sql @@ -0,0 +1,2 @@ +-- Migration 20260513014221 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513014424_t30_revoke_auth_trigger_functions.sql b/supabase/migrations/20260513014424_t30_revoke_auth_trigger_functions.sql new file mode 100644 index 000000000..9e387c6bc --- /dev/null +++ b/supabase/migrations/20260513014424_t30_revoke_auth_trigger_functions.sql @@ -0,0 +1,2 @@ +-- Migration 20260513014424 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513014503_t31_revoke_auth_cron_service_workers.sql b/supabase/migrations/20260513014503_t31_revoke_auth_cron_service_workers.sql new file mode 100644 index 000000000..f40b05dbe --- /dev/null +++ b/supabase/migrations/20260513014503_t31_revoke_auth_cron_service_workers.sql @@ -0,0 +1,2 @@ +-- Migration 20260513014503 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513014540_t32_revoke_auth_admin_vault_test.sql b/supabase/migrations/20260513014540_t32_revoke_auth_admin_vault_test.sql new file mode 100644 index 000000000..6f28fa58c --- /dev/null +++ b/supabase/migrations/20260513014540_t32_revoke_auth_admin_vault_test.sql @@ -0,0 +1,2 @@ +-- Migration 20260513014540 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513015022_t37b1_security_invoker_candidate_batch1.sql b/supabase/migrations/20260513015022_t37b1_security_invoker_candidate_batch1.sql new file mode 100644 index 000000000..1af65ddfc --- /dev/null +++ b/supabase/migrations/20260513015022_t37b1_security_invoker_candidate_batch1.sql @@ -0,0 +1,2 @@ +-- Migration 20260513015022 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513015058_t37b2_security_invoker_candidate_batch2.sql b/supabase/migrations/20260513015058_t37b2_security_invoker_candidate_batch2.sql new file mode 100644 index 000000000..1d098f502 --- /dev/null +++ b/supabase/migrations/20260513015058_t37b2_security_invoker_candidate_batch2.sql @@ -0,0 +1,2 @@ +-- Migration 20260513015058 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513015133_t37d_revoke_authenticated_cron_backend.sql b/supabase/migrations/20260513015133_t37d_revoke_authenticated_cron_backend.sql new file mode 100644 index 000000000..8ec0d432e --- /dev/null +++ b/supabase/migrations/20260513015133_t37d_revoke_authenticated_cron_backend.sql @@ -0,0 +1,2 @@ +-- Migration 20260513015133 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513015749_t33_revoke_auth_unused_log_service_fns.sql b/supabase/migrations/20260513015749_t33_revoke_auth_unused_log_service_fns.sql new file mode 100644 index 000000000..2c47eeaba --- /dev/null +++ b/supabase/migrations/20260513015749_t33_revoke_auth_unused_log_service_fns.sql @@ -0,0 +1,2 @@ +-- Migration 20260513015749 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513022925_seed_dev_role_permissions.sql b/supabase/migrations/20260513022925_seed_dev_role_permissions.sql new file mode 100644 index 000000000..c3fbc09b1 --- /dev/null +++ b/supabase/migrations/20260513022925_seed_dev_role_permissions.sql @@ -0,0 +1,2 @@ +-- Migration 20260513022925 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513040948_fix_is_admin_or_above_missing_supervisor.sql b/supabase/migrations/20260513040948_fix_is_admin_or_above_missing_supervisor.sql new file mode 100644 index 000000000..7eddc1ccd --- /dev/null +++ b/supabase/migrations/20260513040948_fix_is_admin_or_above_missing_supervisor.sql @@ -0,0 +1,2 @@ +-- Migration 20260513040948 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513040959_fix_quarantine_storage_policy.sql b/supabase/migrations/20260513040959_fix_quarantine_storage_policy.sql new file mode 100644 index 000000000..ebb2dd7ef --- /dev/null +++ b/supabase/migrations/20260513040959_fix_quarantine_storage_policy.sql @@ -0,0 +1,2 @@ +-- Migration 20260513040959 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513041026_fix_cron_project_url.sql b/supabase/migrations/20260513041026_fix_cron_project_url.sql new file mode 100644 index 000000000..eab4ac068 --- /dev/null +++ b/supabase/migrations/20260513041026_fix_cron_project_url.sql @@ -0,0 +1,2 @@ +-- Migration 20260513041026 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513060035_restrict_legacy_audit_log_policies.sql b/supabase/migrations/20260513060035_restrict_legacy_audit_log_policies.sql new file mode 100644 index 000000000..a251b51aa --- /dev/null +++ b/supabase/migrations/20260513060035_restrict_legacy_audit_log_policies.sql @@ -0,0 +1,2 @@ +-- Migration 20260513060035 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513060049_harden_storage_buckets.sql b/supabase/migrations/20260513060049_harden_storage_buckets.sql new file mode 100644 index 000000000..d9ad6e163 --- /dev/null +++ b/supabase/migrations/20260513060049_harden_storage_buckets.sql @@ -0,0 +1,2 @@ +-- Migration 20260513060049 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260513060152_add_missing_service_cron_schedules.sql b/supabase/migrations/20260513060152_add_missing_service_cron_schedules.sql new file mode 100644 index 000000000..6ce1788c3 --- /dev/null +++ b/supabase/migrations/20260513060152_add_missing_service_cron_schedules.sql @@ -0,0 +1,2 @@ +-- Migration 20260513060152 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260514163900_t39_create_missing_tables_part2.sql b/supabase/migrations/20260514163900_t39_create_missing_tables_part2.sql new file mode 100644 index 000000000..5153842dc --- /dev/null +++ b/supabase/migrations/20260514163900_t39_create_missing_tables_part2.sql @@ -0,0 +1,2 @@ +-- Migration 20260514163900 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260514163934_t39_create_missing_tables_part3.sql b/supabase/migrations/20260514163934_t39_create_missing_tables_part3.sql new file mode 100644 index 000000000..b9518bea8 --- /dev/null +++ b/supabase/migrations/20260514163934_t39_create_missing_tables_part3.sql @@ -0,0 +1,2 @@ +-- Migration 20260514163934 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260514200725_fix_policy_idempotency_and_security.sql b/supabase/migrations/20260514200725_fix_policy_idempotency_and_security.sql new file mode 100644 index 000000000..65ddfef20 --- /dev/null +++ b/supabase/migrations/20260514200725_fix_policy_idempotency_and_security.sql @@ -0,0 +1,2 @@ +-- Migration 20260514200725 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/supabase/migrations/20260514220558_onda13_rls_audit_logs_admin_only.sql b/supabase/migrations/20260514220558_onda13_rls_audit_logs_admin_only.sql new file mode 100644 index 000000000..5a9eee0c8 --- /dev/null +++ b/supabase/migrations/20260514220558_onda13_rls_audit_logs_admin_only.sql @@ -0,0 +1,2 @@ +-- Migration 20260514220558 applied directly to production database. +-- Stub file created to keep Supabase CLI in sync with remote schema_migrations. diff --git a/tests/e2e/artifacts/compare/viewer/audit-snapshot.html b/tests/e2e/artifacts/compare/viewer/audit-snapshot.html index 74ddb745a..4b14c29e6 100644 --- a/tests/e2e/artifacts/compare/viewer/audit-snapshot.html +++ b/tests/e2e/artifacts/compare/viewer/audit-snapshot.html @@ -1 +1 @@ -

Comparador de Produtos

Comparando 2 produtos

Foto
Prod 1
Prod 2
Produto
Preço
R$ 10,00
R$ 20,00
Qtd. mínima
1 un.
2 un.
Estoque
10
20
Cores
Fornecedor
S1
S1
\ No newline at end of file +

Comparador de Produtos

Comparando 2 produtos

Foto
Prod 1
Prod 2
Produto
Preço
R$ 10,00
R$ 20,00
Qtd. mínima
1 un.
2 un.
Estoque
10
20
Cores
Fornecedor
S1
S1
\ No newline at end of file diff --git a/tests/unit/hooks/useDevGate.test.ts b/tests/unit/hooks/useDevGate.test.ts index 9f8dfe8d5..a4bd5adaf 100644 --- a/tests/unit/hooks/useDevGate.test.ts +++ b/tests/unit/hooks/useDevGate.test.ts @@ -1,3 +1,4 @@ +import { renderHook, act } from '@testing-library/react'; import { describe, it, expect, vi, beforeEach } from 'vitest'; import { useDevGate } from '@/hooks/useDevGate'; import { devInfraGate } from '@/lib/system/dev-gate/DevInfraGate'; @@ -8,10 +9,11 @@ vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => mockUseAuth(), })); -// Mock devInfraGate.shouldShow +// Mock devInfraGate — a API atual usa shouldShow(roles: AppRole[]) e subscribe() vi.mock('@/lib/system/dev-gate/DevInfraGate', () => ({ devInfraGate: { shouldShow: vi.fn(), + subscribe: vi.fn(() => () => {}), }, })); @@ -21,34 +23,64 @@ describe('useDevGate', () => { }); it('deve retornar isAllowed true se devInfraGate.shouldShow retornar true', () => { - mockUseAuth.mockReturnValue({ isDev: true }); + mockUseAuth.mockReturnValue({ roles: ['dev'], isDev: true, isLoading: false }); vi.mocked(devInfraGate.shouldShow).mockReturnValue(true); - const { isAllowed, isDev } = useDevGate(); + const { result } = renderHook(() => useDevGate()); - expect(isAllowed).toBe(true); - expect(isDev).toBe(true); - expect(devInfraGate.shouldShow).toHaveBeenCalledWith(true); + expect(result.current.isAllowed).toBe(true); + expect(result.current.isDev).toBe(true); }); it('deve retornar isAllowed false se devInfraGate.shouldShow retornar false', () => { - mockUseAuth.mockReturnValue({ isDev: false }); + mockUseAuth.mockReturnValue({ roles: [], isDev: false, isLoading: false }); vi.mocked(devInfraGate.shouldShow).mockReturnValue(false); - const { isAllowed, isDev } = useDevGate(); + const { result } = renderHook(() => useDevGate()); - expect(isAllowed).toBe(false); - expect(isDev).toBe(false); - expect(devInfraGate.shouldShow).toHaveBeenCalledWith(false); + expect(result.current.isAllowed).toBe(false); + expect(result.current.isDev).toBe(false); }); it('deve refletir o status isDev corretamente mesmo quando isAllowed é forçado', () => { - mockUseAuth.mockReturnValue({ isDev: false }); - vi.mocked(devInfraGate.shouldShow).mockReturnValue(true); // Forçado por localStorage por exemplo + // isDev é false mas shouldShow retorna true (ex: forçado por localStorage) + mockUseAuth.mockReturnValue({ roles: [], isDev: false, isLoading: false }); + vi.mocked(devInfraGate.shouldShow).mockReturnValue(true); + + const { result } = renderHook(() => useDevGate()); + + expect(result.current.isAllowed).toBe(true); + expect(result.current.isDev).toBe(false); + }); + + it('deve retornar isAllowed false quando isLoading é true', () => { + mockUseAuth.mockReturnValue({ roles: ['dev'], isDev: true, isLoading: true }); + vi.mocked(devInfraGate.shouldShow).mockReturnValue(true); + + const { result } = renderHook(() => useDevGate()); + + expect(result.current.isAllowed).toBe(false); + }); + + it('deve reagir a mudanças na store do devInfraGate', () => { + mockUseAuth.mockReturnValue({ roles: ['dev'], isDev: true, isLoading: false }); + vi.mocked(devInfraGate.shouldShow).mockReturnValue(true); + + const { result } = renderHook(() => useDevGate()); + expect(result.current.isAllowed).toBe(true); + + // Simular mudança de estado na store + vi.mocked(devInfraGate.shouldShow).mockReturnValue(false); - const { isAllowed, isDev } = useDevGate(); + // Capturar o callback de onStoreChange passado para subscribe + const subscribeCall = vi.mocked(devInfraGate.subscribe).mock.calls[0]; + const onStoreChange = subscribeCall?.[0]; - expect(isAllowed).toBe(true); - expect(isDev).toBe(false); + if (onStoreChange) { + act(() => { + onStoreChange(); + }); + expect(result.current.isAllowed).toBe(false); + } }); }); diff --git a/tests/unit/lib/system/dev-gate/DevInfraGate.test.ts b/tests/unit/lib/system/dev-gate/DevInfraGate.test.ts index 2a6f9eab9..8cb8835dc 100644 --- a/tests/unit/lib/system/dev-gate/DevInfraGate.test.ts +++ b/tests/unit/lib/system/dev-gate/DevInfraGate.test.ts @@ -27,42 +27,52 @@ describe('parseGateFlag', () => { }); describe('DevInfraGate', () => { - it('deve retornar isDev quando todos os providers retornam "auto"', () => { + it('deve retornar true quando todos os providers retornam "auto" e usuário tem acesso', () => { const mockProvider: GateFlagProvider = { getFlag: () => 'auto' }; const gate = new DevInfraGate([mockProvider]); - - expect(gate.shouldShow(true)).toBe(true); - expect(gate.shouldShow(false)).toBe(false); + + // Usuário com role 'dev' tem acesso; quando todos os providers dizem 'auto', decisão padrão é true + expect(gate.shouldShow(['dev'])).toBe(true); + // Usuário sem roles não tem acesso + expect(gate.shouldShow([])).toBe(false); }); it('deve respeitar a precedência do primeiro provider que retornar um booleano', () => { const p1: GateFlagProvider = { getFlag: () => false }; const p2: GateFlagProvider = { getFlag: () => true }; const gate = new DevInfraGate([p1, p2]); - - // P1 tem precedência e diz false, ignorando P2 e isDev=true - expect(gate.shouldShow(true)).toBe(false); + + // P1 tem precedência e diz false, ignorando P2 + expect(gate.shouldShow(['dev'])).toBe(false); }); it('deve passar para o próximo provider se o primeiro for "auto"', () => { const p1: GateFlagProvider = { getFlag: () => 'auto' }; const p2: GateFlagProvider = { getFlag: () => true }; const gate = new DevInfraGate([p1, p2]); - - expect(gate.shouldShow(false)).toBe(true); + + // P1 é 'auto', p2 diz true → deve mostrar para usuário com acesso + expect(gate.shouldShow(['dev'])).toBe(true); }); }); describe('EnvGateProvider', () => { + beforeEach(() => { + // Reset static cache between tests to allow reading fresh env values + (EnvGateProvider as unknown as { cachedValue: null }).cachedValue = null; + }); + it('lê flag das variáveis de ambiente', () => { - const provider = new EnvGateProvider(); - vi.stubEnv('VITE_SHOW_DEV_INFRA_MESSAGES', 'false'); + const provider = new EnvGateProvider(); expect(provider.getFlag()).toBe(false); - + vi.unstubAllEnvs(); + + // Reset cache before reading the new env value + (EnvGateProvider as unknown as { cachedValue: null }).cachedValue = null; + vi.stubEnv('VITE_SHOW_DEV_INFRA_MESSAGES', 'true'); expect(provider.getFlag()).toBe(true); - vi.unstubAllEnvs(); }); }); @@ -74,13 +84,13 @@ describe('LocalStorageGateProvider', () => { it('lê flag do localStorage', () => { const provider = new LocalStorageGateProvider('test_key'); - + localStorage.setItem('test_key', 'true'); expect(provider.getFlag()).toBe(true); - + localStorage.setItem('test_key', '0'); expect(provider.getFlag()).toBe(false); - + localStorage.removeItem('test_key'); expect(provider.getFlag()).toBe('auto'); }); @@ -88,11 +98,11 @@ describe('LocalStorageGateProvider', () => { it('falha silenciosamente se localStorage não estiver disponível', () => { const provider = new LocalStorageGateProvider(); const originalGetItem = Storage.prototype.getItem; - + Storage.prototype.getItem = vi.fn(() => { throw new Error('Security Error'); }); - + expect(provider.getFlag()).toBe('auto'); - + Storage.prototype.getItem = originalGetItem; }); }); diff --git a/tests/unit/system/DevInfraGate.test.ts b/tests/unit/system/DevInfraGate.test.ts index 604da00ef..cfa7f4c04 100644 --- a/tests/unit/system/DevInfraGate.test.ts +++ b/tests/unit/system/DevInfraGate.test.ts @@ -22,48 +22,55 @@ describe('DevInfraGate', () => { it('should notify listeners when invalidateCache is called', () => { const listener = vi.fn(); gate.subscribe(listener); - + gate.invalidateCache(); - + // invalidateCache usa debounce de 50ms; avançar os timers para disparar + vi.advanceTimersByTime(50); + expect(listener).toHaveBeenCalledTimes(1); }); it('should invalidate cache when storage event triggers with relevant key', () => { const listener = vi.fn(); gate.subscribe(listener); - - // Simular evento de storage + const event = new StorageEvent('storage', { key: 'show_dev_infra_messages', newValue: 'true' }); window.dispatchEvent(event); - + // O handleStorageEvent chama invalidateCache que usa debounce de 50ms + vi.advanceTimersByTime(50); + expect(listener).toHaveBeenCalledTimes(1); }); it('should NOT invalidate cache when storage event triggers with irrelevant key', () => { const listener = vi.fn(); gate.subscribe(listener); - + const event = new StorageEvent('storage', { key: 'some_other_key', newValue: 'true' }); window.dispatchEvent(event); - + vi.advanceTimersByTime(50); + expect(listener).not.toHaveBeenCalled(); }); it('should return cached value until invalidated', () => { - gate.shouldShow(true); + // Primeira chamada: avalia os providers e armazena em cache + gate.shouldShow(['dev']); + expect(mockProvider.getFlag).toHaveBeenCalledTimes(1); + + // Segunda chamada: usa cache (sem nova avaliação dos providers) + gate.shouldShow(['dev']); expect(mockProvider.getFlag).toHaveBeenCalledTimes(1); - - gate.shouldShow(true); - expect(mockProvider.getFlag).toHaveBeenCalledTimes(1); // Cached - + + // Após invalidar, próxima chamada re-avalia os providers gate.invalidateCache(); - gate.shouldShow(true); - expect(mockProvider.getFlag).toHaveBeenCalledTimes(2); // Re-evaluated + gate.shouldShow(['dev']); + expect(mockProvider.getFlag).toHaveBeenCalledTimes(2); }); });