Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Release #139 #155 #156 #157 #159 #161 #164 #165 #166

Merged
merged 32 commits into from
Apr 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
a7d094b
Limit site area to 1 million hectares during creation
dhakalaashish Feb 2, 2024
eff31df
react-native-auth0 v2 - v3 migration
dhakalaashish Feb 15, 2024
ec335b1
Add whatsapp to nativeapp
dhakalaashish Feb 15, 2024
340c8ac
limit area to be 1e10 meters
dhakalaashish Feb 19, 2024
42e220d
Merge pull request #139 from Plant-for-the-Planet-org/feature/limit-s…
dhakalaashish Feb 20, 2024
4daf772
Upgrade Prisma to 5.10.1
dhakalaashish Feb 21, 2024
15cf06b
Upgrate Prisma to 5.10.2
dhakalaashish Feb 22, 2024
e4c1948
Update stats.lastUpdated on upsert
dhakalaashish Feb 22, 2024
54025ad
Server: Restrict WhatsApp for Indian Phone Numbers
dhakalaashish Feb 20, 2024
5b3b5a2
Nativeapp: Restrict WhatsApp for Indian Phone Numbers
dhakalaashish Feb 20, 2024
c242a88
Update Error Message
dhakalaashish Feb 23, 2024
c4decf7
Merge branch 'develop' of github.com:Plant-for-the-Planet-org/FireAle…
dhakalaashish Feb 26, 2024
372a0bc
Update dev-test whatsapp api
dhakalaashish Feb 26, 2024
dbd5f7a
Resolve nativeapp PR Issues
dhakalaashish Feb 27, 2024
15fd140
Merge pull request #155 from Plant-for-the-Planet-org/feature/fix-las…
dhakalaashish Feb 27, 2024
642ba35
Merge pull request #156 from Plant-for-the-Planet-org/feature/upgrade…
dhakalaashish Feb 27, 2024
7e75f22
Merge branch 'develop' into feature/add-whatsapp-nativeapp
dhakalaashish Feb 27, 2024
10608f8
Merge pull request #157 from Plant-for-the-Planet-org/feature/add-wha…
dhakalaashish Feb 27, 2024
9150577
Avoid device duplication in createAlertMethod
dhakalaashish Mar 4, 2024
6196519
Edit location in email template
dhakalaashish Mar 5, 2024
a1ac4f9
Expand slice 4 and 5
dhakalaashish Mar 8, 2024
476b0ea
Update create-postgis-triggers.sql
dhakalaashish Mar 11, 2024
38e1204
Update geoslice.png
dhakalaashish Mar 11, 2024
eeb1156
Divide Slice 2,3,4,5 and 6 into 3 vertical zones
dhakalaashish Mar 21, 2024
ee8ee0d
Divide slices for equal landmass
dhakalaashish Mar 21, 2024
453316c
Merge pull request #161 from Plant-for-the-Planet-org/feature/expand-…
dhakalaashish Mar 29, 2024
e2f1a5c
Create Site and SiteAlert View SQL migration
dhakalaashish Apr 4, 2024
b40d9a2
Merge pull request #164 from Plant-for-the-Planet-org/feature/create-…
sagararyal Apr 4, 2024
2f2a36c
Merge pull request #165 from Plant-for-the-Planet-org/feature/edit-pp…
sagararyal Apr 4, 2024
9275da1
Prevents duplicate devices alertMethod
dhakalaashish Apr 4, 2024
bde27e2
Update alertMethod.ts
dhakalaashish Apr 4, 2024
f09a833
Merge pull request #159 from Plant-for-the-Planet-org/feature/prevent…
dhakalaashish Apr 4, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions apps/nativeapp/app/components/phoneInput/PhoneInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import PhoneNoInput from 'react-native-phone-number-input';
import {CountryCode} from 'react-native-country-picker-modal';

import {Colors, Typography} from '../../styles';
import {EXCLUDED_COUNTRIES} from '../../constants';
import {DISABLE_SMS_COUNTRY_CODE , DISABLE_WHATSAPP_COUNTRY_CODE} from '../../constants';

const IS_ANDROID = Platform.OS === 'android';

Expand Down Expand Up @@ -37,10 +37,13 @@ const PhoneInput = ({
const countryCode = phoneInput.current?.getCountryCode(value);
valid(checkValid ? checkValid : false);
inputValue(formattedValue);
if (
verificationType === 'Sms' &&
EXCLUDED_COUNTRIES.includes(countryCode)
) {
if ((
verificationType === 'Sms' &&
DISABLE_SMS_COUNTRY_CODE.includes(countryCode)
) || (
verificationType === 'Whatsapp' &&
DISABLE_WHATSAPP_COUNTRY_CODE.includes(countryCode)
)) {
destinationFlag(true);
return;
} else {
Expand Down
10 changes: 7 additions & 3 deletions apps/nativeapp/app/constants/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ const POINT_RADIUS_ARR = [
{name: 'Within 1 km', value: 1000},
];

// Excluded countries for sms type alert methods
const EXCLUDED_COUNTRIES = [
// Disable sms and whatsapp alert methods for some countries
const DISABLE_SMS_COUNTRY_CODE = [
'RU',
'TJ',
'MG',
Expand All @@ -30,4 +30,8 @@ const EXCLUDED_COUNTRIES = [
'BZ',
];

export {WEB_URLS, RADIUS_ARR, POINT_RADIUS_ARR, EXCLUDED_COUNTRIES};
const DISABLE_WHATSAPP_COUNTRY_CODE = [
'IN'
]

export {WEB_URLS, RADIUS_ARR, POINT_RADIUS_ARR, DISABLE_SMS_COUNTRY_CODE, DISABLE_WHATSAPP_COUNTRY_CODE};
2 changes: 1 addition & 1 deletion apps/nativeapp/app/screens/Login/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ const Login = () => {
prompt: 'login',
audience: 'urn:plant-for-the-planet',
},
{ephemeralSession: false},
{ephemeralSession: false, useLegacyCallbackUrl: true},
)
.then(cred => {
const request = {
Expand Down
15 changes: 8 additions & 7 deletions apps/nativeapp/app/screens/Settings/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ import {
TrashOutlineIcon,
VerificationWarning,
DisabledTrashOutlineIcon,
WhatsAppIcon
} from '../../assets/svgs';
import {trpc} from '../../services/trpc';
import {Colors, Typography} from '../../styles';
Expand Down Expand Up @@ -449,11 +450,11 @@ const Settings = ({navigation}) => {
};

// ----------------- handle whatsapp, and Geostationary
// const handleAddWhatsapp = () => {
// navigation.navigate('Verification', {
// verificationType: 'Whatsapp',
// });
// };
const handleAddWhatsapp = () => {
navigation.navigate('Verification', {
verificationType: 'Whatsapp',
});
};

// const handleGeostationary = val => {
// let detectionMethods = [...userDetails?.data?.detectionMethods];
Expand Down Expand Up @@ -902,7 +903,7 @@ const Settings = ({navigation}) => {
)}
</View>
{/* whatsapp */}
{/* <View style={styles.mySiteNameMainContainer}>
<View style={styles.mySiteNameMainContainer}>
<View style={styles.mySiteNameSubContainer}>
<View style={styles.mobileContainer}>
<WhatsAppIcon />
Expand Down Expand Up @@ -966,7 +967,7 @@ const Settings = ({navigation}) => {
))}
</View>
)}
</View> */}
</View>
{/* sms */}
<View style={styles.mySiteNameMainContainer}>
<View style={styles.mySiteNameSubContainer}>
Expand Down
16 changes: 14 additions & 2 deletions apps/nativeapp/app/screens/Verification/Verification.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,21 @@ const Verification = ({navigation, route}) => {
) {
return toast.show('Incorrect Number', {type: 'warning'});
}
if (verificationType === 'Sms' && limitDestination) {
if (
(verificationType === 'Sms' && limitDestination)
) {
return toast.show(
`Apologies, sms services to your region are currently unsupported. Please select a different method.`,
{
type: 'warning',
},
);
}
if (
(verificationType === 'Whatsapp' && limitDestination)
) {
return toast.show(
'Destination is restricted due to country limitations',
`Meta's API change in India affects delivery of FireAlerts over WhatsApp. Please select a different method.`,
{
type: 'warning',
},
Expand Down
4 changes: 2 additions & 2 deletions apps/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
"nodemailer": "^6.9.1",
"pg-promise": "^11.4.3",
"phone": "^3.1.37",
"prisma": "^5.0.0",
"prisma": "^5.10.2",
"react": "^18.2.0",
"react-cookie": "^4.1.1",
"react-dom": "^18.2.0",
Expand All @@ -65,7 +65,7 @@
"@typescript-eslint/parser": "^5.53.0",
"eslint": "^8.34.0",
"eslint-config-next": "^13.5.4",
"prisma": "^5.0.0",
"prisma": "^5.10.2",
"tsconfig": "*",
"typescript": "^5.0.3"
},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
-- Site View
CREATE OR REPLACE VIEW view_site AS
SELECT
"id",
"name",
"type",
"radius",
"isMonitored",
"userId",
"slices"
FROM
"Site"
WHERE
"deletedAt" IS NULL;

-- SiteAlert View
CREATE OR REPLACE VIEW view_siteAlert AS
SELECT
"id",
"siteId",
"type",
"latitude",
"longitude",
"eventDate",
"detectedBy",
"confidence"
FROM
"SiteAlert"
WHERE
"deletedAt" IS NULL;
2 changes: 1 addition & 1 deletion apps/server/src/Services/Notifier/Notifier/SMSNotifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class SMSNotifier implements Notifier {
}

// If the destination is a restricted Country, return false, log error.
if (isPhoneNumberRestricted(destination)) {
if (isPhoneNumberRestricted('sms', destination)) {
// If destination is a restricted phone number
// Then, notification was created before FireAlert introduced SMS Restriction
// Thus, notification must be deleted, so that it is not constantly marked as "not-delivered"
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/pages/api/cron/db-cleanup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ function shouldContinueDeletion(startTime: number, type_of_cleanup:string = 'dat
async function updateOrCreateStats(metric: string, count: number) {
await prisma.stats.upsert({
where: {metric: metric},
update: {count: {increment: count}},
update: {count: {increment: count}, lastUpdated: new Date()},
create: {
metric: metric,
count: count,
Expand Down
18 changes: 9 additions & 9 deletions apps/server/src/pages/api/tests/whatsapp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,22 +40,22 @@ export default async function testWhatsApp(req: NextApiRequest, res: NextApiResp
const notificationParameters_alert: NotificationParameters = {
message: "Fire detected inside Las Americas 7A",
subject: "FireAlert",
url: "https://firealert.plant-for-the-planet.org/alert/ed1cf199-6c3a-4406-bac0-eb5519391e2e",
url: "https://firealert.plant-for-the-planet.org/alert/6769f0f5-86cf-4cea-ba27-6e2dc4b58376",
id: "notificationId",
authenticationMessage: true,
otp: "12345",
siteName: 'Las Americas',
// authenticationMessage: true,
// otp: "12345",
siteName: 'PROBOSQUE 22',
alert:{
id: "ed1cf199-6c3a-4406-bac0-eb5519391e2e",
id: "6769f0f5-86cf-4cea-ba27-6e2dc4b58376",
type: 'fire',
confidence: 'high',
source: "TEST",
date: new Date(),
longitude: 80.45728,
latitude: 66.66537,
longitude: -100.12768,
latitude: 18.72452,
distance: 0,
siteId: "siteId1",
siteName: "SiteName",
siteId: "clikwjyg1004ymk0egij2a716",
siteName: "PROBOSQUE 22",
data: {},
}
};
Expand Down
35 changes: 31 additions & 4 deletions apps/server/src/server/api/routers/alertMethod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export const alertMethodRouter = createTRPCRouter({
const destination = alertMethod.destination
const method = alertMethod.method
if(method === 'sms'){
if (isPhoneNumberRestricted(destination)) {
if (isPhoneNumberRestricted('sms', destination)) {
throw new TRPCError({
code: 'UNAUTHORIZED',
message: `Cannot Verify AlertMethod. ${destination} is restricted due to country limitations.`,
Expand Down Expand Up @@ -175,11 +175,27 @@ export const alertMethodRouter = createTRPCRouter({
if (isDeviceVerified) {

// Check if the destination (PlayerID) already exists in the table
// Retrieve alert methods that match the destination or (userId and deviceName)
const existingAlertMethods = await ctx.prisma.alertMethod.findMany({
where: {
destination: input.destination
OR: [
{destination: input.destination},
// Checks for duplicates by deviceId for all devices (returns duplicate ios devices)
{ deviceId: input.deviceId },
// Checks for devices with the same name but different deviceId for the same user
// We need NOT on deviceId to prevent selecting ios devices (ios deviceNames are not unique)
// (returns duplicate android devices)
{
AND: [
{ userId: userId },
{ deviceName: input.deviceName },
{ deviceId: { not: input.deviceId } }
]
}
]
}
});


// If it does exist and is associated with a different userId, delete it
for (const existingAlertMethod of existingAlertMethods) {
Expand Down Expand Up @@ -218,11 +234,22 @@ export const alertMethodRouter = createTRPCRouter({
// If Method is sms, restrict phone number to only allowed countries
if(input.method === 'sms'){
// Check if the destination falls inside of accepted countries
const isDestinationAccepted = !isPhoneNumberRestricted(input.destination);
const isDestinationAccepted = !isPhoneNumberRestricted('sms', input.destination);
if(isDestinationAccepted === false){
throw new TRPCError({
code: 'BAD_REQUEST',
message: `Phone number is restricted due to country limitations.`,
});
}
}
// If Method is whatsapp, restrict phone number to only allowed countries
if(input.method === 'whatsapp'){
// Check if the destination falls inside of accepted countries
const isDestinationAccepted = !isPhoneNumberRestricted('whatsapp', input.destination);
if(isDestinationAccepted === false){
throw new TRPCError({
code: 'BAD_REQUEST',
message: `Destination is restricted due to country limitations`,
message: `Phone number is restricted due to country limitations.`,
});
}
}
Expand Down
55 changes: 29 additions & 26 deletions apps/server/src/server/api/routers/site.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,32 +14,6 @@ export const siteRouter = createTRPCRouter({
.input(createSiteSchema)
.mutation(async ({ctx, input}) => {
const userId = ctx.user!.id;
// const userPlan = ctx.user!.plan ? ctx.user!.plan as UserPlan : 'basic';
// const siteCount = await ctx.prisma.site.count({
// where:{
// userId,
// }
// })
// if(userPlan === 'basic'){
// if (siteCount >= 20){
// return {
// status: 'error',
// httpStatus: 403,
// code: 'FORBIDDEN',
// message: `You've exceeded the fair site use limits of FireAlert. Please contact info@plant-for-the-planet to remove these limits for your account.`,
// };
// }
// }
// if(userPlan === 'custom'){
// if (siteCount >= 50){
// return {
// status: 'error',
// httpStatus: 403,
// code: 'FORBIDDEN',
// message: `You've exceeded the fair site use limits of FireAlert. You cannot create any more sites.`,
// };
// }
// }
try {
const origin = 'firealert';
const lastUpdated = new Date();
Expand All @@ -54,6 +28,35 @@ export const siteRouter = createTRPCRouter({
radius = input.radius;
}

// Convert geometry to GeoJSON string for PostGIS function
const geometryGeoJSON = JSON.stringify(input.geometry);

// Calculate detection area using PostGIS
const result = await ctx.prisma.$queryRaw`SELECT ST_Area(
ST_Transform(
ST_Buffer(
ST_Transform(
ST_SetSRID(
ST_GeomFromGeoJSON(${geometryGeoJSON}::text),
4326
),
3857
),
${input.radius}
),
3857
)
) AS area`;

const detectionArea = result[0].area; // Assuming result is an array with the area as its first item

// Check if the detection area exceeds 1 million hectares (10,000 square kilometers)
if (detectionArea > 1e10) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: 'Site area exceeds the maximum allowed size of 1 million hectares.',
});
}
const site = await ctx.prisma.site.create({
data: {
origin: origin,
Expand Down
6 changes: 0 additions & 6 deletions apps/server/src/server/api/zodSchemas/site.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,6 @@ const PolygonSchema = z.object({
coordinates: z.array(z.array(z.union([z.tuple([z.number(), z.number()]), z.tuple([z.number(), z.number(), z.optional(z.number())])])))
});


// const MultiPolygonSchema = z.object({
// type: z.literal("MultiPolygon"),
// coordinates: z.array(z.array(z.union([z.tuple([z.number(), z.number()]), z.tuple([z.number(), z.number(), z.optional(z.number())])])))
// });

const MultiPolygonSchema = z.object({
type: z.literal("MultiPolygon"),
coordinates: z.array(
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/utils/notification/emailTemplateString.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,8 +211,8 @@ table, td { color: #4f4f4f; } #u_body a { color: #e86f56; text-decoration: none;

<div style="font-size: 12px; line-height: 130%; text-align: center; word-wrap: break-word;">
<p style="line-height: 130%;">You can manage all email notification preference in the FireAlert app. (<a href="https://play.google.com/store/apps/details?id=eco.pp.firealert">Android</a> | <a href="https://apps.apple.com/app/fire-alert-for-forests/id1667307676">iOS</a>)<br /><br />FireAlert <em>by <a href="https://plant-for-the-planet.org">Plant-for-the-Planet</a></em></p>
<p style="line-height: 100%;">Am Bahnhof 1,</p>
<p style="line-height: 100%;">Uffing Am Staffelsee, 82449</p>
<p style="line-height: 100%;">Lindemannstr. 13,</p>
<p style="line-height: 100%;">Tutzing, 82327</p>
<p style="line-height: 100%;">Germany</p>
<p style="line-height: 100%;"> </p>
<p style="line-height: 130%;"><a rel="noopener" href="https://www.plant-for-the-planet.org/firealert" target="_blank">About FireAlert</a> | Follow us at <a rel="noopener" href="https://twitter.com/trilliontrees" target="_blank">@trilliontrees</a></p>
Expand Down
Loading
Loading