Nessuna descrizione

models.py 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. #from django.db import models
  2. from django.contrib.gis.db import models
  3. from django_google_maps import fields as map_fields
  4. from colorfield.fields import ColorField
  5. #from smart_selects.db_fields import GroupedForeignKey
  6. from smart_selects.db_fields import (
  7. ChainedForeignKey,
  8. ChainedManyToManyField,
  9. GroupedForeignKey,
  10. )
  11. import googlemaps
  12. from django.contrib.gis.geos import fromstr
  13. from django.conf import settings
  14. import csv
  15. gmaps = googlemaps.Client(key=settings.GOOGLE_MAPS_API_KEY)
  16. # Create your models here.
  17. GENDER_CHOICES = (
  18. ('นางสาว','นางสาว'),
  19. ('นาย','นาย'),
  20. ('นาง', 'นาง'),
  21. ("ด.ช.","เด็กชาย"),
  22. ("ด.ญ.","เด็กหญิง"),
  23. )
  24. class Ambulance(models.Model):
  25. code = models.CharField(max_length=100)
  26. license_plate = models.CharField(max_length=100)
  27. brand = models.CharField(max_length=100)
  28. model_name = models.CharField(max_length=100)
  29. comment = models.TextField(blank=True, null=True)
  30. color = ColorField(default='#FF0000')
  31. status = models.CharField(
  32. max_length=30,
  33. choices=(("working", "Working"), ("free", "Free"), ("ma", "MA")),
  34. null=True,
  35. )
  36. created_at = models.DateTimeField(auto_now_add=True, null=True)
  37. updated_at = models.DateTimeField(auto_now=True)
  38. def __str__(self):
  39. return f"{self.license_plate} ({self.get_status_display()}) {self.code} {self.brand} / {self.model_name}"
  40. class Driver(models.Model):
  41. first_name = models.CharField(max_length=100)
  42. last_name = models.CharField(max_length=100)
  43. age = models.IntegerField()
  44. idcard = models.CharField(max_length=20, null=True, blank=False)
  45. prefix = models.CharField(
  46. max_length=30,
  47. choices=GENDER_CHOICES,
  48. null=True,
  49. )
  50. sex = models.CharField(
  51. max_length=30,
  52. choices=(("male", "Male"), ("female", "Female"),),
  53. null=True,
  54. )
  55. photo = models.FileField(upload_to="uploads/%Y/%m/%d/", blank=True, verbose_name="Photo")
  56. address = models.TextField(blank=True, null=True)
  57. #test
  58. status = models.CharField(
  59. max_length=30,
  60. choices=(("working", "Working"), ("free", "Free"), ("block", "Block")),
  61. null=True,
  62. )
  63. created_at = models.DateTimeField(auto_now_add=True, null=True)
  64. updated_at = models.DateTimeField(auto_now=True)
  65. def __str__(self):
  66. return f"{self.first_name} {self.last_name} ({self.get_status_display()})"
  67. class AmbulanceTicket(models.Model):
  68. driver = models.ForeignKey(Driver, on_delete=models.SET_NULL, null=True)
  69. ambulance = models.ForeignKey(Ambulance, on_delete=models.SET_NULL, null=True)
  70. status = models.CharField(
  71. max_length=30,
  72. choices=(("working", "Working"), ("free", "Free"), ("ma", "MA")),
  73. null=True,
  74. )
  75. checkin_at = models.DateTimeField(null=True, blank=True)
  76. checkout_at = models.DateTimeField(null=True, blank=True)
  77. created_at = models.DateTimeField(auto_now_add=True, null=True)
  78. updated_at = models.DateTimeField(auto_now=True)
  79. def save(self, *args, **kwargs):
  80. super(AmbulanceTicket, self).save(*args, **kwargs)
  81. self.ambulance.status = self.status
  82. self.ambulance.save()
  83. self.driver.status = "working"
  84. self.driver.save()
  85. def __str__(self):
  86. return f"{self.driver}@{self.ambulance}"
  87. class Patient(models.Model):
  88. first_name = models.CharField(max_length=100)
  89. last_name = models.CharField(max_length=100)
  90. age = models.IntegerField()
  91. idcard = models.CharField(max_length=20, null=True, blank=False)
  92. prefix = models.CharField(
  93. max_length=30,
  94. choices=GENDER_CHOICES,
  95. null=True,
  96. )
  97. sex = models.CharField(
  98. max_length=30,
  99. choices=(("male", "Male"), ("female", "Female"),),
  100. null=True,
  101. )
  102. photo = models.FileField(upload_to="uploads/%Y/%m/%d/", blank=True, verbose_name="Photo")
  103. address = map_fields.AddressField(max_length=200, null=True)
  104. geolocation = map_fields.GeoLocationField(max_length=100, null=True)
  105. condition_level = models.CharField(
  106. max_length=30,
  107. choices=(("green", "Green"), ("yellow", "Yellow"), ("red", "Red")),
  108. null=True,
  109. )
  110. comment = models.TextField(blank=True, null=True)
  111. #test
  112. def __str__(self):
  113. #self.nearby()
  114. return f"{self.first_name} {self.last_name}"
  115. def nearby(self):
  116. r = gmaps.places_nearby(location=(self.geolocation.lat, self.geolocation.lon), type="hospital", radius=10000)
  117. bd = ""
  118. for r0 in r['results']:
  119. openh = "-"
  120. if 'opening_hours' in r0:
  121. openh = r0['opening_hours']['open_now']
  122. else:
  123. openh = "-"
  124. bd += f"<tr><td>{r0['name']}</td><td>{openh}</td><td>{r0['vicinity']}</td></tr>"
  125. rt = f'''
  126. <br>
  127. <table><thead><tr><th>Name</th><th>Opening Hours</th><th>Vicinity</th></tr></thead>
  128. <tbody>
  129. {bd}
  130. </tbody>
  131. </table>
  132. '''
  133. return rt
  134. class ImportFile(models.Model):
  135. hospital_file = models.FileField(upload_to="uploads/%Y/%m/%d/", blank=True, verbose_name="Hospital (csv)")
  136. def save(self, *args, **kwargs):
  137. super(ImportFile, self).save(*args, **kwargs)
  138. with self.hospital_file.open('r') as csv_file:
  139. csv_reader = csv.reader(csv_file, delimiter=',')
  140. Hospital.objects.all().delete()
  141. line_count = 0
  142. for r in csv_reader:
  143. if line_count > 0:
  144. print(r)
  145. print(f"{r[7]},{r[6]}")
  146. try:
  147. gp = map_fields.GeoPt(lat=float(r[6]), lon=float(r[7]))
  148. location = fromstr(f'POINT({r[7]} {r[6]})', srid=4326)
  149. print(location)
  150. h = Hospital(title=r[3], address_text=r[5], geolocation=gp, address=r[3])
  151. h.save()
  152. except Exception as e:
  153. print(e)
  154. line_count += 1
  155. class Place(models.Model):
  156. #title = models.Char
  157. title = models.CharField(max_length=200, blank=True, null=True)
  158. address = map_fields.AddressField(max_length=200)
  159. geolocation = map_fields.GeoLocationField(max_length=100)
  160. created_at = models.DateTimeField(auto_now_add=True, null=True)
  161. updated_at = models.DateTimeField(auto_now=True)
  162. more_info = models.JSONField(null=True, blank=True)
  163. def __str__(self):
  164. return f"{self.address} ({self.geolocation})"
  165. class Points(models.Model):
  166. #src = models.ForeignKey(Place, on_delete=models.SET_NULL, null=True, blank=False, related_name='src')
  167. dest = models.ForeignKey(Place, on_delete=models.SET_NULL, null=True, blank=False, related_name='dest')
  168. address = map_fields.AddressField(max_length=200, null=True)
  169. geolocation = map_fields.GeoLocationField(max_length=100, null=True)
  170. distance = models.DecimalField(null=True, blank=True, decimal_places=2, max_digits=7, verbose_name="Distance (km)")
  171. duration = models.CharField(max_length=200, null=True, blank=True)
  172. directions = models.JSONField(null=True, blank=True)
  173. def save(self, *args, **kwargs):
  174. geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA')
  175. print(geocode_result)
  176. print(self.geolocation)
  177. origin = [(self.geolocation.lat, self.geolocation.lon)]
  178. dest = [(self.dest.geolocation.lat, self.dest.geolocation.lon)]
  179. dst = gmaps.distance_matrix(origin, dest)
  180. dirs = gmaps.directions(origin[0], dest[0])
  181. self.directions = dirs
  182. print(dirs)
  183. self.distance = dst['rows'][0]['elements'][0]['distance']['value'] / 1000
  184. self.duration = dst['rows'][0]['elements'][0]['duration']['text']
  185. print(dst)
  186. super(Points, self).save(*args, **kwargs)
  187. class Hospital(models.Model):
  188. title = models.CharField(max_length=200)
  189. location = models.PointField(blank=True, null=True)
  190. address_text = models.TextField(blank=True, null=True)
  191. #address = models.CharField(max_length=100)
  192. address = map_fields.AddressField(max_length=200)
  193. geolocation = map_fields.GeoLocationField(max_length=100)
  194. created_at = models.DateTimeField(auto_now_add=True, null=True)
  195. updated_at = models.DateTimeField(auto_now=True)
  196. def __str__(self):
  197. return f"{self.title} {self.address_text}"
  198. class Bed(models.Model):
  199. code = models.CharField(max_length=30)
  200. occupy = models.BooleanField(default=False)
  201. patient = models.ForeignKey(Patient, on_delete=models.SET_NULL, null=True, blank=True)
  202. hospital = models.ForeignKey(Hospital, on_delete=models.CASCADE)
  203. created_at = models.DateTimeField(auto_now_add=True, null=True)
  204. updated_at = models.DateTimeField(auto_now=True)
  205. def __str__(self):
  206. return self.code
  207. class PatientLog(models.Model):
  208. patient = models.ForeignKey(Patient, on_delete=models.SET_NULL, null=True)
  209. hospital = models.ForeignKey(Hospital, on_delete=models.CASCADE, null=True)
  210. bed = ChainedForeignKey(
  211. "Bed",
  212. chained_field="hospital",
  213. chained_model_field="hospital",
  214. show_all=False,
  215. auto_choose=True,
  216. null=True
  217. )
  218. notes = models.TextField(blank=True, null=True)
  219. condition_level = models.CharField(
  220. max_length=30,
  221. choices=(("green", "Green"), ("yellow", "Yellow"), ("red", "Red")),
  222. null=True,
  223. )
  224. status = models.CharField(
  225. max_length=30,
  226. choices=(("active", "Active"), ("inactive", "Inactive"), ("transfer", "Transfer")),
  227. null=True,
  228. )
  229. checkin_at = models.DateTimeField(null=True, blank=True)
  230. checkout_at = models.DateTimeField(null=True, blank=True)
  231. created_at = models.DateTimeField(auto_now_add=True, null=True)
  232. updated_at = models.DateTimeField(auto_now=True)