Bladeren bron

WIP Updates to import screen to actually perform imports on files added.

vtugulan 3 dagen geleden
bovenliggende
commit
a59e343ccc

+ 36 - 18
app/actions/imports.ts

@@ -3,6 +3,7 @@
 import { prisma } from '@/lib/prisma';
 import { revalidatePath } from 'next/cache';
 import { z } from 'zod';
+import { ImportProcessor } from '@/app/lib/excel-import/import-processor';
 
 // Validation schemas
 const createImportSchema = z.object({
@@ -103,11 +104,6 @@ export async function getImportById(id: number) {
             },
           },
         },
-        cintasSummaries: {
-          orderBy: {
-            weekId: 'desc',
-          },
-        },
       },
     });
 
@@ -115,7 +111,15 @@ export async function getImportById(id: number) {
       return { success: false, error: 'Import not found' };
     }
 
-    return { success: true, data: importRecord };
+    // Fetch file separately if fileId exists
+    let file = undefined;
+    if (importRecord.fileId) {
+      file = await prisma.file.findUnique({
+        where: { id: importRecord.fileId },
+      });
+    }
+
+    return { success: true, data: { ...importRecord, file } };
   } catch (error) {
     console.error('Error fetching import:', error);
     return { success: false, error: 'Failed to fetch import' };
@@ -400,11 +404,15 @@ export async function getImportProgress(importId: number) {
       return { success: false, error: 'Import not found' };
     }
 
-    // For now, we'll simulate progress based on the existence of records
-    const totalRecords = await prisma.cintasInstallCalendar.count({
-      where: { importId }
-    });
+    // Check all possible tables for records
+    const [cintasCount, gowDataCount, gowFacCount, gowCorpCount] = await Promise.all([
+      prisma.cintasInstallCalendar.count({ where: { importId } }),
+      prisma.gowData.count({ where: { importId } }),
+      prisma.gowFacId.count({ where: { importId } }),
+      prisma.gowCorpRef.count({ where: { importId } }),
+    ]);
 
+    const totalRecords = cintasCount + gowDataCount + gowFacCount + gowCorpCount;
     // Since we don't have status fields, we'll use record count as proxy
     const hasRecords = totalRecords > 0;
 
@@ -471,15 +479,25 @@ export async function triggerImportProcess(importId: number) {
       };
     }
 
-    // For now, we'll simulate the processing
-    // In production, this would integrate with ImportProcessor
-    // The ImportProcessor would handle the actual file processing
+    // Use the ImportProcessor to actually process the import
+    const processor = new ImportProcessor();
+    const result = await processor.processImport(importId);
 
-    return {
-      success: true,
-      message: 'Import process started successfully',
-      importId
-    };
+    if (result.success) {
+      revalidatePath('/imports');
+      return {
+        success: true,
+        message: 'Import process completed successfully',
+        importId,
+        totalInserted: result.totalInserted
+      };
+    } else {
+      return {
+        success: false,
+        error: 'Import processing failed',
+        errors: result.errors
+      };
+    }
 
   } catch (error) {
     console.error('Error triggering import:', error);

+ 58 - 108
app/components/imports/ImportDetailDialog.tsx

@@ -6,18 +6,7 @@ import { Button } from '@/components/ui/button';
 import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
 import { format } from 'date-fns';
 import { useToast } from '@/hooks/use-toast';
-import { getImportById, calculateCintasSummaries, triggerImportProcess } from '@/app/actions/imports';
-
-interface CintasSummary {
-  id: number;
-  week: string;
-  trrTotal: number;
-  fourWkAverages: number;
-  trrPlus4Wk: number;
-  powerAdds: number;
-  weekId: number;
-  importId: number;
-}
+import { getImportById, triggerImportProcess, getImportProgress } from '@/app/actions/imports';
 
 interface ImportDetail {
   id: number;
@@ -44,13 +33,16 @@ interface ImportDetail {
       }>;
     }>;
   };
-  cintasSummaries: CintasSummary[];
   file?: {
     id: string;
     filename: string;
+    mimetype: string;
     size: number;
-    contentType: string;
-  };
+    data: Uint8Array;
+    userId: string | null;
+    createdAt: Date;
+    updatedAt: Date;
+  } | null;
 }
 
 interface ImportDetailDialogProps {
@@ -62,9 +54,11 @@ interface ImportDetailDialogProps {
 export function ImportDetailDialog({ open, onOpenChange, importId }: ImportDetailDialogProps) {
   const [importDetail, setImportDetail] = useState<ImportDetail | null>(null);
   const [loading, setLoading] = useState(true);
-  const [calculating, setCalculating] = useState(false);
   const [processing, setProcessing] = useState(false);
   const [importStatus, setImportStatus] = useState<'idle' | 'processing' | 'completed' | 'failed'>('idle');
+  const [progress, setProgress] = useState(0);
+  const [processedRecords, setProcessedRecords] = useState(0);
+  const [totalRecords, setTotalRecords] = useState(0);
   const { toast } = useToast();
 
   const loadImportDetail = useCallback(async () => {
@@ -98,34 +92,6 @@ export function ImportDetailDialog({ open, onOpenChange, importId }: ImportDetai
     }
   }, [open, importId, loadImportDetail]);
 
-  async function handleCalculateSummaries() {
-    setCalculating(true);
-    try {
-      const result = await calculateCintasSummaries(importId);
-      if (result.success) {
-        toast({
-          title: 'Success',
-          description: 'Cintas summaries calculated successfully',
-        });
-        loadImportDetail();
-      } else {
-        toast({
-          title: 'Error',
-          description: result.error || 'Failed to calculate summaries',
-          variant: 'destructive',
-        });
-      }
-    } catch {
-      toast({
-        title: 'Error',
-        description: 'Failed to calculate summaries',
-        variant: 'destructive',
-      });
-    } finally {
-      setCalculating(false);
-    }
-  }
-
   async function handleTriggerImport() {
     if (!importDetail?.file) {
       toast({
@@ -148,17 +114,46 @@ export function ImportDetailDialog({ open, onOpenChange, importId }: ImportDetai
           description: result.message || 'Import process started successfully',
         });
 
-        // For now, we'll simulate the processing completion
-        // In a real implementation, you might use polling or WebSocket
-        setTimeout(() => {
-          setImportStatus('completed');
-          setProcessing(false);
-          toast({
-            title: 'Import Complete',
-            description: 'Import process completed successfully',
-          });
-          loadImportDetail();
-        }, 2000);
+        // Poll for import progress until completion
+        const pollInterval = setInterval(async () => {
+          try {
+            const progressResult = await getImportProgress(importId);
+
+            if (progressResult.success && progressResult.data) {
+              const { status, progress, processedRecords, totalRecords } = progressResult.data;
+
+              // Update progress display
+              setProgress(progress);
+              setProcessedRecords(processedRecords);
+              setTotalRecords(totalRecords);
+
+              if (status === 'completed') {
+                clearInterval(pollInterval);
+                setProcessing(false);
+                setImportStatus('completed');
+                toast({
+                  title: 'Import Complete',
+                  description: `Successfully imported ${totalRecords} records`,
+                });
+                loadImportDetail();
+              } else if (status === 'failed') {
+                clearInterval(pollInterval);
+                setProcessing(false);
+                setImportStatus('failed');
+                toast({
+                  title: 'Import Failed',
+                  description: progressResult.data.errorMessage || 'Import processing failed',
+                  variant: 'destructive',
+                });
+              }
+            }
+          } catch (error) {
+            console.error('Error polling import progress:', error);
+            clearInterval(pollInterval);
+            setProcessing(false);
+            setImportStatus('failed');
+          }
+        }, 1000); // Poll every second
 
       } else {
         toast({
@@ -269,24 +264,14 @@ export function ImportDetailDialog({ open, onOpenChange, importId }: ImportDetai
             <CardHeader>
               <div className="flex justify-between items-center">
                 <CardTitle>Import Actions</CardTitle>
-                <div className="flex gap-2">
-                  <Button
-                    onClick={handleTriggerImport}
-                    disabled={processing || !importDetail.file}
-                    size="sm"
-                    variant="default"
-                  >
-                    {processing ? 'Processing...' : 'Start Import'}
-                  </Button>
-                  <Button
-                    onClick={handleCalculateSummaries}
-                    disabled={calculating || processing}
-                    size="sm"
-                    variant="secondary"
-                  >
-                    {calculating ? 'Calculating...' : 'Calculate Summaries'}
-                  </Button>
-                </div>
+                <Button
+                  onClick={handleTriggerImport}
+                  disabled={processing || !importDetail.file}
+                  size="sm"
+                  variant="default"
+                >
+                  {processing ? 'Processing...' : 'Start Import'}
+                </Button>
               </div>
             </CardHeader>
             <CardContent>
@@ -314,41 +299,6 @@ export function ImportDetailDialog({ open, onOpenChange, importId }: ImportDetai
             </CardContent>
           </Card>
 
-          <Card>
-            <CardHeader>
-              <CardTitle>Cintas Summaries</CardTitle>
-            </CardHeader>
-            <CardContent>
-              {importDetail.cintasSummaries.length === 0 ? (
-                <p className="text-muted-foreground">No summaries calculated yet</p>
-              ) : (
-                <div className="overflow-x-auto">
-                  <table className="w-full text-sm">
-                    <thead>
-                      <tr className="border-b">
-                        <th className="text-left py-2">Week</th>
-                        <th className="text-right py-2">TRR Total</th>
-                        <th className="text-right py-2">4WK Averages</th>
-                        <th className="text-right py-2">TRR + 4WK</th>
-                        <th className="text-right py-2">Power Adds</th>
-                      </tr>
-                    </thead>
-                    <tbody>
-                      {importDetail.cintasSummaries.map((summary) => (
-                        <tr key={summary.id} className="border-b">
-                          <td className="py-2">{summary.week}</td>
-                          <td className="text-right py-2">{summary.trrTotal}</td>
-                          <td className="text-right py-2">{summary.fourWkAverages}</td>
-                          <td className="text-right py-2">{summary.trrPlus4Wk}</td>
-                          <td className="text-right py-2">{summary.powerAdds}</td>
-                        </tr>
-                      ))}
-                    </tbody>
-                  </table>
-                </div>
-              )}
-            </CardContent>
-          </Card>
         </div>
 
         <div className="flex justify-end gap-2 mt-6">

+ 24 - 6
app/lib/excel-import/bulk-inserter.ts

@@ -29,13 +29,16 @@ export class BulkInserter {
         // Prepare data for insertion with proper field mapping
         const values = batch.map(row => {
           const mappedRow: any = {
-            importId: importId
+            importId: importId,
+            createdAt: new Date(),
+            updatedAt: new Date()
           };
 
           // Map the row data to match Prisma model field names
           Object.keys(row).forEach(key => {
             // Convert snake_case to camelCase for Prisma model compatibility
-            const camelKey = key.replace(/_([a-z])/g, (g) => g[1].toUpperCase());
+            // Also handle digits (e.g., corp_id_2 -> corpId2)
+            const camelKey = key.replace(/_([a-z0-9])/g, (g) => g[1].toUpperCase());
             mappedRow[camelKey] = row[key];
           });
 
@@ -48,11 +51,26 @@ export class BulkInserter {
             data: values,
             skipDuplicates: false
           });
-        } else if (tableName === 'cintas_install_calendar_summary') {
+        } else if (tableName === 'cintas_install_calendar_summary' || tableName === 'cintas_intall_calendar_summary') {
           await this.prisma.cintasSummary.createMany({
             data: values,
             skipDuplicates: false
           });
+        } else if (tableName === 'gow_data') {
+          await this.prisma.gowData.createMany({
+            data: values,
+            skipDuplicates: false
+          });
+        } else if (tableName === 'gow_fac_id') {
+          await this.prisma.gowFacId.createMany({
+            data: values,
+            skipDuplicates: false
+          });
+        } else if (tableName === 'gow_corp_ref') {
+          await this.prisma.gowCorpRef.createMany({
+            data: values,
+            skipDuplicates: false
+          });
         } else {
           // Fallback to raw SQL for other tables
           await this.prisma.$executeRawUnsafe(
@@ -76,7 +94,7 @@ export class BulkInserter {
     if (values.length === 0) return '';
 
     const keys = Object.keys(values[0]);
-    const columns = keys.join(', ');
+    const columns = keys.map(key => `"${key}"`).join(', ');
 
     const placeholders = values.map(row => {
       const valuesList = keys.map(key => {
@@ -106,9 +124,9 @@ export class BulkInserter {
       const createTableQuery = `
         CREATE TABLE IF NOT EXISTS "${tableName}" (
           id SERIAL PRIMARY KEY,
-          import_id INTEGER NOT NULL,
+          "importId" INTEGER NOT NULL,
           ${columns},
-          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+          "createdAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
         )
       `;
 

+ 80 - 0
prisma/migrations/20260202233207_update_gow_tables/migration.sql

@@ -0,0 +1,80 @@
+/*
+  Warnings:
+
+  - You are about to drop the column `createdAt` on the `gow_corp_ref` table. All the data in the column will be lost.
+  - You are about to drop the column `updatedAt` on the `gow_corp_ref` table. All the data in the column will be lost.
+  - You are about to drop the column `corpId` on the `gow_data` table. All the data in the column will be lost.
+  - You are about to drop the column `createdAt` on the `gow_data` table. All the data in the column will be lost.
+  - You are about to drop the column `updatedAt` on the `gow_data` table. All the data in the column will be lost.
+  - You are about to drop the column `createdAt` on the `gow_fac_id` table. All the data in the column will be lost.
+  - You are about to drop the column `updatedAt` on the `gow_fac_id` table. All the data in the column will be lost.
+  - Added the required column `updated_at` to the `gow_corp_ref` table without a default value. This is not possible if the table is not empty.
+  - Added the required column `updated_at` to the `gow_data` table without a default value. This is not possible if the table is not empty.
+  - Added the required column `updated_at` to the `gow_fac_id` table without a default value. This is not possible if the table is not empty.
+
+*/
+-- AlterTable
+ALTER TABLE "gow_corp_ref" DROP COLUMN "createdAt",
+DROP COLUMN "updatedAt",
+ADD COLUMN     "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ADD COLUMN     "updated_at" TIMESTAMP(3) NOT NULL,
+ALTER COLUMN "well_name" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "api_no" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "corporate_id" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "current_well_status" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "county_parish" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "state" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "area" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "completion_date" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "pop_first_production" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "operator" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "abandon_date" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "battery" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "common_pad_name" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "id_well" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "lease_id" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "latitude" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "longitude" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "pad_code" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "pad_name" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "permit_number" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "well_sub_status" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "shut_in_date" SET DATA TYPE VARCHAR(4000);
+
+-- AlterTable
+ALTER TABLE "gow_data" DROP COLUMN "corpId",
+DROP COLUMN "createdAt",
+DROP COLUMN "updatedAt",
+ADD COLUMN     "corp_id" VARCHAR(4000),
+ADD COLUMN     "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ADD COLUMN     "updated_at" TIMESTAMP(3) NOT NULL,
+ALTER COLUMN "well_name" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "month" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "completion_type" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "state" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "days_on" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "gas_production" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "gas_sales" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "oil_production" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "oil_sales" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "water_production" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "operator" SET DATA TYPE VARCHAR(4000);
+
+-- AlterTable
+ALTER TABLE "gow_fac_id" DROP COLUMN "createdAt",
+DROP COLUMN "updatedAt",
+ADD COLUMN     "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ADD COLUMN     "updated_at" TIMESTAMP(3) NOT NULL,
+ALTER COLUMN "corp_id" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "odeq_fac_id" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "odeq_facility_name" SET DATA TYPE VARCHAR(4000),
+ALTER COLUMN "corp_id_2" SET DATA TYPE VARCHAR(4000);
+
+-- AddForeignKey
+ALTER TABLE "gow_fac_id" ADD CONSTRAINT "gow_fac_id_import_id_fkey" FOREIGN KEY ("import_id") REFERENCES "imports"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "gow_data" ADD CONSTRAINT "gow_data_import_id_fkey" FOREIGN KEY ("import_id") REFERENCES "imports"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "gow_corp_ref" ADD CONSTRAINT "gow_corp_ref_import_id_fkey" FOREIGN KEY ("import_id") REFERENCES "imports"("id") ON DELETE CASCADE ON UPDATE CASCADE;

+ 66 - 0
prisma/migrations/20260202235000_recreate_gow_tables/migration.sql

@@ -0,0 +1,66 @@
+-- Drop existing tables with CASCADE to handle any dependencies
+DROP TABLE IF EXISTS "gow_corp_ref" CASCADE;
+DROP TABLE IF EXISTS "gow_data" CASCADE;
+DROP TABLE IF EXISTS "gow_fac_id" CASCADE;
+
+-- Recreate gow_fac_id table
+CREATE TABLE "gow_fac_id" (
+    id                 SERIAL PRIMARY KEY,
+    "importId"         INTEGER NOT NULL REFERENCES imports ON UPDATE CASCADE ON DELETE CASCADE,
+    "corp_id" VARCHAR(4000),
+    "odeq_fac_id" VARCHAR(4000),
+    "odeq_facility_name" VARCHAR(4000),
+    "corp_id_2" VARCHAR(4000),
+    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+    "updatedAt" TIMESTAMP(3) NOT NULL
+);
+
+-- Recreate gow_data table
+CREATE TABLE "gow_data" (
+    id                 SERIAL PRIMARY KEY,
+    "importId"         INTEGER NOT NULL REFERENCES imports ON UPDATE CASCADE ON DELETE CASCADE,
+    "well_name" VARCHAR(4000),
+    "month" VARCHAR(4000),
+    "corpId" VARCHAR(4000),
+    "completion_type" VARCHAR(4000),
+    "state" VARCHAR(4000),
+    "days_on" VARCHAR(4000),
+    "gas_production" VARCHAR(4000),
+    "gas_sales" VARCHAR(4000),
+    "oil_production" VARCHAR(4000),
+    "oil_sales" VARCHAR(4000),
+    "water_production" VARCHAR(4000),
+    "operator" VARCHAR(4000),
+    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+    "updatedAt" TIMESTAMP(3) NOT NULL
+);
+
+-- Recreate gow_corp_ref table
+CREATE TABLE "gow_corp_ref" (
+    id                 SERIAL PRIMARY KEY,
+    "importId"         INTEGER NOT NULL REFERENCES imports ON UPDATE CASCADE ON DELETE CASCADE,
+    "well_name" VARCHAR(4000),
+    "api_no" VARCHAR(4000),
+    "corporate_id" VARCHAR(4000),
+    "current_well_status" VARCHAR(4000),
+    "county_parish" VARCHAR(4000),
+    "state" VARCHAR(4000),
+    "area" VARCHAR(4000),
+    "completion_date" VARCHAR(4000),
+    "pop_first_production" VARCHAR(4000),
+    "operator" VARCHAR(4000),
+    "abandon_date" VARCHAR(4000),
+    "battery" VARCHAR(4000),
+    "common_pad_name" VARCHAR(4000),
+    "id_well" VARCHAR(4000),
+    "lease_id" VARCHAR(4000),
+    "latitude" VARCHAR(4000),
+    "longitude" VARCHAR(4000),
+    "pad_code" VARCHAR(4000),
+    "pad_name" VARCHAR(4000),
+    "permit_number" VARCHAR(4000),
+    "well_sub_status" VARCHAR(4000),
+    "shut_in_date" VARCHAR(4000),
+    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+    "updatedAt" TIMESTAMP(3) NOT NULL
+);

+ 58 - 52
prisma/schema.prisma

@@ -1,5 +1,5 @@
 // This is your Prisma schema file,
-// learn more about it in the docs: https://pris.ly/d/prisma-schema
+// learn more about it in the docs: https://pris.ly/d/prisma schema
 
 generator client {
   provider = "prisma-client-js"
@@ -86,7 +86,10 @@ model Import {
   createdAt  DateTime @default(now())
   updatedAt  DateTime @updatedAt
 
-  cintasSummaries      CintasSummary[]
+  gowFacIds      GowFacId[]
+  gowData        GowData[]
+  gowCorpRefs    GowCorpRef[]
+  cintasSummaries CintasSummary[]
   cintasInstallCalendar CintasInstallCalendar[]
 
   @@map("imports")
@@ -174,66 +177,69 @@ model SiteInfoLeakComponents {
 }
 
 model GowFacId {
-  id            Int      @id @default(autoincrement())
-  importId      Int      @map("import_id")
-  corpId        String?  @map("corp_id") @db.VarChar(1000)
-  odeqFacId     String?  @map("odeq_fac_id") @db.VarChar(1000)
-  odeqFacilityName String? @map("odeq_facility_name") @db.VarChar(1000)
-  corpId2       String?  @map("corp_id_2") @db.VarChar(1000)
-  createdAt     DateTime @default(now())
-  updatedAt     DateTime @updatedAt
+  id               Int      @id @default(autoincrement())
+  importId         Int      @map("importId")
+  import           Import   @relation(fields: [importId], references: [id], onDelete: Cascade, onUpdate: Cascade)
+  corpId           String?  @map("corp_id") @db.VarChar(4000)
+  odeqFacId        String?  @map("odeq_fac_id") @db.VarChar(4000)
+  odeqFacilityName String?  @map("odeq_facility_name") @db.VarChar(4000)
+  corpId2          String?  @map("corp_id_2") @db.VarChar(4000)
+  createdAt        DateTime @default(now()) @map("createdAt")
+  updatedAt        DateTime @updatedAt @map("updatedAt")
 
   @@map("gow_fac_id")
 }
 
 model GowData {
-  id               Int      @id @default(autoincrement())
-  importId         Int      @map("import_id")
-  wellName         String?  @map("well_name") @db.VarChar(1000)
-  month            String?  @db.VarChar(1000)
-  corpId           String?  @db.VarChar(1000)
-  completionType   String?  @map("completion_type") @db.VarChar(1000)
-  state            String?  @db.VarChar(1000)
-  daysOn           String?  @map("days_on") @db.VarChar(1000)
-  gasProduction    String?  @map("gas_production") @db.VarChar(1000)
-  gasSales         String?  @map("gas_sales") @db.VarChar(1000)
-  oilProduction    String?  @map("oil_production") @db.VarChar(1000)
-  oilSales         String?  @map("oil_sales") @db.VarChar(1000)
-  waterProduction  String?  @map("water_production") @db.VarChar(1000)
-  operator         String?  @db.VarChar(1000)
-  createdAt        DateTime @default(now())
-  updatedAt        DateTime @updatedAt
+  id              Int      @id @default(autoincrement())
+  importId        Int      @map("importId")
+  import          Import   @relation(fields: [importId], references: [id], onDelete: Cascade, onUpdate: Cascade)
+  wellName        String?  @map("well_name") @db.VarChar(4000)
+  month           String?  @db.VarChar(4000)
+  corpId          String?  @map("corpId") @db.VarChar(4000)
+  completionType  String?  @map("completion_type") @db.VarChar(4000)
+  state           String?  @db.VarChar(4000)
+  daysOn          String?  @map("days_on") @db.VarChar(4000)
+  gasProduction   String?  @map("gas_production") @db.VarChar(4000)
+  gasSales        String?  @map("gas_sales") @db.VarChar(4000)
+  oilProduction   String?  @map("oil_production") @db.VarChar(4000)
+  oilSales        String?  @map("oil_sales") @db.VarChar(4000)
+  waterProduction String?  @map("water_production") @db.VarChar(4000)
+  operator        String?  @db.VarChar(4000)
+  createdAt       DateTime @default(now()) @map("createdAt")
+  updatedAt       DateTime @updatedAt @map("updatedAt")
 
   @@map("gow_data")
 }
 
 model GowCorpRef {
-  id                   Int      @id @default(autoincrement())
-  importId            Int      @map("import_id")
-  wellName            String?  @map("well_name") @db.VarChar(1000)
-  apiNo               String?  @map("api_no") @db.VarChar(1000)
-  corporateId         String?  @map("corporate_id") @db.VarChar(1000)
-  currentWellStatus   String?  @map("current_well_status") @db.VarChar(1000)
-  countyParish        String?  @map("county_parish") @db.VarChar(1000)
-  state               String?  @db.VarChar(1000)
-  area                String?  @db.VarChar(1000)
-  completionDate      String?  @map("completion_date") @db.VarChar(1000)
-  popFirstProduction  String?  @map("pop_first_production") @db.VarChar(1000)
-  operator            String?  @db.VarChar(1000)
-  abandonDate         String?  @map("abandon_date") @db.VarChar(1000)
-  battery             String?  @db.VarChar(1000)
-  commonPadName       String?  @map("common_pad_name") @db.VarChar(1000)
-  idWell              String?  @map("id_well") @db.VarChar(1000)
-  leaseId             String?  @map("lease_id") @db.VarChar(1000)
-  latitude            String?  @db.VarChar(1000)
-  longitude           String?  @db.VarChar(1000)
-  padCode             String?  @map("pad_code") @db.VarChar(1000)
-  padName             String?  @map("pad_name") @db.VarChar(1000)
-  permitNumber        String?  @map("permit_number") @db.VarChar(1000)
-  wellSubStatus       String?  @map("well_sub_status") @db.VarChar(1000)
-  shutInDate          String?  @map("shut_in_date") @db.VarChar(1000)
-  createdAt           DateTime @default(now())
-  updatedAt           DateTime @updatedAt
+  id                 Int      @id @default(autoincrement())
+  importId           Int      @map("importId")
+  import             Import   @relation(fields: [importId], references: [id], onDelete: Cascade, onUpdate: Cascade)
+  wellName           String?  @map("well_name") @db.VarChar(4000)
+  apiNo              String?  @map("api_no") @db.VarChar(4000)
+  corporateId        String?  @map("corporate_id") @db.VarChar(4000)
+  currentWellStatus  String?  @map("current_well_status") @db.VarChar(4000)
+  countyParish       String?  @map("county_parish") @db.VarChar(4000)
+  state              String?  @db.VarChar(4000)
+  area               String?  @db.VarChar(4000)
+  completionDate     String?  @map("completion_date") @db.VarChar(4000)
+  popFirstProduction String?  @map("pop_first_production") @db.VarChar(4000)
+  operator           String?  @db.VarChar(4000)
+  abandonDate        String?  @map("abandon_date") @db.VarChar(4000)
+  battery            String?  @db.VarChar(4000)
+  commonPadName      String?  @map("common_pad_name") @db.VarChar(4000)
+  idWell             String?  @map("id_well") @db.VarChar(4000)
+  leaseId            String?  @map("lease_id") @db.VarChar(4000)
+  latitude           String?  @db.VarChar(4000)
+  longitude          String?  @db.VarChar(4000)
+  padCode            String?  @map("pad_code") @db.VarChar(4000)
+  padName            String?  @map("pad_name") @db.VarChar(4000)
+  permitNumber       String?  @map("permit_number") @db.VarChar(4000)
+  wellSubStatus      String?  @map("well_sub_status") @db.VarChar(4000)
+  shutInDate         String?  @map("shut_in_date") @db.VarChar(4000)
+  createdAt          DateTime @default(now()) @map("createdAt")
+  updatedAt          DateTime @updatedAt @map("updatedAt")
 
   @@map("gow_corp_ref")
 }