@@ -51,35 +51,80 @@ export async function POST(req: NextRequest) {
5151 return NextResponse . json ( { error : 'Not a member of this organization' } , { status : 403 } ) ;
5252 }
5353
54- // Upsert device: if same serial number + org exists, update; otherwise create
55- const device = await db . device . upsert ( {
56- where : {
57- serialNumber_organizationId : {
58- serialNumber : serialNumber ?? '' ,
54+ // Branch on serialNumber to avoid collisions for serial-less devices.
55+ // PostgreSQL treats NULLs as distinct in unique constraints, so devices
56+ // without a serial number can safely coexist in the same org.
57+ let device ;
58+
59+ if ( serialNumber ) {
60+ // Serial number present — upsert on the unique (serialNumber, organizationId) key
61+ device = await db . device . upsert ( {
62+ where : {
63+ serialNumber_organizationId : {
64+ serialNumber,
65+ organizationId,
66+ } ,
67+ } ,
68+ update : {
69+ name,
70+ hostname,
71+ platform,
72+ osVersion,
73+ hardwareModel,
74+ agentVersion,
75+ userId : session . user . id ,
76+ } ,
77+ create : {
78+ name,
79+ hostname,
80+ platform,
81+ osVersion,
82+ serialNumber,
83+ hardwareModel,
84+ agentVersion,
85+ userId : session . user . id ,
5986 organizationId,
6087 } ,
61- } ,
62- update : {
63- name,
64- hostname,
65- platform,
66- osVersion,
67- hardwareModel,
68- agentVersion,
69- userId : session . user . id ,
70- } ,
71- create : {
72- name,
73- hostname,
74- platform,
75- osVersion,
76- serialNumber,
77- hardwareModel,
78- agentVersion,
79- userId : session . user . id ,
80- organizationId,
81- } ,
82- } ) ;
88+ } ) ;
89+ } else {
90+ // No serial number — find by hostname + userId + org (same user re-registering
91+ // the same machine), or create a new record with serialNumber = null.
92+ const existing = await db . device . findFirst ( {
93+ where : {
94+ hostname,
95+ userId : session . user . id ,
96+ organizationId,
97+ serialNumber : null ,
98+ } ,
99+ } ) ;
100+
101+ if ( existing ) {
102+ device = await db . device . update ( {
103+ where : { id : existing . id } ,
104+ data : {
105+ name,
106+ platform,
107+ osVersion,
108+ hardwareModel,
109+ agentVersion,
110+ } ,
111+ } ) ;
112+ } else {
113+ device = await db . device . create ( {
114+ data : {
115+ name,
116+ hostname,
117+ platform,
118+ osVersion,
119+ serialNumber : null ,
120+ hardwareModel,
121+ agentVersion,
122+ userId : session . user . id ,
123+ organizationId,
124+ } ,
125+ } ) ;
126+ }
127+ }
83128
84129 return NextResponse . json ( { deviceId : device . id } ) ;
85130 } catch ( error ) {
0 commit comments