Skip to content

Commit

Permalink
mid-fix: call logs post is logging
Browse files Browse the repository at this point in the history
  • Loading branch information
Naveen-g09 committed Jan 12, 2024
1 parent 652aa21 commit ef039dd
Show file tree
Hide file tree
Showing 5 changed files with 94 additions and 44 deletions.
3 changes: 2 additions & 1 deletion app/(tabs)/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
getCallLogs,
postCallLogs,
updateTask,
sync,
} from "../../lib/db_helpers";
import { Task } from "../../lib/types";

Expand All @@ -31,13 +32,13 @@ export default function TabOneScreen() {
const handleRefresh = useCallback(async () => {
setRefreshing(true);
await fetchTasks();
// await postAndSyncCallLogs();
setRefreshing(false);
}, []);

useEffect(() => {
fetchTasks();
getCallLogs();
sync();
const intervalId = setInterval(() => {
fetchTasks();
}, 30 * 1000);
Expand Down
51 changes: 35 additions & 16 deletions app/settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,36 @@ import React, { useState } from "react";
import { TextInput } from "react-native";

import { Text, View } from "../components/Themed";
interface ModalScreenState {
phoneNumber: string;
isEditing: boolean;
user: any;
}

export default function ModalScreen() {
const [phoneNumber, setPhoneNumber] = useState("");
const [isEditing, setIsEditing] = useState(true);
const [user, setUser] = useState(null);
const ModalScreen: React.FC = () => {
const [state, setState] = useState<ModalScreenState>({
phoneNumber: "",
isEditing: true,
user: null,
});

const savePhoneNumber = () => {
setUser({phoneNumber,});
setIsEditing(false);
setState((prevState) => ({
...prevState,
user: { phoneNumber: prevState.phoneNumber },
isEditing: false,
}));
};

const editPhoneNumber = () => {
setIsEditing(true);
setState((prevState) => ({
...prevState,
isEditing: true,
}));
};

console.log("user", user);
console.log("user", state.user);

return (
<View className="flex-1 items-center justify-center">
<Text className="text-2xl font-bold">Settings</Text>
Expand All @@ -27,28 +42,32 @@ export default function ModalScreen() {
darkColor="rgba(255,255,255,0.1)"
/>

{/* Input field for the phone number */}
<TextInput
className="h-10 border border-blue-300 p-2 mb-4"
placeholder="Enter your phone number"
keyboardType="phone-pad"
value={phoneNumber}
onChangeText={(text) => setPhoneNumber(text)}
editable={isEditing}
value={state.phoneNumber}
onChangeText={(text) =>
setState((prevState) => ({ ...prevState, phoneNumber: text }))
}
editable={state.isEditing}
/>

{/* Save/Edit button */}
<Text
className={`bg-blue-500 text-white p-2 rounded ${
isEditing ? "" : "opacity-50"
state.isEditing ? "" : "opacity-50"
}`}
onPress={isEditing ? savePhoneNumber : editPhoneNumber}
onPress={state.isEditing ? savePhoneNumber : editPhoneNumber}
>
{isEditing ? "Save Phone Number" : "Edit Phone Number"}
{state.isEditing ? "Save Phone Number" : "Edit Phone Number"}
</Text>

{/* Use a light status bar on iOS to account for the black space above the modal */}
<StatusBar style="auto" />
</View>
);
}
};

export default ModalScreen;
export const phoneNumber = ModalScreen.phoneNumber;
50 changes: 31 additions & 19 deletions lib/db_helpers.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import CallLogs from "react-native-call-log";

import { checkPermission } from "../lib/permissions";
import { checkPermission, loadCallLogs } from "../lib/permissions";

const getContactNumbers = async () => {
try {
const response = await fetch(
"https://worker-turso-ts.technoculture.workers.dev/tasks",
);
const tasks = await response.json();
console.log("Tasks fetched successfully", tasks);

const contactNumbers = tasks.map((task: any) => task.contactNumber);
return contactNumbers;
} catch (error) {
Expand All @@ -20,15 +18,16 @@ const getContactNumbers = async () => {

const getCallLogs = async () => {
try {
if (!(await checkPermission())) return [];
await checkPermission();
await loadCallLogs();
const callLogs = await CallLogs.loadAll();
console.log("Call logs fetched successfully", callLogs);
console.log("Call logs fetched successfully:", callLogs);
return callLogs;
} catch (error) {
console.error("Error fetching call logs:", error);
return [];
}
};

const getTasks = async () => {
try {
const response = await fetch(
Expand All @@ -43,28 +42,17 @@ const getTasks = async () => {

const postCallLogs = async (callLogs: any) => {
try {
const formattedCallLogs = callLogs.map((log: any) => {
return {
taskId: log.taskId,
callTime: log.timestamp,
callStatus: log.callType,
duration: log.duration,
};
});

const response = await fetch(
"https://worker-turso-ts.technoculture.workers.dev/call-logs",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(formattedCallLogs),
body: JSON.stringify(callLogs),
},
);

console.log("Call logs posted successfully:", response);
return response;
} catch (error) {
console.error("Error posting call logs:", error);
}
Expand Down Expand Up @@ -93,4 +81,28 @@ const updateTask = async (taskId: number) => {
}
};

export { getCallLogs, getTasks, postCallLogs, getContactNumbers, updateTask };
const sync = async () => {
try {
const callLogs = await getCallLogs();
await postCallLogs(callLogs);
const tasks = await getTasks();
const contactNumbers = await getContactNumbers();
const tasksToBeUpdated = tasks.filter((task: any) =>
contactNumbers.includes(task.contactNumber),
);
for (const task of tasksToBeUpdated) {
await updateTask(task.id);
}
} catch (error) {
console.error("Error syncing:", error);
}
};

export {
getCallLogs,
getTasks,
postCallLogs,
getContactNumbers,
updateTask,
sync,
};
19 changes: 11 additions & 8 deletions lib/permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@ import CallLogs from "react-native-call-log";

import { getContactNumbers } from "../lib/db_helpers";

const loadCallLogs = async () => {
const contactNumbers = await getContactNumbers();
const filter = {
phoneNumbers: contactNumbers,
};
CallLogs.load(-1, filter).then((callLogs) => console.log(callLogs));
};

const checkPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
Expand All @@ -16,13 +24,8 @@ const checkPermission = async () => {
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
const contactNumbers = await getContactNumbers();
const filter = {
phoneNumbers: contactNumbers,
};

// Load call logs using the filter
CallLogs.load(-1, filter).then((callLogs) => console.log(callLogs));
console.log("Call Log permission granted");
loadCallLogs();
} else {
console.log("Call Log permission denied");
}
Expand All @@ -31,4 +34,4 @@ const checkPermission = async () => {
}
};

export { checkPermission };
export { checkPermission, loadCallLogs };
15 changes: 15 additions & 0 deletions worker-turso-ts/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ console.log(buildLibsqlClient);
function buildRouter(env: Env): RouterType {
const router = Router();

//add user endpoint to url so that we can use the same worker for multiple users
//fetch user from settings page
router.get('/tasks', async () => {
const client = buildLibsqlClient(env);
const rs = await client.execute('select * from tasks');
Expand All @@ -58,8 +60,21 @@ function buildRouter(env: Env): RouterType {
router.post('/call-logs', async (request) => {
try {
const client = buildLibsqlClient(env);
const contentType = request.headers.get('content-type');

if (!contentType || contentType.indexOf('application/json') !== 0) {
// Ensure the request has the correct content type
throw new Error('Invalid content type. Expected application/json.');
}

const jsonBody = await request.json();

if (!jsonBody || typeof jsonBody !== 'object') {
throw new Error('Invalid JSON format in the request body.');
}

console.log('Parsed Request Body:', jsonBody);

const rs = await client.execute({
sql: 'insert into callLogs (taskId, callTime, callStatus, duration) values (?, ?, ?, ?)',
args: [jsonBody.taskId, jsonBody.callTime, jsonBody.callStatus, jsonBody.duration],
Expand Down

0 comments on commit ef039dd

Please sign in to comment.