Compare commits

...

2 Commits

Author SHA1 Message Date
9116876f7b API Rewrite 2024-06-13 14:27:36 -05:00
0a1250dfd2 API Listing half-rewrite 2024-06-12 14:28:13 -05:00
4 changed files with 291 additions and 45 deletions

View File

@ -3,6 +3,7 @@ version: '3'
services:
fbla_api:
image: fbla-api
restart: unless-stopped
ports:
- "8000:8000"
volumes:

View File

@ -22,47 +22,37 @@ enum BusinessType {
other,
}
enum JobType { cashier, server, mechanic, other }
class Business {
int id;
String name;
String description;
BusinessType type;
String website;
String contactName;
String contactEmail;
String contactPhone;
String notes;
String locationName;
String locationAddress;
String? website;
String? contactName;
String? contactEmail;
String? contactPhone;
String? notes;
String? locationName;
String? locationAddress;
Business({
required this.id,
required this.name,
required this.description,
required this.type,
required this.website,
required this.contactName,
required this.contactEmail,
required this.contactPhone,
required this.notes,
required this.locationName,
required this.locationAddress,
});
Business(
{required this.id,
required this.name,
required this.description,
this.website,
this.contactName,
this.contactEmail,
this.contactPhone,
this.notes,
this.locationName,
this.locationAddress});
factory Business.fromJson(Map<String, dynamic> json) {
bool typeValid = true;
try {
BusinessType.values.byName(json['type']);
} catch (e) {
typeValid = false;
}
return Business(
id: json['id'],
name: json['name'],
description: json['description'],
type: typeValid
? BusinessType.values.byName(json['type'])
: BusinessType.other,
website: json['website'],
contactName: json['contactName'],
contactEmail: json['contactEmail'],
@ -74,6 +64,44 @@ class Business {
}
}
class JobListing {
String? id;
String? businessId;
String name;
String description;
JobType type;
String? wage;
String? link;
JobListing(
{this.id,
this.businessId,
required this.name,
required this.description,
required this.type,
this.wage,
this.link});
factory JobListing.fromJson(Map<String, dynamic> json) {
bool typeValid = true;
try {
JobType.values.byName(json['type']);
} catch (e) {
typeValid = false;
}
return JobListing(
id: json['id'],
businessId: json['businessId'],
name: json['name'],
description: json['description'],
type: typeValid ? JobType.values.byName(json['type']) : JobType.other,
wage: json['wage'],
link: json['link'],
);
}
}
Future<String> fetchBusinessData() async {
final result = await postgres.query('''
SELECT json_agg(
@ -93,9 +121,7 @@ Future<String> fetchBusinessData() async {
) FROM businesses
''');
var encoded = json.encode(result);
var decoded = json.decode(encoded);
encoded = json.encode(decoded[0][0]);
var encoded = json.encode(result[0][0]);
return encoded;
}
@ -125,12 +151,95 @@ void main() async {
headers: {'Access-Control-Allow-Origin': '*'},
);
});
app.get('/fbla-api/businessdata/overview', (Request request) async {
print('business overview request received');
var filters = request.url.queryParameters['filters']?.split(',') ??
JobType.values.asNameMap().keys;
// List<Map<String, List<Map<String, dynamic>>>> this is the real type lol
List<dynamic> output = [];
for (int i = 0; i < filters.length; i++) {
var postgresResult = (await postgres.query('''
SELECT json_agg(
json_build_object(
'id', id,
'name', name,
'description', description,
'website', website,
'contactEmail', "contactEmail",
'contactPhone', "contactPhone",
'locationName', "locationName"
)
) FROM public.businesses WHERE id IN (SELECT "businessId" FROM public.listings WHERE type='${filters.elementAt(i)}')
'''))[0][0];
if (postgresResult != null) {
output.add({filters.elementAt(i): postgresResult});
}
}
return Response.ok(
json.encode(output),
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'text/plain'
},
);
});
app.get('/fbla-api/businessdata/business/<business>',
(Request request, String business) async {
print('idividual business data request received');
var result = (await postgres.query('''
SELECT
json_build_object(
'id', b.id,
'name', b.name,
'description', b.description,
'website', b.website,
'contactName', b."contactName",
'contactEmail', b."contactEmail",
'contactPhone', b."contactPhone",
'notes', b.notes,
'locationName', b."locationName",
'locationAddress', b."locationAddress",
'listings',
json_agg(
json_build_object(
'id', l.id,
'name', l.name,
'description', l.description,
'type', l.type,
'wage', l.wage,
'link', l.link
)
)
)
FROM businesses b
LEFT JOIN listings l ON b.id = l.business_id
WHERE b.id = $business
GROUP BY b.id;
'''))[0][0];
return Response.ok(
json.encode(result),
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'text/plain'
},
);
});
app.get('/fbla-api/businessdata', (Request request) async {
print('business data request received');
final output = await fetchBusinessData();
return Response.ok(
output.toString(),
headers: {'Access-Control-Allow-Origin': '*'},
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'text/plain'
},
);
});
app.get('/fbla-api/logos/<logo>', (Request request, String logoId) {
@ -158,8 +267,8 @@ void main() async {
Business business = Business.fromJson(json);
await postgres.query('''
INSERT INTO businesses (name, description, type, website, "contactName", "contactPhone", "contactEmail", notes, "locationName", "locationAddress")
VALUES ('${business.name.replaceAll("'", "''")}', '${business.description.replaceAll("'", "''")}', '${business.type.name}', '${business.website}', '${business.contactName.replaceAll("'", "''")}', '${business.contactPhone}', '${business.contactEmail}', '${business.notes.replaceAll("'", "''")}', '${business.locationName.replaceAll("'", "''")}', '${business.locationAddress.replaceAll("'", "''")}')
INSERT INTO businesses (name, description, website, "contactName", "contactPhone", "contactEmail", notes, "locationName", "locationAddress")
VALUES ('${business.name.replaceAll("'", "''")}', '${business.description.replaceAll("'", "''")}', '${business.website ?? 'NULL'}', '${business.contactName?.replaceAll("'", "''") ?? 'NULL'}', '${business.contactPhone ?? 'NULL'}', '${business.contactEmail ?? 'NULL'}', '${business.notes?.replaceAll("'", "''") ?? 'NULL'}', '${business.locationName?.replaceAll("'", "''") ?? 'NULL'}', '${business.locationAddress?.replaceAll("'", "''") ?? 'NULL'}')
''');
final dbBusiness = await postgres.query('''SELECT * FROM public.businesses
@ -187,6 +296,40 @@ void main() async {
headers: {'Access-Control-Allow-Origin': '*'},
);
});
app.post('/fbla-api/createlisting', (Request request) async {
print('create business request received');
final payload = await request.readAsString();
var auth = request.headers['Authorization']?.replaceAll('Bearer ', '');
try {
JWT.verify(auth!, secretKey);
var json = jsonDecode(payload);
JobListing listing = JobListing.fromJson(json);
await postgres.query('''
INSERT INTO listings ("businessId", name, description, type, wage, link)
VALUES ('${listing.businessId}' '${listing.name.replaceAll("'", "''")}', '${listing.description.replaceAll("'", "''")}', '${listing.type.name}', '${listing.wage ?? 'NULL'}', '${listing.link?.replaceAll("'", "''") ?? 'NULL'}')
''');
final dbListing = await postgres.query('''SELECT id FROM public.listings
ORDER BY id DESC LIMIT 1''');
var id = dbListing[0][0];
return Response.ok(
id.toString(),
headers: {'Access-Control-Allow-Origin': '*'},
);
} on JWTExpiredException {
print('JWT Expired');
} on JWTException catch (e) {
print(e.message);
}
return Response.unauthorized(
'unauthorized',
headers: {'Access-Control-Allow-Origin': '*'},
);
});
app.post('/fbla-api/deletebusiness', (Request request) async {
print('delete business request received');
@ -197,11 +340,7 @@ void main() async {
var json = jsonDecode(payload);
var id = json['id'];
await postgres.query('''
DELETE FROM public.businesses
WHERE id IN
($id);
''');
await postgres.query('DELETE FROM public.business WHERE id=$id;');
try {
await File('logos/$id.png').delete();
@ -224,6 +363,33 @@ void main() async {
headers: {'Access-Control-Allow-Origin': '*'},
);
});
app.post('/fbla-api/deletelisting', (Request request) async {
print('delete listing request received');
final payload = await request.readAsString();
var auth = request.headers['Authorization']?.replaceAll('Bearer ', '');
try {
JWT.verify(auth!, secretKey);
var json = jsonDecode(payload);
var id = json['id'];
await postgres.query('DELETE FROM public.listings WHERE id=$id;');
return Response.ok(
id.toString(),
headers: {'Access-Control-Allow-Origin': '*'},
);
} on JWTExpiredException {
print('JWT Expired');
} on JWTException catch (e) {
print(e.message);
}
return Response.unauthorized(
'unauthorized',
headers: {'Access-Control-Allow-Origin': '*'},
);
});
app.post('/fbla-api/editbusiness', (Request request) async {
print('edit business request received');
@ -237,7 +403,7 @@ void main() async {
await postgres.query('''
UPDATE businesses SET
name = '${business.name.replaceAll("'", "''").replaceAll("\"", "\"\"")}'::text, description = '${business.description.replaceAll("'", "''").replaceAll("\"", "\"\"")}'::text, website = '${business.website}'::text, type = '${business.type.name}'::text, "contactName" = '${business.contactName.replaceAll("'", "''").replaceAll("\"", "\"\"")}'::text, "contactPhone" = '${business.contactPhone}'::text, "contactEmail" = '${business.contactEmail}'::text, notes = '${business.notes.replaceAll("'", "''").replaceAll("\"", "\"\"")}'::text, "locationName" = '${business.locationName.replaceAll("'", "''").replaceAll("\"", "\"\"")}'::text, "locationAddress" = '${business.locationAddress.replaceAll("'", "''").replaceAll("\"", "\"\"")}'::text WHERE
name = '${business.name.replaceAll("'", "''").replaceAll("\"", "\"\"")}'::text, description = '${business.description.replaceAll("'", "''").replaceAll("\"", "\"\"")}'::text, website = '${business.website!}'::text, "contactName" = '${business.contactName!.replaceAll("'", "''").replaceAll("\"", "\"\"")}'::text, "contactPhone" = '${business.contactPhone!}'::text, "contactEmail" = '${business.contactEmail!}'::text, notes = '${business.notes!.replaceAll("'", "''").replaceAll("\"", "\"\"")}'::text, "locationName" = '${business.locationName!.replaceAll("'", "''").replaceAll("\"", "\"\"")}'::text, "locationAddress" = '${business.locationAddress!.replaceAll("'", "''").replaceAll("\"", "\"\"")}'::text WHERE
id = ${business.id};
''');
@ -270,6 +436,38 @@ void main() async {
headers: {'Access-Control-Allow-Origin': '*'},
);
});
app.post('/fbla-api/editlisting', (Request request) async {
print('edit listing request received');
final payload = await request.readAsString();
var auth = request.headers['Authorization']?.replaceAll('Bearer ', '');
try {
JWT.verify(auth!, secretKey);
var json = jsonDecode(payload);
JobListing listing = JobListing.fromJson(json);
await postgres.query('''
UPDATE listings SET
"businessId" = ${listing.businessId}, name = '${listing.name.replaceAll("'", "''")}'::text, description = '${listing.description.replaceAll("'", "''")}'::text, type = '${listing.type.name}'::text, wage = '${listing.wage ?? 'NULL'}'::text, link = '${listing.link?.replaceAll("'", "''") ?? 'NULL'}'::text WHERE
id = ${listing.id};
''');
return Response.ok(
listing.id.toString(),
headers: {'Access-Control-Allow-Origin': '*'},
);
} on JWTExpiredException {
print('JWT Expired');
} on JWTException catch (e) {
print(e.message);
}
return Response.unauthorized(
'unauthorized',
headers: {'Access-Control-Allow-Origin': '*'},
);
});
app.post('/fbla-api/signin', (Request request) async {
print('signin request received');

View File

@ -81,7 +81,6 @@ void main() async {
"id": 0,
"name": "tmp",
"description": "tmp",
"type": "business",
"website": "tmp",
"contactName": "tmp",
"contactEmail": "tmp",

View File

@ -26,6 +26,7 @@ class _CreateBusinessDetailState extends State<BusinessDetail> {
),
body: ListView(
children: [
// Title, logo, desc, website
Card(
clipBehavior: Clip.antiAlias,
child: Column(
@ -41,8 +42,7 @@ class _CreateBusinessDetailState extends State<BusinessDetail> {
),
leading: ClipRRect(
borderRadius: BorderRadius.circular(6.0),
child: Image.network(
'$apiAddress/logos/${business.id}',
child: Image.network('$apiAddress/logos/${business.id}',
width: 48,
height: 48, errorBuilder: (BuildContext context,
Object exception, StackTrace? stackTrace) {
@ -63,6 +63,52 @@ class _CreateBusinessDetailState extends State<BusinessDetail> {
],
),
),
// Available positions
Card(
child: Padding(
padding: const EdgeInsets.only(left: 16.0, top: 8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Available Postitions',
style: const TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
// Container(
// height: 400,
// width: 300,
ListView(
scrollDirection: Axis.vertical,
shrinkWrap: true,
children: [
ListTile(
title: Text('Postition 1'),
leading: Icon(Icons.work),
onTap: () {
// launchUrl(Uri.parse(''));
},
),
ListTile(
title: Text('Postition 2'),
leading: Icon(Icons.work),
onTap: () {
// launchUrl(Uri.parse(''));
},
),
ListTile(
title: Text('Postition 3'),
leading: Icon(Icons.work),
onTap: () {
// launchUrl(Uri.parse(''));
},
),
],
),
]),
),
),
// Contact info
Visibility(
visible: (business.contactEmail.isNotEmpty ||
business.contactPhone.isNotEmpty),
@ -138,6 +184,7 @@ class _CreateBusinessDetailState extends State<BusinessDetail> {
),
),
),
// Location
Visibility(
child: Card(
clipBehavior: Clip.antiAlias,
@ -152,6 +199,7 @@ class _CreateBusinessDetailState extends State<BusinessDetail> {
),
),
),
// Notes
Visibility(
visible: business.notes.isNotEmpty,
child: Card(