Untitled

 avatar
unknown
plain_text
3 years ago
14 kB
4
Indexable
//main.js

/*const electron = require("electron");
const url = require("url");
const path = require("path");*/

const {app,BrowserWindow,ipcMain,dialog} = require('electron');
const user = require('./models/user.js')
const kargo = require('./models/list.js')
const client = require('./models/client.js')


function createWindow(){
   const win= new BrowserWindow({
width:800,
height :700,
webPreferences :{
   nodeIntegration: true,
   contextIsolation:false,
   traceProcessWarnings:true
  },
    })
    win.loadFile('src/index.html')
}

function createWindow_1(){
   const mainWindow = new BrowserWindow({width:1400,height:1050,
     });

    mainWindow.loadFile('src/main.html' );}
    function createWindow_2(){
      const mainWindow = new BrowserWindow({width:1400,height:1050,
        webPreferences :{
          nodeIntegration: true,
          contextIsolation:false,
          traceProcessWarnings:true
         },
        });
    
       mainWindow.loadFile('src/kargolist.html' );}
       function createWindow_3(){
        const mainWindow = new BrowserWindow({width:1400,height:1050,
          webPreferences :{
            nodeIntegration: true,
            contextIsolation:false,
            traceProcessWarnings:true
           },
          });
      
         mainWindow.loadFile('src/client.html' );}
        
 
ipcMain.handle('new', async (e, arg) => {
const s = JSON.stringify(arg)
const f=JSON.parse(s)
   const newUser = new user(arg)
   const t = await user.find({email:f.email}).exec();
   const n = await user.find({name:f.name}).exec();
  
   if (  t.length !== 0) {
    dialog.showErrorBox('used-email','This  email is used!') 
 }
 else if( n.length !== 0){
  dialog.showErrorBox('This username is unavailable','Please choose another username!')
 } 
 else{
   const newUser = new user(arg)
    const userSaved = await newUser.save()
   console.log(userSaved)
  e.sender.send('new-user-created',JSON.stringify(userSaved))
  dialog.showErrorBox('new-user','New User Created')
 }
   
 })
 ipcMain.handle('not-new', async (e, arg) => {
  
    dialog.showErrorBox('Passwords do not match!','')  
   })

 ipcMain.handle('get-users', async (e, arg) => {
  const s = JSON.stringify(arg)
    const f=JSON.parse(s)
      const n = await user.find({name:f.name}).exec();
      const p = await user.find({pass:f.pass}).exec();
       if ( (!n || n.length === 0)||(!p || p.length === 0)) {
        dialog.showErrorBox('Username or Password is incorrect!','')
     }
     else {
 const tasks = await user.find(arg).exec();
e.sender.send('enter',createWindow_2())

 
     }
  });


  ipcMain.handle('update-user', async (e, arg) => {
    const s = JSON.stringify(arg)
    const f=JSON.parse(s)
      const t = await user.find({email:f.email}).exec();
      const n = await user.find({name:f.name}).exec();
      const p = await user.find({pass:f.pass}).exec();
       if ( !t || t.length === 0) {
        dialog.showErrorBox('This Email Is Not Registered!','')
     }
     else if( !n || n.length === 0){
      dialog.showErrorBox('Username is not correct!','')
    } 
    else if( !p || p.length === 0){
      dialog.showErrorBox('Password is not correct!','')
    }else{
   console.log(f.newpass)
    const updatedTask = await user.updateOne({ name:f.name},{pass:f.newpass})
      dialog.showErrorBox('Password has been changed successfully!','')}
   // e.sender.send("update-task-success", JSON.stringify(updatedTask));
  });


  ipcMain.handle('new-kargo', async (e, arg) => {
   
    
        const s = JSON.stringify(arg)
        const f=JSON.parse(s)
           const newKargo = new kargo(arg)
           const t = await kargo.find({clientName:f.clientName}).exec();
           const kargoSaved = await newKargo.save()
           console.log(kargoSaved)
          e.sender.send('new-kargo-created',JSON.stringify(kargoSaved))
         
     })


     
     ipcMain.handle('cl', async (e, arg) => {
     
      const tasks = await client.find({}).distinct('clientName');
    e.sender.send("get-tasks", JSON.stringify(tasks));
    });

    ipcMain.handle('get-list', async (e, arg) => {
     
      const tasks = await kargo.find();
    e.sender.send('send-list', JSON.stringify(tasks));
    });
    
  
  
  ipcMain.handle("update-kargo", async (e, args) => {
    console.log(args);
    const updatedKargo = await kargo.findByIdAndUpdate(
      args.idToUpdate,
      { clientName: args.clientName, address: args.address }
     ).exec();
    console.log(updatedKargo);
    e.sender.send("update-kargo-success", JSON.stringify(updatedKargo));
  });

  ipcMain.handle('delete-kargo', async (e, args) => {
    const kargoDeleted = await kargo.findByIdAndDelete(args);
    let options  = {
      buttons: ["Yes","No","Cancel"],
      message: "Do you really want to delete this record?"
     }
    dialog.showMessageBox(options).then(data=> {
     if (data.response === 0) {
console.log(data.response)
     
      e.sender.send("delete-kargo-success", JSON.stringify(kargoDeleted));    
 }  }).catch(err => {
      console.log(err)
   }); 
  
   
  });
  
ipcMain.handle('new-client', async (e, arg) => {
  const s = JSON.stringify(arg)
  const f=JSON.parse(s)
     const newClient = new client(arg)
     const t = await client.find({clientName:f.clientName}).exec();
    
     if (  t.length !== 0) {
      dialog.showErrorBox('','This  client is already registered!') 
   }
   
   else{
    
      const clientSaved = await newClient.save()
    
    e.sender.send('new-client-created',JSON.stringify(clientSaved))
    dialog.showErrorBox('new-client','New Client Entry')
   } })


module.exports= { createWindow_1,createWindow,createWindow_2, createWindow_3}
app.whenReady().then(createWindow) 

//kargolist.js

//const { Button } = require('bootstrap');

function initialize() {

	var mapOptions, map, marker, searchBox, 
		infoWindow = '',
		addressEl = document.querySelector( '#map-search' ),
		
		element = document.getElementById( 'map' );


	mapOptions = {
		// How far the maps zooms in.
		zoom: 15,
		center: new google.maps.LatLng( 40.765470, 29.940592 ),
		// Current Lat and Long position of the pin/
		
		// center : {
		// 	lat: -34.397,
		// 	lng: 150.644
		// },
		disableDefaultUI: false, // Disables the controls like zoom control on the map if set to true
		scrollWheel: true, // If set to false disables the scrolling on the map.
		draggable: true, // If set to false , you cannot move the map around.
		// mapTypeId: google.maps.MapTypeId.HYBRID, // If set to HYBRID its between sat and ROADMAP, Can be set to SATELLITE as well.
		// maxZoom: 11, // Wont allow you to zoom more than this
		// minZoom: 9  // Wont allow you to go more up.

	};

	/**
	 * Creates the map using google function google.maps.Map() by passing the id of canvas and
	 * mapOptions object that we just created above as its parameters.
	 *
	 */
	// Create an object map with the constructor function Map()
	map = new google.maps.Map( element, mapOptions ); // Till this like of code it loads up the map.

	/**
	 * Creates the marker on the map
	 *
	 */
	marker = new google.maps.Marker({
		position: mapOptions.center,
		map: map,
		// icon: 'http://pngimages.net/sites/default/files/google-maps-png-image-70164.png',
		draggable: true
	});

	/**
	 * Creates a search box
	 */
	searchBox = new google.maps.places.SearchBox( addressEl );

	/**
	 * When the place is changed on search box, it takes the marker to the searched location.
	 */
	google.maps.event.addListener( searchBox, 'places_changed', function () {
		var places = searchBox.getPlaces(),
			bounds = new google.maps.LatLngBounds(),
			i, place, resultArray,
			addresss = places[0].formatted_address;

		for( i = 0; place = places[i]; i++ ) {
			bounds.extend( place.geometry.location );
			marker.setPosition( place.geometry.location );  // Set marker position new.
		}

		map.fitBounds( bounds );  // Fit to the bound
		map.setZoom( 15 ); // This function sets the zoom to 15, meaning zooms to level 15.
		// console.log( map.getZoom() );

		

		resultArray =  places[0].address_components;

		// Get the city and set the city input value to the one selected
		

		// Closes the previous info window if it already exists
		if ( infoWindow ) {
			infoWindow.close();
		}
		/**
		 * Creates the info Window at the top of the marker
		 */
		infoWindow = new google.maps.InfoWindow({
			content: addresss
		});

		infoWindow.open( map, marker );
	} );


	/**
	 * Finds the new position of the marker when the marker is dragged.
	 */
	google.maps.event.addListener( marker, "dragend", function ( event ) {
		var  address, resultArray;

		console.log( 'i am dragged' );
		

		var geocoder = new google.maps.Geocoder();
		geocoder.geocode( { latLng: marker.getPosition() }, function ( result, status ) {
			if ( 'OK' === status ) {  // This line can also be written like if ( status == google.maps.GeocoderStatus.OK ) {
				address = result[0].formatted_address;
				resultArray =  result[0].address_components;

				// Get the city and set the city input value to the one selected
				
				addressEl.value = address;
				

			} else {
				console.log( 'Geocode was not successful for the following reason: ' + status );
			}

			// Closes the previous info window if it already exists
			if ( infoWindow ) {
				infoWindow.close();
			}

			/**
			 * Creates the info Window at the top of the marker
			 */
			infoWindow = new google.maps.InfoWindow({
				content: address
			});

			infoWindow.open( map, marker );
		} );

    	})
}
	const taskForm = document.querySelector("#taskForm");
	const c = document.querySelector("#client");
	const adres = document.querySelector('#map-search');
	const Liste = document.querySelector("#Liste");
	
	//var input=document.getElementById("adres");
	//var autocomplete=new google.maps.places.AutoComplete(input,options);
	const {ipcRenderer} = require('electron')
	let lists = [];
	ipcRenderer.invoke('get-list').then(()=> console.log('')).catch((err)=> console.error('Error'));
	ipcRenderer.on("send-list", (e, args) => {
		const receivedLists= JSON.parse(args);
		lists= receivedLists;
		renderList(lists);
	  });
	ipcRenderer.invoke('cl').then(()=> console.log('cl')).catch((err)=> console.error('Error'));
	ipcRenderer.on("get-tasks", (e, args) => {
	   const tasks = JSON.parse(args);
	for(var i = 0; i < tasks.length; i++) {
		var opt = tasks[i];
		var el = document.createElement("option");
		el.textContent = opt;
		el.value = opt;
	   c.appendChild(el);
	}});
	function deleteK(id) {
		
      ipcRenderer.invoke('delete-kargo',id).then(()=> console.log('cl')).catch((err)=> console.error('Error'));
    
    return;
  }
	  let idToUpdate = "";
	  let updateStatus = false;
	
	  function edit(id) {
		updateStatus = true;
		idToUpdate =id;
		const k = lists.find(k => k._id === id);
	   c.value = k.clientName;
	   adres.value =k.address;
	   adres.focus()
	  }

	function renderList(lists) {
		Liste.innerHTML = "";
		console.log(lists);
		lists.map(t => {
		  Liste.innerHTML += `
				<li class="card">
				<style display:inline-block>
	table, th, td {
	  border:1px solid black;
	  border-collapse: collapse;
	}
	</style>
				<div>
				<table style="width:70%">
				<tr>
				  <th>KargoId</th>
				  <th>MüşteriAdı</th> 
				  <th>Adres</th>
				</tr>
				<tr>
		<td>${t._id}</td>
		<td>${t.clientName}</td>
		<td>${t.address}</td>
	  <td>  <button onclick="edit('${t._id}')" />  ✎ Edit</td>
	  <td>  <button onclick="deleteK('${t._id}')" /> 🗑 Delete</td>
	  </tr>
			  
			  </table> </div>
				  
				 
				</li>
			  `;
		});
	  }
	  

	
				
			taskForm.reset()	
			  
	
	
	  
	 
	  
	taskForm.addEventListener("submit", async e => {
		e.preventDefault();
	  
		const list = {
			
		  clientName: c.value,
		  address: adres.value
		};
		if (!updateStatus) {
			ipcRenderer.invoke('new-kargo', list).then(()=> console.log('new kargo')).catch((err)=> console.error('Error'));
		  } else {
		   ipcRenderer.invoke("update-kargo", { ...list, idToUpdate }).then(()=> console.log('update kargo')).catch((err)=> console.error('Error'));;
		   
		  
		  }
	  taskForm.reset()
		  renderList(lists);
	
		 
		});
		renderList(lists)
	  
	  ipcRenderer.on("new-kargo-created", (e, arg) => {
		console.log(arg);
		const taskSaved = JSON.parse(arg);
		lists.push(taskSaved);
		
		renderList(lists);
		
		
	  });
	 
	  ipcRenderer.on("update-kargo-success", (e, args) => {
		updateStatus = false;
		
		const updatedkargo = JSON.parse(args);
	lists = lists.map((t, i) => {
		   
		  if (t._id === updatedkargo._id) {
		  
			t.clientName = updatedkargo.clientName;
			t.address = updatedkargo.address
		}
		return t;
	  });
	  renderList(lists);
	});
	
	ipcRenderer.on("delete-kargo-success", (e, args) => {
		const deletedKargo = JSON.parse(args);
		const newLists = lists.filter(t => {
		  return t._id !== deletedKargo._id;
		});
	   lists = newLists;
		renderList(lists);
	taskForm.reset()
	console.log("dd")
	  });
 
//kargolist.html

<!DOCTYPE html>
<html lang="en">
<head>
  
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="ui/list.css" />
    <title>List</title>
    <style>
      #map {
          height: 600px;
          width: 100%;
      }
  </style>
</head>
<body>
    <h2>Kargo Yönetim Sistemi</h2>
    
    <form id="taskForm" class="card">
        
      <label >Müşteri : </label><br>
      <select name="client" id="client" >
        <option >    </option>  
       
    </select>
    <a href="client.html">Add New Client</a>
    <br><br>
 <label for="">Address: <input id="map-search"  placeholder="Search Box" size="104"></label><br>

    <button type="submit" id="s" >Kargo Ekle
    </button>
  </form>


  <div id="map"></div>
  
    <script    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAn1m17AAhjM7pKbqe3lFNyqwZpuqMLUh4&libraries=places&callback=initialize"
    async    ></script>
            <h2>Kargo List</h2>
         
    <div>
      <ol id="Liste"></ol>
     
    </div>
    
           
            <script src="kargolist.js"></script>

  
</body>
</html>

Editor is loading...